next.js icon indicating copy to clipboard operation
next.js copied to clipboard

Urgent - next/image "url" parameter is valid but upstream response is invalid (2)

Open dev-bluecomet opened this issue 7 months ago • 67 comments

Link to the code that reproduces this issue

https://github.com/bluecomet1994

To Reproduce

I'm using Next 14.0.1 for the web application development. But I'm facing some issues with the usage of optimized Image component. The image is not appear on the browser when I run the website and when I go though the network tab, I'm getting this response from them.

next/image "url" parameter is valid but upstream response is invalid

Current vs. Expected behavior

The output should not have any error response in the network and should display the image with the specific path.

Verify canary release

  • [x] I verified that the issue exists in the latest Next.js canary release

Provide environment information

Operating System:
Windows 10
21H2
19044.1288

Packages
NPM v9.8.1
Yarn v1.22.19
PNPM v8.10.2

node_modules
  "dependencies": {
    "@emotion/react": "^11.11.1",
    "@emotion/styled": "^11.11.0",
    "@mui/icons-material": "^5.14.16",
    "@mui/material": "^5.14.17",
    "next": "^14.0.1",
    "react": "^18",
    "react-dom": "^18",
    "react-redux": "^8.1.3",
    "redux": "^4.2.1",
    "redux-devtools-extension": "^2.13.9",
    "redux-thunk": "^2.4.2"
  },
  "devDependencies": {
    "@types/node": "^20",
    "@types/react": "^18",
    "@types/react-dom": "^18",
    "autoprefixer": "^10.0.1",
    "eslint": "^8",
    "eslint-config-next": "14.0.1",
    "postcss": "^8",
    "tailwindcss": "^3.3.0",
    "typescript": "^5"
  }

next.config.js
/** @type {import('next').NextConfig} */
const nextConfig = {
  reactStrictMode: true,
  i18n: {
    locales: ["en", "es"],
    defaultLocale: "en"
  }
};

module.exports = nextConfig;

Which area(s) are affected? (Select all that apply)

Image optimization (next/image, next/legacy/image)

Additional context

In earlier versions like below 13.5, it works fine.

dev-bluecomet avatar Nov 09 '23 14:11 dev-bluecomet

Same problem in NextJS v14.0.0

stasdre avatar Nov 09 '23 15:11 stasdre

Same issue over here - seems to be a regression, as it works in v13.5.5

cpotey avatar Nov 09 '23 16:11 cpotey

I've been facing the same problem for weeks now :C

luchesigui avatar Nov 09 '23 17:11 luchesigui

Experiencing this as well on 14.0.1

We're hosted on Azure and the log stream outputs this:

⨯ upstream image response failed for /img/app/man-holding-phone.jpg TypeError: fetch failedat Object.fetch (node:internal/deps/undici/undici:11576:11)at process.processTicksAndRejections (node:internal/process/task_queues:95:5)at async invokeRequest (C:\home\site\wwwroot\node_modules\next\dist\server\lib\server-ipc\invoke-request.js:17:12)at async C:\home\site\wwwroot\node_modules\next\dist\server\next-server.js:592:35at async imageOptimizer (C:\home\site\wwwroot\node_modules\next\dist\server\image-optimizer.js:576:13)at async cacheEntry.imageResponseCache.get.incrementalCache (C:\home\site\wwwroot\node_modules\next\dist\server\next-server.js:176:65)at async C:\home\site\wwwroot\node_modules\next\dist\server\response-cache\index.js:93:36at async C:\home\site\wwwroot\node_modules\next\dist\lib\batcher.js:41:32 {cause: AggregateErrorat internalConnectMultiple (node:net:1111:18)at afterConnectMultiple (node:net:1663:5)at TCPConnectWrap.callbackTrampoline (node:internal/async_hooks:130:17) {code: 'EACCES',[errors]: [ [Error], [Error] ]}}

lostchopstik avatar Nov 09 '23 18:11 lostchopstik

I was facing the same issue and spent a whole day debugging this on my end.

