next-server-middleware
TypeScript icon, indicating that this package has built-in type declarations

1.3.2 • Public • Published

Next Server Middleware

A simple type-safe express-like middleware for Next.js api routes using app directory and next/server.

Installation

npm install next-server-middleware

or

yarn add next-server-middleware

or

pnpm add next-server-middleware

Usage

  1. Create a middleware function

Similar to express, a middleware function is a function that takes a request and a next function and can affect the request and response. What's different is that we don't get the response as a parameter, but only get it after awaiting next, which is in line with how new Next.js api routes work.

// withLogging.ts
export const withLogging = (): Middleware<NextRequest, NextRequest> => async (request, next) => {
  const endpointName = `${request.method} ${request.nextUrl.pathname}`
  console.log(`API request: ${endpointName}`)
  const response = await next(request)
  console.log(`API response: ${endpointName} ${response.status}`)
  return response
}
  1. Add middlewares to your api route using withMiddlewares
// app/api/hello.ts
import { withMiddlewares } from 'next-server-middleware'

import { withLogging } from './withLogging'

export const GET = withMiddlewares(
  withLogging(), 
  (request) =>  NextResponse.json({hello: 'world',})
)

Example middlewares

Package Sidebar

Install

npm i next-server-middleware

Weekly Downloads

0

Version

1.3.2

License

MIT

Unpacked Size

30.3 kB

Total Files

30

Last publish

Collaborators

  • antomics