Next.js Discord

Discord Forum

Multi Middleware

Answered
Tan posted this in #help-forum
Open in Discord
TanOP
How can I create more than one middleware ?

is there a docs about this ?
Answered by B33fb0n3
currently there is no way to define multiple middlewares. However you can create one middleware and put your functions and stuff that you want to do inside thie one middleware. You can even go crazy and make something like this:
import { NextResponse } from 'next/server'
import type { NextRequest } from 'next/server'
 
// This function can be marked `async` if using `await` inside
export function middleware(request: NextRequest) {
  middleware1();
  middleware2();
  middleware3();
// ...

  return NextResponse.redirect(new URL('/home', request.url))
}
 
// See "Matching Paths" below to learn more
export const config = {
  matcher: '/about/:path*',
}
View full answer

3 Replies

@Tan How can I create more than one middleware ? is there a docs about this ?
currently there is no way to define multiple middlewares. However you can create one middleware and put your functions and stuff that you want to do inside thie one middleware. You can even go crazy and make something like this:
import { NextResponse } from 'next/server'
import type { NextRequest } from 'next/server'
 
// This function can be marked `async` if using `await` inside
export function middleware(request: NextRequest) {
  middleware1();
  middleware2();
  middleware3();
// ...

  return NextResponse.redirect(new URL('/home', request.url))
}
 
// See "Matching Paths" below to learn more
export const config = {
  matcher: '/about/:path*',
}
Answer