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)?
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)?
Share Improve this question edited Aug 22, 2022 at 8:25 jedrzej.kurylo 40.9k10 gold badges106 silver badges112 bronze badges asked Aug 19, 2022 at 10:41 Can PoyrazoğluCan Poyrazoğlu 34.8k54 gold badges206 silver badges423 bronze badges3 Answers
Reset to default 14Looks like the middleware docs have been updated to account for something like this.
nextjs middleware docs
export const config = {
matcher: [
/*
* Match all request paths except for the ones starting with:
* - api (API routes)
* - static (static files)
* - favicon.ico (favicon file)
*/
'/((?!api|static|favicon.ico).*)',
],
}
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
}
It might help
const matcherRegex = new RegExp('^(?!/(?:_next/static|favicon\\.ico|swc\\.js|api)(?:/|$))');
export function middleware(request: NextRequest){
const isMiddlewareAllowed = matcherRegex.test(pathname)
if (isMiddlewareAllowed) {
//...
}else return
}