In my case, I moved the path of some images from /some/folder1 to /public/img. After testing the change by running npm run dev I was getting the fetch error as above and apparently happened only for .png images. All .svgs worked as intended. I verified that the image format was not being blocked by any next.config.js configuration or through any middleware security.

However after running the code with npm run build and npm run start, I loaded the images and they seemed to work fine. So for me, the issue was with dev environment. However upon running the dev environment again the images loaded normally. The actual issue was caused in the way next loads the images. The svgs were being server from _next/static path whereas the the pngs were being served with /_next/image?url=%2F_next%2Fstatic%2Fmedia%2Fmyfile.somehash.png". Since I moved the folders of the images, the path did not exist in my build folder from which it seems to be generating the hash for referencing the image.

TL;DR Issue in dev environment. Run npm run build to add image to build cache and try running dev again.

CromulentCoder avatar Nov 09 '23 20:11 CromulentCoder

Try running npm run start and going manually to that page. Maybe its generating the images on the fly?

CromulentCoder avatar Nov 09 '23 21:11 CromulentCoder

Ive got the same issue with next 14.0.0 - what's weird is that some images on my deployed app are displayed correctly and some get the "url" parameter is valid but upstream response is invalid" error, all png images, all in my public folder

Naasgul avatar Nov 10 '23 07:11 Naasgul

Locally everything is ok for me, but on the firevase hosting the png images don’t work

stasdre avatar Nov 10 '23 07:11 stasdre

Ive got the same issue with next 14.0.0 - what's weird is that some images on my deployed app are displayed correctly and some get the "url" parameter is valid but upstream response is invalid" error, all png images, all in my public folder

I am running into this, or similar as well. Vercel seems to be caching the 502 response if for any reason it couldn't find the source image, and even when the source file is available it keeps serving the 502. Would appreciate a fix.

smessaris avatar Nov 10 '23 09:11 smessaris

Locally everything is ok for me, but on the firevase hosting the png images don’t work

Same here since i bump next from 13 to 14.0.1

Felixaverlant avatar Nov 10 '23 10:11 Felixaverlant

my webpage loads some pictures correctly in mobile view which arent able to load with known error message on desktop view - I'll test if setting the width/height of the image component helps with solving this issue since its relevant for the optimization (/_next/image?url=%2Fimages%2FHeresMyImage.webp&w=1080&q=75)

Naasgul avatar Nov 10 '23 11:11 Naasgul

How do you run it fine on local?

import image from '@/assets/images/image.png';

<Image
   src={image}
   className={'mb-8 h-auto max-w-[110px] md:max-w-[175px] xl:order-last xl:mb-0 xl:shrink-0'}
   width={175}
   height={360}
   quality={85}
   sizes={'100vw'}
   placeholder={'blur'}
/>

This case locally works& But after deploy to firebase I get an error: "url" parameter is valid but upstream response is invalid

I'm temporarily ditching the component next/image for now and just using <picture> tag

stasdre avatar Nov 10 '23 11:11 stasdre

How do you run it fine on local?

import image from '@/assets/images/image.png';

<Image
   src={image}
   className={'mb-8 h-auto max-w-[110px] md:max-w-[175px] xl:order-last xl:mb-0 xl:shrink-0'}
   width={175}
   height={360}
   quality={85}
   sizes={'100vw'}
   placeholder={'blur'}
/>

This case locally works& But after deploy to firebase I get an error: "url" parameter is valid but upstream response is invalid

I'm temporarily ditching the component next/image for now and just using <picture> tag

You can also just use the "unoptimized" attribute for the next/image component - for quick fix I transformed all my .png-images to .webp and use the unoptimized attribute - Im not really seeing a performance issue, having just a small webpage tho

Naasgul avatar Nov 10 '23 11:11 Naasgul

You can also just use the "unoptimized" attribute for the next/image component - for quick fix I transformed all my .png-images to .webp and use the unoptimized attribute - Im not really seeing a performance issue, having just a small webpage tho

Yes, but this does not solve the problem with the png format. And there is a bug with png images and it needs to be fixed

