#middleware routing matcher not working with root path

1 messages · Page 1 of 1 (latest)

topaz solstice
#

in my middleware I want to setup a matcher that will match all paths except for: /api routes, /_next (Next.js internals), /_static (inside /public), /images (inside /public) and all root files inside /public
however, when I visit my app from the root path like: some-url.com
it does not go into the middleware, because the matcher does not match it
here is my config:

export const config = {
  matcher: [
    /*
     * Match all paths except for:
     * 1. /api routes
     * 2. /_next (Next.js internals)
     * 3. /_static (inside /public)
     * 4. /images (inside /public)
     * 5. all root files inside /public (e.g. /favicon.ico)
     */
    "/((?!api/|_next/|_static/|images/|[\\w-]+\\.\\w+).*)"
  ]
};

I want it to run the middleware when I visit my site from rool path like some-url.com, but with this config unfortonatly it does not
what is wrong here?

ornate cloudBOT
#

Hi @topaz solstice. I'm kapa.ai, your friendly support bot. I will try to answer your question by searching through the knowledge base. :wave:

#

The issue you're experiencing might be due to the regular expression used in your matcher configuration. The regular expression "/((?!api/|_next/|_static/|images/|[\\w-]+\\.\\w+).*)" is designed to match all paths except for the ones you specified. However, it seems like it's not matching the root path (/).

The root path might not be matched because of the negative lookahead part of your regex ((?!api/|_next/|_static/|images/|[\\w-]+\\.\\w+)). This part of the regex is designed to not match the specified paths, but it might also be excluding the root path.

You could try modifying your regex to explicitly include the root path. Here's an example:

export const config = {
  matcher: [
    /*
     * Match all paths except for:
     * 1. /api routes
     * 2. /_next (Next.js internals)
     * 3. /_static (inside /public)
     * 4. /images (inside /public)
     * 5. all root files inside /public (e.g. /favicon.ico)
     */
    "/((?!api/|_next/|_static/|images/|[\\w-]+\\.\\w+|^$).*)"
  ]
};

In this example, ^$ is added to the negative lookahead part of the regex. This should match the root path, allowing the middleware to run when you visit your site from the root path.

Please note that this is just a suggestion based on the information provided in the extracts. You might need to adjust the regex to suit your specific needs.

For more information on how to use the matcher configuration in Next.js middleware, you can refer to the official Next.js documentation (https://nextjs.org/docs/pages/building-your-application/routing/middleware#matcher).

Note: you can ask me a follow up question by @ mentioning me again :speech_balloon: