In Node.js, what does tls.connect() verify by default, and why can it fail with ERR_TLS_CERT_ALTNAME_INVALID when https.get() to the same host succeeds?
answer
- rejectUnauthorized defaults to true
- chain first, then host name
- SNI is opt-in here
- https fills in servername
- ca replaces, it does not add
basics
~20 stls.connect() refuses the connection unless the certificate chains to a trusted CA and matches the host name. Unlike https, it sends no SNI without servername, so a server hosting many names may present its default certificate, failing the name check.
solid answer
~40 sWith the default `rejectUnauthorized: true`, `tls.connect()` checks that the server's certificate chains to a trusted CA, then calls `tls.checkServerIdentity()` against `servername`, or `host` when no `servername` is set. A failure destroys the socket with an `'error'` whose `code` names the problem. The catch is SNI: `tls.connect()` does not send Server Name Indication unless you pass `servername`, while the https agent fills it in from the request's host. An endpoint serving many names then presents its default certificate, and the name check fails with `ERR_TLS_CERT_ALTNAME_INVALID`. The fix is `servername: host`. The trusted CAs are Node's bundled roots plus `NODE_EXTRA_CA_CERTS`, or the system store with `--use-system-ca`; a `ca` option replaces them rather than adding to them. Never fix a failure with `rejectUnauthorized: false` or `NODE_TLS_REJECT_UNAUTHORIZED=0`, which switch verification off.
code
javascript · 11 linesimport tls from 'node:tls';
const host = 'devices.example.com';
const socket = tls.connect({ host, port: 7443, servername: host }, () => {
console.log(`authorized=${socket.authorized} protocol=${socket.getProtocol()}`);
});
socket.on('error', (err) => {
console.error(`TLS failed: ${err.code}`);
});go deeper
Recall that Node verifies TLS certificates by default and that turning that off with rejectUnauthorized: false is not a fix.
Explain the two checks, chain then host name, the SNI difference between tls.connect() and https, and where the trusted CA list comes from.
Diagnose from err.code: tell a missing intermediate from an untrusted private root from a name mismatch, and pick the fix that keeps verification on.
Set the team rule for private CAs: one supported way to add trust, such as NODE_EXTRA_CA_CERTS or the system store, and a ban on disabling verification enforced in code review.
## What the client checks, in order `tls.connect(options[, callback])` from `node:tls` opens a TCP connection, or wraps an existing `socket`, and runs a TLS handshake over it. It returns a `tls.TLSSocket`, and the callback becomes a listener for `'secureConnect'`. With default options a client: 1. Negotiates a protocol version between `tls.DEFAULT_MIN_VERSION` (`'TLSv1.2'`) and `tls.DEFAULT_MAX_VERSION` (`'TLSv1.3'`) unless CLI flags change them. 2. Verifies that the server's certificate **chains to a trusted CA**. A failure here carries an OpenSSL code such as `UNABLE_TO_VERIFY_LEAF_SIGNATURE`. 3. Only if the chain is valid, calls `checkServerIdentity(servername, cert)`, by default `tls.checkServerIdentity()`, against `servername` if you set one, otherwise `host`. A mismatch yields `ERR_TLS_CERT_ALTNAME_INVALID`. 4. Because `rejectUnauthorized` defaults to `true`, any failure destroys the socket with an `'error'`; otherwise `'secureConnect'` fires with `tlsSocket.authorized` set to `true`. ## Where the trusted CAs come from | Source | How it is enabled | Scope | |---|---|---| | Node's bundled root certificates | Default | Every TLS client in the process | | `NODE_EXTRA_CA_CERTS=file` | Environment variable, read at startup | Adds PEM certificates to the default roots | | `--use-system-ca` | CLI flag | Also trusts the operating system's certificate store | | `ca` option | Passed to `tls.connect()` or a secure context | **Replaces** the default list for that connection | The last row is the classic surprise. Passing `ca: [internalRootPem]` to reach an internal service does not add a root; it makes that connection trust **only** the listed certificates, so the same options pointed at a public host fail. The documentation says users must concatenate manually if they want both, and that neither the bundled nor the extra certificates are used when `ca` is set explicitly. ## The SNI trap Server Name Indication is the client telling the server, during the handshake, which host name it wants. Endpoints that terminate TLS for many names use it to pick a certificate. - `tls.connect()` **does not send SNI by default**; the documentation says so in so many words and tells you to set `servername` in addition to `host`. - The https agent computes a `servername` from the request's host (or its `Host` header) unless the host is an IP address, so `https.get()` sends SNI automatically. - The host-name check still runs against `host` when `servername` is missing. So a raw `tls.connect({ host, port })` can receive the endpoint's default certificate and then reject it as not matching `host`. - `servername` must be a host name, never an IP address. ## The server side in brief `tls.createServer({ key, cert })` accepts TLS connections and emits `'secureConnection'` with each `tls.TLSSocket`. To serve several names from one listener, `SNICallback` or `server.addContext()` picks a certificate per requested name, which is exactly why a client that omits SNI can be handed the wrong one. `requestCert: true` makes the server ask clients for certificates (mutual TLS); the server's `rejectUnauthorized` only takes effect then. A handshake that does not finish within `handshakeTimeout`, 120 seconds by default, is aborted. ## Reading the failure | `err.code` | Usual meaning | |---|---| | `UNABLE_TO_VERIFY_LEAF_SIGNATURE` | The server did not send its intermediate certificate, or the issuing CA is not trusted | | `UNABLE_TO_GET_ISSUER_CERT_LOCALLY` | The chain leads to a CA missing from the trusted list | | `SELF_SIGNED_CERT_IN_CHAIN` | A private root appears in the chain but is not trusted locally | | `DEPTH_ZERO_SELF_SIGNED_CERT` | The server certificate is self-signed | | `CERT_HAS_EXPIRED` | The certificate's validity period has ended | | `ERR_TLS_CERT_ALTNAME_INVALID` | The chain is fine but no subject alternative name matches the host | For several of the chain errors, Node appends a hint suggesting `--use-system-ca` when the root is installed locally. ## Fixes that keep verification on - **Set `servername`** to the host name on every raw `tls.connect()`. - **Trust a private CA explicitly**: `NODE_EXTRA_CA_CERTS` for the whole process, or `ca` for one connection, concatenated with the default roots from `tls.getCACertificates()` if public hosts must keep working. - **Fix the server's chain** when it omits intermediates; clients should not paper over it. - **Customise `checkServerIdentity`** only to add checks such as pinning, calling `tls.checkServerIdentity()` inside it rather than replacing it with a function that accepts everything. What not to do: `rejectUnauthorized: false` still encrypts, but to whoever answered, and `NODE_TLS_REJECT_UNAUTHORIZED=0` does the same for every TLS and HTTPS client in the process. Node emits a process warning the first time that variable takes effect, precisely because it is so often left on in production.
- What does rejectUnauthorized: false actually change?Node still runs the chain and host-name checks, but a failure no longer destroys the socket: `'secureConnect'` fires with `tlsSocket.authorized` set to `false` and the reason in `tlsSocket.authorizationError`. Traffic is encrypted to whoever answered, including an interceptor, so the option removes the protection TLS exists to give unless your code checks `authorized` itself.
- How do you trust a private CA without disabling verification?Point `NODE_EXTRA_CA_CERTS` at a PEM file before the process starts, which adds it to the bundled roots for every client, or start Node with `--use-system-ca` if the CA is installed in the operating system's store. For a single connection pass `ca`, remembering that it replaces the default roots, so concatenate them if that connection must also reach public hosts.
- tls.connect() sends SNI from the host option automatically, just like https.
- Passing a ca option adds a private root on top of the bundled certificates.
- rejectUnauthorized: false only skips the host-name check but still validates the chain.
- Setting NODE_TLS_REJECT_UNAUTHORIZED=0 is a safe way to work around an internal CA.
- The 'secureConnect' event always means the server's certificate was trusted.