keepcalculator

06 Numbers and Powers

Untrusted Certificate: 3 TLS Errors in Node

Card No. 06·81401 · Updated · Standard formula, shown below

When Node.js throws an “untrusted certificate” error, it usually means one of three distinct TLS problems: the certificate is self-signed, the certificate has expired or is not yet valid, or the hostname in the certificate does not match the URL you requested. This article explains how to tell these three apart by reading the exact error message and checking the certificate yourself, then gives you the safe fix for each case.

Background: How TLS Certificate Validation Works in Node

Node.js uses its built-in tls module (and https on top of it) to verify the server’s certificate against a list of trusted root certificates that ships with your operating system. When you connect to https://example.com, Node performs three checks in order:

  • Chain of trust – the server’s certificate must be signed by a certificate authority (CA) that Node trusts, either directly or through intermediate certificates.
  • Validity period – the certificate’s notBefore and notAfter dates must include the current time.
  • Hostname match – the certificate’s subjectAltName (or legacy commonName) must match the hostname in the URL.

If any of these fail, Node aborts the TLS handshake and emits an error with a code like UNABLE_TO_VERIFY_LEAF_SIGNATURE, CERT_HAS_EXPIRED, or ERR_TLS_CERT_ALTNAME_INVALID. The good news: the error code is your first clue. The better news: you can always inspect the actual certificate to confirm.

Error 1: Self-Signed or Unknown CA (UNABLE_TO_VERIFY_LEAF_SIGNATURE)

This is the most common “untrusted” error. It means Node cannot find a path from the server’s certificate to a trusted root CA. This happens with:

  • Self-signed certificates (common in development and internal tools).
  • Certificates signed by a private CA that isn’t installed on your system.
  • Missing intermediate certificates on the server (the server sends only its leaf certificate, not the chain).

The error message usually looks like:

Error: self signed certificate
    at TLSSocket.onConnectSecure (node:_tls_wrap.js:...)
    at ...
  code: 'UNABLE_TO_VERIFY_LEAF_SIGNATURE'

To confirm, run openssl s_client -connect host:port -showcerts and look at the output. If the certificate’s subject and issuer are the same, it’s self-signed. If the issuer is a name you don’t recognize, it’s a private CA. If the server sends only one certificate but the issuer is a public CA, the chain is incomplete.

Error 2: Expired or Not-Yet-Valid Certificate (CERT_HAS_EXPIRED)

This error is exactly what it sounds like: the certificate’s validity window does not include the current date. It can happen when a certificate has expired, or when your system clock is wrong (too far ahead or behind). The error code is CERT_HAS_EXPIRED and the message often says certificate has expired.

To check the dates, use:

openssl s_client -connect example.com:443 -servername example.com 2>/dev/null | openssl x509 -noout -dates

This prints notBefore and notAfter. Compare those with your current system date (date on Linux/macOS, Get-Date on Windows). If the dates are fine but Node still complains, your system clock is likely off – fix that first, because a wrong clock breaks many other TLS operations too.

Error 3: Hostname Mismatch (ERR_TLS_CERT_ALTNAME_INVALID)

This error means the certificate is valid and trusted, but it was issued for a different hostname. For example, you connect to https://api.example.com but the certificate only covers www.example.com. Node’s error code is ERR_TLS_CERT_ALTNAME_INVALID and the message typically includes the expected hostname and the actual certificate names.

To see the names the certificate covers:

openssl s_client -connect example.com:443 -servername example.com 2>/dev/null | openssl x509 -noout -text | grep -A1 "Subject Alternative Name"

You’ll see a list like DNS:example.com, DNS:www.example.com. If your hostname isn’t there, that’s the mismatch. This often happens when a server hosts multiple sites on one IP and you didn’t send the correct SNI (Server Name Indication) – Node sends SNI automatically based on the URL, but if you’re using a custom agent or connecting via IP, it may send the wrong name.

How to Fix Each Error (Safely)

The fix depends on which error you have. Never disable certificate validation globally in production – that opens you to man-in-the-middle attacks. Instead, do one of the following:

  • Self-signed / unknown CA: If you control the server, add the CA certificate to your system’s trust store (on Linux, copy it to /usr/local/share/ca-certificates/ and run update-ca-certificates; on macOS, add it to Keychain and mark it as trusted). For a one-off connection, pass the CA file to Node via the ca option in tls.connect() or https.request(). Example: ca: fs.readFileSync('my-ca.pem').
  • Expired: Renew the certificate on the server. If it’s a public site, the administrator needs to get a new one from their CA. If it’s your own test cert, generate a new one with a longer validity period (e.g., openssl req -x509 -newkey rsa:2048 -days 365 -keyout key.pem -out cert.pem).
  • Hostname mismatch: Use the exact hostname that the certificate covers. If you’re testing locally, add an entry to your /etc/hosts file mapping that hostname to 127.0.0.1. If you’re connecting to an IP, consider using servername option in Node to send the correct SNI: servername: 'api.example.com'.

Common Misconception: “Just set rejectUnauthorized: false”

Many tutorials tell you to set rejectUnauthorized: false in your https.request options. That disables all three checks at once, and it’s almost never the right answer. It’s only acceptable for a quick local test against a self-signed cert that you generated yourself, and even then you should remove it before committing. The proper way is to supply the correct CA or fix the hostname. If you’re debugging a third-party API that suddenly gives this error, the server likely changed its certificate – contact the provider rather than bypassing validation.

How to Inspect a Certificate Programmatically in Node

If you want to see exactly what Node sees, you can use the tls module to capture the peer certificate during the handshake:

const tls = require('tls');
const socket = tls.connect({
  host: 'example.com',
  port: 443,
  servername: 'example.com'
}, () => {
  const cert = socket.getPeerCertificate();
  console.log(cert.subject);
  console.log(cert.issuer);
  console.log(cert.valid_from, cert.valid_to);
  console.log(cert.subjectaltname);
  socket.end();
});
socket.on('error', (err) => console.error(err.message));

This prints the certificate’s subject, issuer, validity dates, and the subject alternative names. Compare those with the error code you got and you’ll know exactly which of the three problems you have.

Frequently Asked Questions

Why does the same certificate work in my browser but not in Node?

Browsers use their own root store (and sometimes a different set of intermediate certificates) than Node. If your browser has a private CA installed but your OS doesn’t, Node won’t trust it. Also, browsers are more lenient with hostname mismatches in some cases (e.g., they may still show a warning but allow you to click through). Node is strict by default.

Can I get the error code from the callback instead of the message?

Yes. In https.request, the error object has a code property. Check err.code – it will be one of the three codes mentioned above. This is more reliable than parsing the message text, which can vary between Node versions.

What if the error says “unable to verify the first certificate”?

That’s a variant of the self-signed/unknown CA problem. It usually means the server sent a certificate chain that doesn’t include the root CA, or the root CA is not in your trust store. The fix is the same: supply the correct CA file or install it system-wide.

Does NODE_TLS_REJECT_UNAUTHORIZED=0 work the same as rejectUnauthorized: false?

Yes, it sets the same global flag. It disables all certificate validation for all HTTPS requests in that process. It’s a blunt tool and should never be used in production. Prefer the per-request ca option.

How do I fix a certificate that’s valid but for the wrong environment (e.g., staging vs production)?

That’s a hostname mismatch. The certificate was issued for staging.example.com but you’re connecting to api.example.com. Either use the correct hostname, or if you’re in control, get a certificate that covers both names (a wildcard or SAN certificate).

Related

Method: the standard formula for this calculation, rounded as each result states. See how the calculators work or report an error.

More cards in this drawer

The whole Numbers and Powers drawer →