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)?
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
}