Home > Software engineering >  Next.js middleware matcher negate path
Next.js middleware matcher negate path

Time:08-20

I have a middleware on a Next.js project, and I want to negate my /api/* route.

In other words, I want middleware to run for every route except anything that starts with /api/. I couldn't find an example in the docs.

How do I achieve that (of course, without writing all included routes one by one)?

CodePudding user response:

You cannot do this with matcher, because it only accepts simple path patterns, therefore you'll need to use conditional statement:

export function middleware(request: NextRequest) {
 if (request.nextUrl.pathname.startsWith('/api/')) {
   return NextResponse.next()
 }

 // your middleware logic
}
  • Related