Next.js Discord

Discord Forum

NextJS middleware is executed for /public/

Unanswered
Polar bear posted this in #help-forum
Open in Discord
Polar bearOP
export const config = {
  matcher: [
    /*
     * Match all request paths except for the ones starting with:
     * - api (API routes)
     * - _next/static (static files)
     * - _next/image (image optimization files)
     * - favicon.ico, sitemap.xml, robots.txt (metadata files)
     */
    '/((?!api|_next/static|_next/image|favicon.ico|sitemap.xml|robots.txt).*)',
  ],
}

23 Replies

Polar bearOP
logo.svg is at /public/logo.svg
Asian black bear
It works as intended because static assets in the public directory are served at root level.
@Asian black bear It works as intended because static assets in the public directory are served at root level.
Polar bearOP
But I don't want to execute the middleware and do extra unneeded requests for just loading an image
How can I achieve that
Asian black bear
It's not an extra request - the middleware just runs before the incoming request is handled.
There is typically not an issue about it.
And in many cases, especially when serving static assets, the middleware will just run next() and do nothing.
Asian black bear
Because your middleware, as it is configure now, runs for each public path.
Except for the cases listed in the comment.
Polar bearOP
That's the point
I want to exclude public pathes
Asian black bear
You'd have to list every single path you'd like the middleware NOT to run on but it's pretty much pointless.
The cost of running the middleware for static assets it negligible.
@Asian black bear You'd have to list every single path you'd like the middleware NOT to run on but it's pretty much pointless.
Polar bearOP
So there is no regex to exclude public directory contents
like images sound files etc
Asian black bear
No because the files in /public are mapped to /*
Polar bearOP
I think reversing the process is better
To specify the pathes that I want middleware to work in
Instead of excluding every single attachment in /public
because as you said they're mapped to /*
What do you think?
Because I'm currently fetching the user data for each protected route and check for his permissions
Asian black bear
It's a possible point of failure - when you add a new route that should be secured but your forgot to add it or have a typo then you're accidentally exposing it.
Polar bearOP
So what's the best practice in your pov