Skip to content
Tutorials Center
My learning

Topics

Node.js Reference ยท HTTP, HTTPS, net, TLS, dgram and dns

Node.js tls.connect() method

Reference for tls.connect() in Node.js: open an encrypted client connection, verify certificates with ca and servername, ALPN, session reuse and common TLS errors.

tls.connect() opens a TCP connection and runs a TLS handshake over it, returning a tls.TLSSocket. From then on you use it like any net.Socket, but everything is encrypted, and the server has proved its identity with a certificate that Node checked against a list of trusted authorities.

The 'secureConnect' event tells you the handshake finished and the certificate was accepted (or, with rejectUnauthorized: false, ignored). Do not send secrets before it. HTTPS clients and database drivers use this function underneath; you call it directly for custom protocols such as SMTP over TLS or your own services.

NODE
import tls from 'node:tls';

const socket = tls.connect({ host: 'example.com', port: 443 }, () => {
  console.log(socket.authorized);
});

Try it

The examples below create a throwaway self-signed certificate in a temporary folder with the openssl command line tool that the runner provides. In your own code you would use a certificate from a real authority, or a private CA.

Node.js A verified connection

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or process.stdin), it gets the next line from this box.

Node.js Certificate failures

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or process.stdin), it gets the next line from this box.

Syntax

NODE
tls.connect(options: object, secureConnectListener?: () => void): tls.TLSSocket
tls.connect(port: number, host?: string, options?: object, secureConnectListener?: () => void): tls.TLSSocket
tls.connect(path: string, options?: object, secureConnectListener?: () => void): tls.TLSSocket
Name Description
host, port, path Where to connect, as for net.createConnection(). host defaults to 'localhost'.
servername Name sent in the SNI extension and checked against the certificate. Defaults to host when it is a name, not an IP. Set it explicitly when you connect by IP.
ca Trusted certificate(s) as a string, Buffer or array. Replaces the built-in list of public authorities.
cert, key, pfx, passphrase Client certificate and private key for mutual TLS.
rejectUnauthorized Default true. With false, certificate errors are ignored. Never do this in production.
checkServerIdentity(host, cert) Custom host name check; return an Error to reject.
minVersion, maxVersion Protocol limits such as 'TLSv1.2' and 'TLSv1.3'.
ALPNProtocols Array of protocol names to offer, for example ['h2', 'http/1.1'].
session A saved session Buffer to resume (see getSession()).
socket Run TLS over an existing connected socket instead of opening a new one.
ciphers, ecdhCurve, secureContext Fine tuning; a shared tls.createSecureContext() object avoids parsing certificates repeatedly.
timeout, signal, lookup As for net.connect().

Returns: a tls.TLSSocket. Events: 'secureConnect' after a successful handshake, 'error' for network or certificate failures, plus all net.Socket events.

Errors and edge cases: certificate problems carry OpenSSL codes such as DEPTH_ZERO_SELF_SIGNED_CERT, UNABLE_TO_VERIFY_LEAF_SIGNATURE, CERT_HAS_EXPIRED, and ERR_TLS_CERT_ALTNAME_INVALID for a name mismatch. Protocol failures show as ERR_SSL_* codes. Connecting to a plain TCP server gives ERR_SSL_WRONG_VERSION_NUMBER.

Usage notes

  • Never disable verification to "make it work". rejectUnauthorized: false removes the protection against man-in-the-middle attacks. Add the right ca instead.
  • IP addresses need servername. Certificates are issued for names; connecting to an IP with a certificate that lists only a DNS name fails unless you pass the name.
  • ca replaces the defaults. To trust both public authorities and your own, pass [...tls.rootCertificates, myCa].
  • TLS 1.3 is the default maximum. The minimum is tls.DEFAULT_MIN_VERSION (TLS 1.2).
  • Wait for 'secureConnect'. Writes before it are buffered, but you may be talking to an unverified peer when rejectUnauthorized is off.
  • Session reuse speeds up reconnects. Save socket.getSession() and pass it as session later; check socket.isSessionReused().
  • HTTPS is better for HTTP. For web requests use https.request() or fetch(), which wrap this function.