next.js
next.js copied to clipboard
Docs: Wrong example on middleware matcher
What is the improvement or update you wish to see?
This example:
Match all request paths except for the ones starting with:
- api (API routes)
- _next/static (static files)
- favicon.ico (favicon file)
'/((?!api|_next/static|favicon.ico).*)'
doesn't do what is says. Tried with nextjs-basic-auth-middleware, it asks for auth on static files, where it should not, but ont on index, where it should.
Is there any context that might help us understand?
Regex needs fixing, or if it is correct, something else is broken.
Does the docs page already exist? Please link to it.
https://nextjs.org/docs/advanced-features/middleware#matcher
This did the job for me, but I believe there may lie a deeper problem with negative lookaheads.
'/', '/((?!_next/static)(?!api)(?!favicon.ico).*)'
Do you have a reproduction?
export function middleware(req) {
console.log(req.url)
}
export const config = {
matcher: [
/*
* Match all request paths except for the ones starting with:
* - api (API routes)
* - _next/static (static files)
* - favicon.ico (favicon file)
*/
'/((?!api|_next/static|favicon.ico).*)',
],
}
This only logs for paths not matched by the matcher
.
This issue has been automatically closed because it received no activity for a month and had no reproduction to investigate. If you think it was closed by accident, please leave a comment. If you are running into a similar issue, please open a new issue with a reproduction. Thank you.
Actually, I think @smessaris is right: /
is also excluded when using the expression '/((?!api|_next/static|favicon.ico).*)'
from your example, @balazsorban44.
To have the middleware match /
and everything except api|_next/static|favicon.ico
you need:
export const config = {
matcher: [
'/',
'/((?!api|_next/static|favicon.ico).*)'
],
};
This bit me hard while trying to use NextAuth and have certain paths excluded from authorization. Because you naturally browse to /
of your app, it seemed like the authentication wasn't working at all, when actually just /
wasn't protected because of the way the matching works.
This closed issue has been automatically locked because it had no new activity for a month. If you are running into a similar issue, please create a new issue with the steps to reproduce. Thank you.