Skip to content
Tutorials Center
My learning

Topics

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

Node.js tls.createServer() method

Reference for tls.createServer() in Node.js: key and cert options, SNI with addContext, client certificates, ALPN, protocol versions and the secureConnection event.

tls.createServer() creates a TCP server that speaks TLS. It is a net.Server with encryption added: each accepted connection performs a handshake with the certificate and private key you supply, and your listener receives a tls.TLSSocket once that handshake is complete.

The HTTPS server is built on this function: https.createServer() is tls.createServer() plus HTTP parsing. Use tls directly for custom encrypted protocols, or when you need control over the handshake, for example to require client certificates.

NODE
import tls from 'node:tls';
import fs from 'node:fs';

const server = tls.createServer({
  key: fs.readFileSync('key.pem'),
  cert: fs.readFileSync('cert.pem'),
}, (socket) => socket.end('hello\n'));
server.listen(8443);

Try it

Node.js Mutual TLS with a client certificate

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 Picking a certificate by server name (SNI)

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.createServer(options?: object, secureConnectionListener?: (socket: tls.TLSSocket) => void): tls.Server
Name Description
key, cert Private key and certificate chain in PEM form (string, Buffer or arrays). Alternatively pfx and passphrase.
ca Certificates used to verify client certificates. Replaces the built-in list.
requestCert Ask clients for a certificate. Default false.
rejectUnauthorized With requestCert, refuse clients whose certificate cannot be verified. Default true.
SNICallback(servername, cb) Choose a secure context per requested name; cb(null, ctx).
ALPNProtocols Protocols you accept, in preference order.
minVersion, maxVersion Limits such as 'TLSv1.2'.
ciphers, honorCipherOrder, dhparam, ecdhCurve Cipher and key-exchange settings.
sessionTimeout, ticketKeys Session resumption control; share ticketKeys across processes.
handshakeTimeout Milliseconds to wait for a handshake. Default 120000.
allowHalfOpen, pauseOnConnect, noDelay, keepAlive As for net.createServer().

Returns: a tls.Server. Events: 'secureConnection' (the listener), 'tlsClientError' (a failed handshake, with the socket), 'newSession', 'resumeSession', 'keylog', plus the net.Server events. Method server.addContext(hostname, context) adds a certificate for a name, and server.setSecureContext() replaces the default one at runtime (for example after certificate renewal).

Errors and edge cases: invalid PEM data throws when the server is created (or when the context is built). A failed handshake never reaches your connection listener; it is reported through 'tlsClientError' instead, with codes such as ERR_SSL_PEER_DID_NOT_RETURN_A_CERTIFICATE or ERR_SSL_WRONG_VERSION_NUMBER (a plain-text client).

Usage notes

  • Keep private keys private. Read them from files with strict permissions or a secret store, never from the repository.
  • Handshake errors are normal. Scanners, plain HTTP clients and outdated browsers produce them constantly. Handle 'tlsClientError', or they are only visible as dropped connections.
  • Renew without restart. Call server.setSecureContext({ key, cert }) when a certificate is renewed; new connections use it, existing ones continue.
  • Client certificates. requestCert: true with rejectUnauthorized: false lets you inspect socket.authorized yourself, which is useful for optional authentication.
  • Intermediate certificates. Put the whole chain (leaf first) in cert, or clients may fail with UNABLE_TO_VERIFY_LEAF_SIGNATURE.
  • Ports below 1024 need privileges; terminate TLS in a reverse proxy or use a high port.
  • Prefer a proxy for production web traffic. Nginx, Caddy or a load balancer terminate TLS better than hand-written code; use tls for custom protocols and internal services.