日本語

Fixing “self-signed certificate” Errors in Node.js

​​Node.js​HTTPS,JavaScript,Troubleshooting

When Node.js fetch() stops with TypeError: fetch failed and cause shows Error: self-signed certificate, Node.js does not trust the certificate of the server you are connecting to. If you start Node.js with the environment variable NODE_EXTRA_CA_CERTS pointing to that certificate file, the error goes away without turning off verification.

This applies when a Node.js script connects to an HTTPS server with a certificate you created yourself for development, or to a test API running on a self-signed certificate. I created a self-signed certificate in a test environment, caused the error, and confirmed that the fix removes it.

Note

The test environment was Ubuntu 24.04, Node.js 22.23.5 (bundled OpenSSL 3.5.9), and the openssl command used to create the certificate was 3.0.13. The server and the client ran on the same machine. I did not test Windows or macOS, Node.js 21 and earlier, setups behind a proxy, or libraries such as the npm undici package or axios.

The message you get from fetch with a self-signed certificate server

First, I created a self-signed test certificate with the openssl command. The name (CN and subjectAltName) is localhost. I omitted the progress output that openssl prints.

console
$ openssl req -x509 -newkey rsa:2048 -nodes -keyout key.pem -out cert.pem -days 30 -subj "/CN=localhost" -addext "subjectAltName=DNS:localhost"
$ openssl x509 -in cert.pem -noout -subject -issuer -ext subjectAltName
subject=CN = localhost
issuer=CN = localhost
X509v3 Subject Alternative Name: 
    DNS:localhost

subject (whose certificate it is) and issuer (who signed it) are the same. That makes it a self-signed certificate.

I ran an HTTPS server, server.mjs, with this certificate.

js
import { createServer } from 'node:https';
import { readFileSync } from 'node:fs';

const server = createServer({
  key: readFileSync('key.pem'),
  cert: readFileSync('cert.pem'),
}, (req, res) => {
  res.setHeader('Content-Type', 'application/json');
  res.end(JSON.stringify({ message: 'hello' }));
});

server.listen(8443, () => {
  console.log('https://localhost:8443 で待ち受けています');
});

The client client.mjs just sends a GET request with fetch().

js
const res = await fetch('https://localhost:8443/');
console.log(res.status, await res.text());

With the server running, I ran node client.mjs with no settings. It exited with code 1 and printed the following (paths are placeholders):

text
node:internal/deps/undici/undici:15456
      Error.captureStackTrace(err);
            ^

TypeError: fetch failed
    at node:internal/deps/undici/undici:15456:13
    at process.processTicksAndRejections (node:internal/process/task_queues:103:5)
    at async file:///path/to/app/client.mjs:1:13 {
  [cause]: Error: self-signed certificate
      at TLSSocket.onConnectSecure (node:internal/tls/wrap:1787:34)
      at TLSSocket.emit (node:events:519:28)
      at TLSSocket._finishInit (node:internal/tls/wrap:1176:8)
      at ssl.onhandshakedone (node:internal/tls/wrap:962:12) {
    code: 'DEPTH_ZERO_SELF_SIGNED_CERT'
  }
}

Node.js v22.23.5

The first line, TypeError: fetch failed, does not tell you the cause. The [cause] line shows that certificate verification failed during the TLS handshake. self-signed certificate and DEPTH_ZERO_SELF_SIGNED_CERT are OpenSSL verification errors. According to the list of verification errors in the OpenSSL manual, this means the certificate presented is self-signed and no matching certificate is found in the list of trusted certificates.

Trusting the certificate with NODE_EXTRA_CA_CERTS

To fix this, add the certificate to the trusted set. In Node.js, if you point the environment variable NODE_EXTRA_CA_CERTS to a PEM certificate file, that certificate is added to the root certificates that are already built in (the NODE_EXTRA_CA_CERTS entry in the Node.js docs).

When I ran the client against the same server with cert.pem specified, no error appeared, the response was printed, and the process exited with code 0.

console
$ NODE_EXTRA_CA_CERTS=cert.pem node client.mjs
200 {"message":"hello"}

What you specify is the server's certificate (the cert.pem that is safe to share). Do not give the client the private key key.pem.

Setting process.env inside the script does not work

NODE_EXTRA_CA_CERTS is read only once, when the Node.js process starts. I tried client-setenv.mjs, which sets it in process.env at the top of the script:

js
process.env.NODE_EXTRA_CA_CERTS = './cert.pem';

const res = await fetch('https://localhost:8443/');
console.log(res.status, await res.text());

Running node client-setenv.mjs printed the same [cause]: Error: self-signed certificate (code: 'DEPTH_ZERO_SELF_SIGNED_CERT') as before and exited with code 1. The official documentation also says that changing process.env.NODE_EXTRA_CA_CERTS while the process is running has no effect on that process. Set this variable in the environment that launches the node command.

Adding the certificate to the OS store and reading it with –use-system-ca

