next.js icon indicating copy to clipboard operation
next.js copied to clipboard

Docs: Wrong example on middleware matcher

Open smessaris opened this issue 1 year ago • 2 comments

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

smessaris avatar Nov 18 '22 10:11 smessaris

This did the job for me, but I believe there may lie a deeper problem with negative lookaheads. '/', '/((?!_next/static)(?!api)(?!favicon.ico).*)'

smessaris avatar Nov 18 '22 10:11 smessaris

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.

balazsorban44 avatar Nov 18 '22 12:11 balazsorban44

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.

balazsorban44 avatar Dec 20 '22 23:12 balazsorban44

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.

soulchild avatar Dec 23 '22 15:12 soulchild

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.

github-actions[bot] avatar Jan 23 '23 00:01 github-actions[bot]