Next.js Discord

Discord Forum

Is there a way to exclude specific path from running on middleware?

Answered
Nile Crocodile posted this in #help-forum
Open in Discord
Avatar
Nile CrocodileOP
Is there a way to exclude specific path like "/about/" or "careers" from running middleware.

This is code i am using right now but it seems, this will exclude all paths starting with "about".
So it will exclude "about-test" also, which is something i don't want?

export const config = {
matcher: [
"/((?!about|careers|contact-us|api|_next/static|_next/image|favicon.ico|robots.txt|manifest.json|browserconfig.xml).*)",
],
};
Answered by iyxan23
hi, this is a workaround i had just figured out, looks kinda clunky but it works 😄
Image
View full answer

15 Replies

Answer
Avatar
Asian black bear
If you don't want to mess with the matcher just check for the path in the middleware and early return using next() in there
Avatar
i honestly think it would be more intuitive if the next team, instead of using a single regex, used glob matching on a list instead. imagine doing { exclude: ["/careers/*", "/about/*"] }, that'd be pretty awesome :)
Avatar
@iyxan23 hi, this is a workaround i had just figured out, looks kinda clunky but it works 😄
Avatar
Nile CrocodileOP
Testing this returned and error /((?!about(/|w|$)|^api|_next/static|_next/image|favicon.ico|robots.txt|manifest.json|browserconfig.xml).*) https://nextjs.org/docs/messages/invalid-route-source
Avatar
seems like you're missing a backslash \ on the w there
but huh that's odd, even if it was a regular w, it should've been able to be parsed
might want to try gin's regex to see if that works
Avatar
    let requestedPath = request.nextUrl.pathname;

    //No authentication needed for route
    if (mw_IsNoAuthRoute(requestedPath) == true) {
        return NextResponse.next();
    }


To @Asian black bear point, this is how I do it.
Avatar
@Asian black bear If you don't want to mess with the matcher just check for the path in the middleware and early return using `next()` in there
Avatar
Nile CrocodileOP
This would still be logged as invocation of middleware. Right? I can still see that path being logged for triggering middleware even when using something like:
if (request.nextUrl.pathname === "/about/") { return NextResponse.next(); }
Avatar
Asian black bear
Yes, but it really doesn't matter.
Avatar
Nile CrocodileOP
yeah, just wanted to to check
@Asian black bear Idea is i guess that it would just not run any function but go further to that path.