Next.js Discord

Discord Forum

Next.js Middleware matcher not ignoring images

Unanswered
Luke posted this in #help-forum
Open in Discord
Hey all, thank you for taking the time to read this.

I'm switching my Next.js 14.2.5 App Router app to use middleware for auth instead of checking in layouts/pages.

Our app has internal pages for our employees, and some external pages for customers to view. I opted to use [Next's default route matcher regex](https://nextjs.org/docs/app/building-your-application/routing/middleware#matcher) that they provide in the docs, and then extend it with the unprotected routes (we don't have any sensitive static files/images, and our we handle auth checks directly on our api routes).

So, I went ahead and copied the config in, and added my external offer and checkout pages to the matcher, and now, everything works as expected, where those two pages don't perform any auth checks, and the other pages do.

But! There's one, very odd issue, for some reason, everything is working besides the images served by _next/image, including static files. I don't know why this would be, but they are being blocked by the middleware for unauthenticated users. I've tested on multiple browsers.

Here is my middleware.ts:

export { auth as middleware } from "~/auth";

export const config = {
  matcher: [
    /*
     * Match all request paths except for the ones starting with:
     * - api (API routes) (this is okay because we have protectedProcedure's on tRPC routes)
     * - _next/static (static files)
     * - _next/image (image optimization files)
     * - favicon.ico (favicon file)
     *
     * (external) route group pages:
     * - offer (offer page)
     * - checkout (checkout page)
     */
    "/((?!api|_next/static|_next/image|favicon.ico|offer|checkout).*)",
  ],
};


Example blocked image request:
http://localhost:3000/_next/image?url=%2Fimg%2Flogo.png&w=256&q=75

Example working next/static request:
http://localhost:3000/_next/static/media/4012cc4b67ad157d-s.p.woff2

Why is this happening? And why is it not effecting my static files? They look to be defined about the same.

0 Replies