错误信息
code: 'DEPTH_ZERO_SELF_SIGNED_CERT'
也可能输出为
- self-signed certificate; if the root CA is installed locally, try running Node.js with --use-system-ca
- DEPTH_ZERO_SELF_SIGNED_CERT
Node.js 24.22 打印的消息是“self-signed certificate; if the root CA is installed locally, try running Node.js with --use-system-ca”;较早的版本只打印“self-signed certificate”(Node.js 17 之前为“self signed certificate”)。错误代码才是稳定的、适合搜索的部分。
Node.js tls / https / fetch — error.message "self-signed certificate" (OpenSSL X509_V_ERR_DEPTH_ZERO_SELF_SIGNED_CERT, 18)
含义
服务器的证书是自签名的(它就是自己的颁发者,位于证书链的第 0 层,即“depth zero”),而且不在 Node.js 信任的证书集合中。Node.js 报告的消息是“self-signed certificate”,代码为 DEPTH_ZERO_SELF_SIGNED_CERT。这种情况常见于本地开发服务器、内部工具,以及仍在使用安装时生成的证书的服务。
原因
使用自动生成证书的本地 HTTPS 服务器
常见开发服务器(启用 https 的 Vite 或 webpack、本地 API 网关、docker-compose 服务栈)会创建自签名证书,而 Node.js 脚本、测试和 SSR 代码并不信任它。
内部工具和专用设备
常见从未配置过 CA 签发证书的自托管服务(Jenkins、Grafana、Elasticsearch、路由器或 NAS 的管理页面)。
代理提供的是内置的默认证书
偶见如果没有任何已配置的证书与请求的名称匹配,Ingress 控制器和反向代理就会出示自签名的默认证书。
修复方法
- 1.
只为一个 Agent 信任这一张证书
把服务器的证书作为 ca 传入。这样只接受这一张证书,主机名和有效期检查仍然开启;注意,ca 会替换这个 Agent 的默认根证书。
js // Trust exactly this certificate for this agent (hostname and dates are still checked) import https from "node:https"; import fs from "node:fs"; const agent = new https.Agent({ ca: fs.readFileSync("localhost.pem") }); https.get("https://localhost:8443/", { agent }, (res) => res.resume()); - 2.
为整个进程添加该证书
NODE_EXTRA_CA_CERTS 对 https、tls 和 fetch() 同样有效,而且无需修改代码。
bash # Whole process, including fetch(): add the certificate to the trusted set NODE_EXTRA_CA_CERTS=./localhost.pem node app.js - 3.
开发时使用本地 CA
只需信任一次的本地根证书(mkcert、step-ca)可以为每台开发主机签发正规签名的证书,避免逐张证书设置例外。
bash # Development: a local CA (mkcert) instead of one-off self-signed certificates mkcert -install && mkcert localhost 127.0.0.1 NODE_EXTRA_CA_CERTS="$(mkcert -CAROOT)/rootCA.pem" node app.js - 4.
临时诊断:rejectUnauthorized: false
会让该 Agent 接受任何证书,包括攻击者的证书。只可用于快速的本地检查;切勿用于要发布的代码。
js // Temporary diagnostic in a test only: accepts ANY certificate on this agent const agent = new https.Agent({ rejectUnauthorized: false });
相关错误
self-signed certificate in certificate chainNode.js tls / https / fetchnpm error code DEPTH_ZERO_SELF_SIGNED_CERTnpm (Node.js)curl: (60) SSL certificate problem: self-signed certificatecurl (OpenSSL backend)[SSL: CERTIFICATE_VERIFY_FAILED] certificate verify failed: self-signed certifi…Python ssl module (OpenSSL)