You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Next.js 13.5.4自定义HTTPS服务器加载本地图片遇ImageError求助

Next.js 13.5.4 HTTPS自定义服务器下next/image本地图片加载失败解决指南

问题场景

使用next@13.5.4搭建自定义HTTPS服务器(监听443端口),通过import header from "@/public/image/header.png"引入本地图片时,next/image无法加载,抛出以下错误:

upstream image response failed for /_next/static/media/header.022b632b.png TypeError: fetch failed
at Object.fetch (node:internal/deps/undici/undici:11457:11)
at async invokeRequest (C:\projects\web\node_modules\next\dist\server\lib\server-ipc\invoke-request.js:17:12)
at async C:\projects\web\node_modules\next\dist\server\next-server.js:362:39
at async imageOptimizer (C:\projects\web\node_modules\next\dist\server\image-optimizer.js:537:13)
at async cacheEntry.imageResponseCache.get.incrementalCache (C:\projects\web\node_modules\next\dist\server\next-server.js:519:61)
at async C:\projects\web\node_modules\next\dist\server\response-cache\index.js:102:36 {
cause: SocketError: other side closed
at Socket.onSocketEnd (C:\projects\web\node_modules\next\dist\compiled\undici\index.js:1:73361)
at Socket.emit (node:events:525:35)
at endReadableNT (node:internal/streams/readable:1359:12)
at process.processTicksAndRejections (node:internal/process/task_queues:82:21) {
code: 'UND_ERR_SOCKET',
socket: {
localAddress: '127.0.0.1',
localPort: 9090,
remoteAddress: '127.0.0.1',
remotePort: 443,
remoteFamily: 'IPv4',
timeout: undefined,
bytesWritten: 864,
bytesRead: 0
}
}
}
ImageError: "url" parameter is valid but upstream response is invalid
at imageOptimizer (C:\projects\web\node_modules\next\dist\server\image-optimizer.js:549:19)
at async cacheEntry.imageResponseCache.get.incrementalCache (C:\projects\web\node_modules\next\dist\server\next-server.js:519:61)
at async C:\projects\web\node_modules\next\dist\server\response-cache\index.js:102:36 {
statusCode: 500
}

核心原因

  1. Next.js图片优化器通过内部HTTP请求获取图片资源,当使用自定义HTTPS服务器时,Node.js内置的undici(Next.js使用的fetch实现)默认不信任自签名证书,导致连接被主动关闭。
  2. 图片优化器请求本地资源时,协议/端口配置不匹配,无法正确访问HTTPS服务器上的静态资源。

解决步骤

1. 临时信任本地HTTPS证书(开发环境)

在启动自定义服务器时,添加环境变量跳过证书校验:
修改package.json中的启动脚本:

{
  "scripts": {
    "start": "NODE_TLS_REJECT_UNAUTHORIZED=0 node server.js"
  }
}

注意:此方法仅适用于开发环境,生产环境需使用受信任的CA证书。

2. 配置next.config.js允许本地图片域名

在项目根目录的next.config.js中添加图片域名/远程规则配置:

/** @type {import('next').NextConfig} */
const nextConfig = {
  images: {
    // 允许本地域名访问
    domains: ['localhost', '127.0.0.1'],
    // 或更精确的远程规则
    remotePatterns: [
      {
        protocol: 'https',
        hostname: 'localhost',
        port: '443',
        pathname: '/_next/static/media/**',
      },
    ],
  },
};

module.exports = nextConfig;

3. 确保自定义HTTPS服务器配置正确

检查服务器代码中证书和密钥的路径是否正确,确保服务器能正常处理HTTPS请求:

const https = require('https');
const fs = require('fs');
const next = require('next');

const dev = process.env.NODE_ENV !== 'production';
const app = next({ dev });
const handle = app.getRequestHandler();

// 替换为你的证书和密钥路径
const httpsOptions = {
  key: fs.readFileSync('./path/to/private.key'),
  cert: fs.readFileSync('./path/to/certificate.crt'),
};

app.prepare().then(() => {
  https.createServer(httpsOptions, (req, res) => {
    handle(req, res);
  }).listen(443, (err) => {
    if (err) throw err;
    console.log('> 服务器已启动:https://localhost:443');
  });
});

4. 验证图片引入方式

确保图片放置在public/image目录下,且组件中正确使用next/image:

import Image from 'next/image';
import header from '@/public/image/header.png';

export default function HomePage() {
  return (
    <div>
      <Image
        src={header}
        alt="页面头部图片"
        width={800}
        height={400}
        priority
      />
    </div>
  );
}

内容的提问来源于stack exchange,提问作者a.nayebi

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.09 04:49:59