If you want to register the certificate with the OS so that other tools can share it, you can start Node.js with --use-system-ca. According to the –use-system-ca entry, on platforms other than Windows and macOS, it reads certificates from the default files and directories that OpenSSL uses. In Node.js 22, a change that made this option available on platforms other than Windows and macOS is listed in the 22.15.0 changelog.

In the test environment (Ubuntu 24.04), I copied the certificate to /usr/local/share/ca-certificates/ and ran update-ca-certificates.

console
$ sudo cp cert.pem /usr/local/share/ca-certificates/neko-localhost.crt
$ sudo update-ca-certificates

I ran these as root in the test environment, so I did not use sudo there. I omitted the output of update-ca-certificates. After that, running node client.mjs with no options still failed with self-signed certificate. In the test environment, Node.js did not use the OS certificate store by default. With --use-system-ca, it succeeded:

console
$ node --use-system-ca client.mjs
200 {"message":"hello"}

After I removed the registered certificate and re-ran update-ca-certificates --fresh, running with --use-system-ca produced self-signed certificate again.

When you see "self-signed certificate in certificate chain"

The message can end with in certificate chain. In the test environment, I got this message in the following setup. The server's certificate was not self-signed. It was signed by a private CA (certificate authority), and the server also sent that CA's certificate.

To set this up, I created a CA certificate ca.pem named Neko Test CA and used that CA to sign a certificate for localhost. For the server, I passed a file that concatenates the server certificate and the CA certificate (server-chain.mjs. The only difference from server.mjs is the name of the file it reads). The server sent these two certificates:

text
subject=CN = localhost
issuer=CN = Neko Test CA

subject=CN = Neko Test CA
issuer=CN = Neko Test CA

When I ran node client.mjs against this server, the [cause] changed as follows (the other lines were the same as the first message):

text
  [cause]: Error: self-signed certificate in certificate chain
      at TLSSocket.onConnectSecure (node:internal/tls/wrap:1787:34)
      at TLSSocket.emit (node:events:519:28)
      at TLSSocket._finishInit (node:internal/tls/wrap:1176:8)
      at ssl.onhandshakedone (node:internal/tls/wrap:962:12) {
    code: 'SELF_SIGNED_CERT_IN_CHAIN'
  }

In the OpenSSL verification error list, SELF_SIGNED_CERT_IN_CHAIN means the certificate chain could be followed, but no trusted starting point (usually a self-signed root certificate) was found. In this case, what you specify in NODE_EXTRA_CA_CERTS is the CA certificate, not the server certificate:

console
$ NODE_EXTRA_CA_CERTS=ca.pem node client.mjs
200 {"message":"hello"}

When I left NODE_EXTRA_CA_CERTS pointing to the self-signed cert.pem I created first, the result was still the same self-signed certificate in certificate chain.

When the certificate is trusted but you get ERR_TLS_CERT_ALTNAME_INVALID

Even with NODE_EXTRA_CA_CERTS set, a different error can appear depending on how you address the server. I kept the first certificate, which covers only localhost, and changed the URL to https://127.0.0.1:8443/. This is the output. I ran client-ip.mjs, which catches the error and prints err.message along with the code and message of cause:

console
$ NODE_EXTRA_CA_CERTS=cert.pem node client-ip.mjs
fetch failed
ERR_TLS_CERT_ALTNAME_INVALID: Hostname/IP does not match certificate's altnames: IP: 127.0.0.1 is not in the cert's list: 

ERR_TLS_CERT_ALTNAME_INVALID in the Node.js error list means the hostname or IP address you connected to does not match any subjectAltName in the certificate. The certificate is trusted, but the name you connected to is not in it. Either change the URL back to localhost, which is in the certificate, or recreate the certificate with the name you want to use in subjectAltName.

I recreated the certificate with -addext "subjectAltName=DNS:localhost,IP:127.0.0.1" and restarted the server. Both https://127.0.0.1:8443/ and https://localhost:8443/ then returned 200 {"message":"hello"}.

Avoid NODE_TLS_REJECT_UNAUTHORIZED=0, which turns off verification

You can also clear the error by setting NODE_TLS_REJECT_UNAUTHORIZED=0. For comparison, I tried it. The error did go away, but Node.js printed this warning (the process ID changes on each run):

text
(node:3807) Warning: Setting the NODE_TLS_REJECT_UNAUTHORIZED environment variable to '0' makes TLS connections and HTTPS requests insecure by disabling certificate verification.
(Use `node --trace-warnings ...` to show where the warning was created)
200 {"message":"hello"}
Warning

NODE_TLS_REJECT_UNAUTHORIZED=0 turns off certificate verification for every TLS connection in that process. It is not limited to the server you intended to reach. Connections to other external APIs also lose the ability to detect impersonation. The official documentation also states that using this environment variable is strongly discouraged.

If you know which certificate you want to trust, add only that certificate with NODE_EXTRA_CA_CERTS. Verification for all other connections stays in place.

​Posted by 86