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

NextJS getServerSideProps报UNABLE_TO_VERIFY_LEAF_SIGNATURE错误求助

NextJS getServerSideProps 证书验证错误问题解决

问题背景

我是NextJS新手,将ReactJS项目迁移至NextJS后运行正常,此前一直使用useEffect获取数据。现在尝试按照NextJS推荐使用getServerSideProps()时遇到问题。

我的getServerSideProps代码

export async function getServerSideProps() {
  const res = await axios.get(`BACKEND_URL/product/0`);
  const data = await res.data;
  return { props: { data } };
}

错误情况

该API调用在React的useEffect中可正常工作,但使用getServerSideProps()时返回状态码500,错误信息为UNABLE_TO_VERIFY_LEAF_SIGNATURE,错误栈如下:

"message":"unable to verify the first certificate",
"stack":"Error: unable to verify the first certificate
    at TLSSocket.onConnectSecure (_tls_wrap.js:1515:34)
    at TLSSocket.emit (events.js:400:28)
    at TLSSocket._finishInit (_tls_wrap.js:937:8)
    at TLSWrap.ssl.onhandshakedone (_tls_wrap.js:709:12)",
"code":"UNABLE_TO_VERIFY_LEAF_SIGNATURE","status":null

我已确认后端可访问、URL有效,不使用getServerSideProps()时页面正常运行。目前可通过在_app.js中添加以下代码临时解决,但该做法存在安全风险,求问问题根源及安全的解决方案:

axios.defaults.httpsAgent = new https.Agent({
  rejectUnauthorized: false,
});

问题根源

核心原因是浏览器客户端与Node.js环境的SSL证书信任机制差异:

  • 浏览器内置了完善的根证书信任列表,能自动验证由合法中间CA签发的服务器证书;
  • getServerSideProps运行在Node.js环境中,Node.js的默认证书信任池可能缺少后端证书链中的中间CA证书,导致无法完成完整的证书链验证,从而抛出该错误。

安全解决方案

方案1:配置完整证书链

获取后端服务的完整SSL证书链(包含根证书、中间证书、服务器证书),保存为.pem格式文件(例如fullchain.pem),然后在axios请求中指定该证书链:

import https from 'https';
import fs from 'fs';

export async function getServerSideProps() {
  const agent = new https.Agent({
    ca: fs.readFileSync('./fullchain.pem'), // 替换为你的证书链文件实际路径
  });
  const res = await axios.get(`BACKEND_URL/product/0`, { httpsAgent: agent });
  const data = await res.data;
  return { props: { data } };
}

方案2:升级Node.js版本

如果后端使用的是公共CA签发的证书,可能是你的Node.js版本过旧,其内置的根证书列表未包含最新的CA证书。升级Node.js到最新稳定版,即可自动适配新的信任证书。

方案3:通过环境变量指定信任证书

在Node.js运行时通过环境变量NODE_EXTRA_CA_CERTS添加额外信任的CA证书,无需修改代码:

NODE_EXTRA_CA_CERTS=./fullchain.pem npm run dev

该方式适合开发环境快速验证,生产环境也可配置到启动脚本中。

内容的提问来源于stack exchange,提问作者SJ19

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.17 02:15:36