Skip to content

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

License

Notifications You must be signed in to change notification settings

antonmihaylov/next-server-middleware

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

16 Commits
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 

Repository files navigation

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

About

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

Topics

Resources

License

Stars

Watchers

Forks

Releases

No releases published

Packages

No packages published