Next.js项目部署至Vercel后图片加载返回502错误求助
Hey there, let's break down why your images are throwing that 502 error on Vercel while imported images work perfectly—this is a common gotcha with Next.js's Image component and static asset handling!
The Root Cause
Looking at your error URL:https://portfolio-l2jkasia3-shafeequeot.vercel.app/_next/image?url=%2F..%2Fpublic%2Fimages%2Fnetflix.jpg&w=384&q=75
The encoded path %2F..%2Fpublic%2Fimages%2Fnetflix.jpg translates to ../public/images/netflix.jpg—that's the problem! Next.js treats the public directory as your static asset root. When deploying to Vercel, assets in public are served directly from your domain's root (e.g., https://your-domain.com/images/netflix.jpg), so adding ../public to the path breaks the asset resolution.
Imported images work because Next.js automatically resolves their paths during build time, but dynamic paths (like key.image) don't get that automatic fix—you have to ensure the path is correct manually.
Step-by-Step Fixes
Correct your image paths
Update the value ofkey.imageto remove the../publicprefix. For example:- Before:
../public/images/netflix.jpg - After:
/images/netflix.jpg
Your component should then look like this:
<Image width={330} height={220} className='object-fill w-44' src={key.image} alt={key.name}></Image>- Before:
Verify your path generation logic
Ifkey.imagecomes from a data source (like a JSON file or API), double-check that all image paths are formatted to start with/and reference the path insidepublic(e.g.,/images/xxx.jpginstead of including../public).Test locally with production build
Catch issues before deploying by running:npm run build && npm run startThis mimics the Vercel production environment, so you'll see if the path error occurs locally too.
Double-check
next.config.js(if needed)
If you're using external images, you need to add their domains to theimagesconfig, but for localpublicassets, this shouldn't be necessary. Just make sure you haven't accidentally enabledunoptimized: trueunless you intend to bypass Next.js's image optimization.
Why This Works
When you use /images/netflix.jpg, Next.js's image optimization service on Vercel can correctly locate the asset in your public directory. The ../public prefix confuses the server, leading to the 502 bad gateway error because it can't find the requested resource.
内容的提问来源于stack exchange,提问作者Shafeeque OT

