Next.js Discord

Discord Forum

How to avoid "/" root route in NextJS middleware matcher

Answered
Transvaal lion posted this in #help-forum
Open in Discord
Transvaal lionOP
With this config:
export const config = {
    matcher: ["/((?!api|_next/static|_next/image|favicon.ico|.*\.svg|register).*)"]
}

I am able to apply this regex to everything that I want, but it doesn't apply to the root route /. How do I NOT apply it to the root route?
Answered by James4u
export const config = {
    matcher: [
        "/((?!api|_next/static|_next/image|favicon.ico|.*\\.svg|register|$).*)"
    ]
}
View full answer

5 Replies

export const config = {
    matcher: [
        "/((?!api|_next/static|_next/image|favicon.ico|.*\\.svg|register|$).*)"
    ]
}
Answer
Try this @Transvaal lion
@James4u export const config = { matcher: [ "/((?!api|_next/static|_next/image|favicon.ico|.*\\.svg|register|$).*)" ] }
Transvaal lionOP
Thank you! What does the $ signify in this?
|$ is added to the negative lookahead ((?!...)) part of the regex to ensure the root route is not matched. The |$ part means "or the end of the string" which effectively excludes the root route (/).
@James4u |$ is added to the negative lookahead ((?!...)) part of the regex to ensure the root route is not matched. The |$ part means "or the end of the string" which effectively excludes the root route (/).
Transvaal lionOP
Ah ok, I forgot about assertions, just like ^ is for the beginning of the input, $ is for the end. So anything that ends with nothing, in this case the root route. Gotcha 👍