stasdre avatar Nov 10 '23 14:11 stasdre

I'm confirming this bug in v14.0.2 and it is so weird bug sometimes display and sometimes no issue, refreshing the page can reproduce it. somtimes close the browser and deleting the build directory then running npm run dev it sometimes reproduce it

windows 10 pro v22H2 (19045.3570)
node v18.15.0
 "dependencies": {
    "next": "^14.0.2",
    "react": "^18.2.0",
    "react-dom": "^18.2.0",
  },
  "devDependencies": {
    "@types/node": "^20",
    "@types/react": "^18.2.34",
    "@types/react-dom": "^18.2.14",
    "autoprefixer": "^10",
    "eslint": "^8",
    "eslint-config-next": "^14.0.1",
    "postcss": "^8",
    "tailwindcss": "^3",
    "typescript": "^5"

AymanMorsy avatar Nov 11 '23 03:11 AymanMorsy

Same here with v14.0.0 :( ... any improvements?

It seems like the file extensions matter. When I used '.jpeg' files, the error above occurred. However, the basic '.jpg' images that blog-starter provides work well without the error.

ihnokim avatar Nov 16 '23 15:11 ihnokim

will someone try npm ci and see if it resolves the issue?

https://docs.npmjs.com/cli/v8/commands/npm-ci

joey-ma avatar Nov 16 '23 17:11 joey-ma

Same here for IIS.

jmacbhc avatar Nov 16 '23 19:11 jmacbhc

for me it's only for IIS (works well on Heroku/Vercel) v.13.5.5

evgenTraytyak avatar Nov 17 '23 07:11 evgenTraytyak

Issue still apparant.

ErosKarm avatar Nov 18 '23 10:11 ErosKarm

I'm in 14.0.3 and I'm trying to load an image from CraftCMS in my local dev environment using GraphQL, the query pulls the image url through fine but next/image won't load it, I get this on console:

TypeError: fetch failed
    at Object.fetch (node:internal/deps/undici/undici:14152:11)
    at process.processTicksAndRejections (node:internal/process/task_queues:95:5)
    at async imageOptimizer (/Users/andrew/Sites/unravelyourfood/node_modules/next/dist/server/image-optimizer.js:560:29)
    at async cacheEntry.imageResponseCache.get.incrementalCache (/Users/andrew/Sites/unravelyourfood/node_modules/next/dist/server/next-server.js:176:65)
    at async /Users/andrew/Sites/unravelyourfood/node_modules/next/dist/server/response-cache/index.js:90:36
    at async /Users/andrew/Sites/unravelyourfood/node_modules/next/dist/lib/batcher.js:41:32 {
  cause: Error: unable to verify the first certificate
      at TLSSocket.onConnectSecure (node:_tls_wrap:1540:34)
      at TLSSocket.emit (node:events:513:28)
      at TLSSocket._finishInit (node:_tls_wrap:959:8)
      at ssl.onhandshakedone (node:_tls_wrap:743:12) {
    code: 'UNABLE_TO_VERIFY_LEAF_SIGNATURE'
  }
}

Edit: I forgot to mention I can access the local image url fine, and the url is passed in properly but results in a 500 error in Next JS.

Finally I figured my issue out, not sure if this is helpful to anyone else — based on https://github.com/vercel/next.js/discussions/13546

So my setup is CraftCMS on a project-cms.test domain and NextJS on localhost:3000 — I'm using Valet to host all of my CraftCMS sites/CMS instances, this secures them but NextJS 14 didn't seem to like it.

Based on the above I used mkcert to generate a new certificate for my Valet site — I then went into the Valet config folder: /User/andrew/.config/valet/Nginx and edited my sites nginx config to replace these two lines:

ssl_certificate "/Users/andrew/.config/valet/Certificates/unravelyourfood-cms.test.pem";
ssl_certificate_key "/Users/andrew/.config/valet/Certificates/unravelyourfood-cms.test-key.pem";

Based on the above issue I put this in my .env file: NODE_EXTRA_CA_CERTS=/Users/andrew/.config/valet/Certificates/unravelyourfood-cms.test.pem

I then launched NextJS in SSL mode using: next dev --experimental-https

and it works 🥲

a-rbsn avatar Nov 20 '23 16:11 a-rbsn

@bluecomet1994 I think this probably not the bug for next.

TL;DR

Just explicitly specify the port like this ( in this example luca-vogels/bug-next-image) :

const dev = true;
const HTTP_PORT = 80;
const nextApp = next({ dev, port: HTTP_PORT });

And it'll run perfectly without any error.

image

I also test latest next.js version [email protected], and everything is good.

WHY

The Component <Image /> always optimize the image.

unoptimized = {false} // {false} | {true}

And when client want the image, server will call imageOptimizer to optimize the image. So you can specify unoptimized in <Image /> tag to solve this problem (that's why @Naasgul 's method work), but it not the best choice.

And In this line next server try to fetch image with url http://localhost:<port> Here is the bug:

const invokeRes = await invokeRequest(
           `${protocol}://${this.fetchHostname || 'localhost'}:${this.port}${newReq.url || ''}`,
            {
              method: newReq.method || 'GET',
              headers: newReq.headers,
              signal: signalFromNodeResponse(res.originalResponse),
			}
)

If you don't pass the port explicitly like next({ dev, port: HTTP_PORT }), next don't know the port, and this.port will be 3000, which is the default port of next.

Muffeter avatar Nov 21 '23 13:11 Muffeter

I have just updated to Next 14.0.3 and facing the same issue. My log on render.com: Screenshot 2023-11-22 151310

jacksonllk avatar Nov 22 '23 07:11 jacksonllk

Just recently found the reason why Next.js was giving us this error. It was due to Next trying to convert our local .webp images into .avif format for Mac browsers.

When this line is used in next.config.js, the issue appears and in addition causes a timeout after 40 seconds or so:

    formats: ["image/avif", "image/webp"],

Once we removed the formats property entirely, the issue went away. Might have to do with the sharp package integration.

stx-chris avatar Nov 22 '23 08:11 stx-chris

Just recently found the reason why Next.js was giving us this error. It was due to Next trying to convert our local .webp images into .avif format for Mac browsers.

When this line is used in next.config.js, the issue appears and in addition causes a timeout after 40 seconds or so:

    formats: ["image/avif", "image/webp"],

Once we removed the formats property entirely, the issue went away. Might have to do with the sharp package integration.

But i currently do not have the format property in my next.config.js and I am still seeing that error

jacksonllk avatar Nov 22 '23 08:11 jacksonllk

Do you import local files as recommended in the docs using import statements or do you use a relative path to some folder in the src property?

Because switching from relative path to imports helped us reduce potential errors with image loading.

stx-chris avatar Nov 22 '23 08:11 stx-chris

I tried doing that but it doesn't work for me somehow. My image component is like so: <Image src="/images/hero-image1.webp" alt="Hero Image" fill={true} style={{ objectFit: 'cover', objectPosition: 'top', }} quality={10} priority />

I'm still on pages and not app router. Not sure if that is causing it. So the error in this thread is related to images not being imported?

jacksonllk avatar Nov 22 '23 10:11 jacksonllk

ok, can you try the following instead?

// the relative path might need adjustment according to your file location
import heroImage1 from "/images/hero-image1.webp"; 

<Image
   src={heroImage1}
   alt="Hero Image"
   fill={true}
   style={{
       objectFit: 'cover',
       objectPosition: 'top',
   }}
   quality={10}
   priority
/>

Not sure in which version this way of handling was introduced (whether only for app router or already for pages), just give it a try. Good luck!

stx-chris avatar Nov 22 '23 10:11 stx-chris

Yea for some reason this doesn't work for me, but thanks for your help! Still waiting for a definitive answer on the error of this thread. It's been unresolved since August.

jacksonllk avatar Nov 22 '23 12:11 jacksonllk

same problem exists

hsnbsst avatar Nov 23 '23 07:11 hsnbsst