Search code examples
reactjsnext.jsmiddlewarenextjs-image

NextJS ImageError: Unable to optimize image and unable to fallback to upstream image


I created middleware and add matcher /((?!api|_next/static|_next/image|favicon.ico|auth/login).*) in config middleware. When I try to run npm run dev.The result comes out like this:

ImageError: Unable to optimize image and unable to fallback to upstream image
    at imageOptimizer (C:\work\internal-dashboard\node_modules\next\dist\server\image-optimizer.js:563:19)
    at async cacheEntry.imageResponseCache.get.incrementalCache (C:\work\internal-dashboard\node_modules\next\dist\server\next-server.js:238:72)
    at async C:\work\internal-dashboard\node_modules\next\dist\server\response-cache\index.js:83:36 {
  statusCode: 400
}
ImageError: Unable to optimize image and unable to fallback to upstream image
    at imageOptimizer (C:\work\internal-dashboard\node_modules\next\dist\server\image-optimizer.js:563:19)
    at async cacheEntry.imageResponseCache.get.incrementalCache (C:\work\internal-dashboard\node_modules\next\dist\server\next-server.js:238:72)
    at async C:\work\internal-dashboard\node_modules\next\dist\server\response-cache\index.js:83:36 {
  statusCode: 400
}

Before I added middleware this was not happening, this happened when I added config matcher in middleware. Here is the config matcher on the middleware I made:

export const config = {
  matcher: [
    '/((?!api|_next/static|_next/image|favicon.ico|auth/login).*)',
    '/partner/:path*'
  ],
};

I am trying to omit _next/image from the middleware matcher. As a result, some images cannot be loaded.

Is there a way to solve the case? or maybe I forgot something when I made middleware?


Solution

  • This problem started to occur when I added middleware.[jt]s. I realised that all of the paths are being matched by it.

    So I added this:

    export const config = {
      matcher: ['/((?!api|_next/static|_next/image|favicon.ico).*)']
    }
    

    but it didn't work.

    Later I updated the regex to include images folder as well because I have my images as public/images/my-image.png.

    So, my working regex now looks like this:

    export const config = {
      matcher: ['/((?!api|_next/static|_next/image|images|favicon.ico).*)']
    }
    

    Diff TLDR

     export const config = {
    -  matcher: ['/((?!api|_next/static|_next/image|favicon.ico).*)']
    +  matcher: ['/((?!api|_next/static|_next/image|images|favicon.ico).*)']
     }