Comprehensive Guide to TLS/SSL in Node.js

The node:tls module provides Node.js with a full implementation of the TLS (Transport Layer Security) and SSL (Secure Socket Layer) protocols, built on top of OpenSSL. It enables encrypted communication, certificate handling, authentication, perfect forward secrecy, ALPN, SNI, PSK, session resumption, and fine‑grained control over cipher suites and security levels. This module is essential for building secure servers, HTTPS services, and encrypted TCP connections.

TLS / SSLOpenSSLCertificates & Private KeysPerfect Forward SecrecyALPN / SNIPSK (Pre‑Shared Keys)Session Resumption

~3 min read · Updated Dec 30, 2025

1. Introduction


The node:tls module enables encrypted communication in Node.js. It works similarly to TLS implementations in browsers but is built directly on OpenSSL.


2. Detecting Missing Crypto Support


If Node.js is built without node:crypto, importing node:tls will throw an error. In CommonJS, this can be handled with try/catch. In ESM, use dynamic import() to safely load the module.


3. TLS/SSL Concepts


  • TLS/SSL relies on PKI (Public Key Infrastructure).
  • Servers must have a private key.
  • Certificates are public keys signed by a CA or self‑signed.
  • OpenSSL is used to generate keys, CSRs, certificates, and PFX files.

4. Perfect Forward Secrecy (PFS)


PFS ensures that even if a server’s private key is compromised, past communications remain secure.


  • ECDHE: Enabled by default.
  • DHE: Disabled by default; can be enabled.
  • Mandatory in TLS 1.3 (except PSK‑only connections).

5. ALPN and SNI


  • ALPN: Negotiates protocols like HTTP/1.1 or HTTP/2 during handshake.
  • SNI: Allows multiple hostnames with different certificates on one server.

6. Pre‑Shared Keys (PSK)


PSK provides certificate‑less authentication using shared secrets.


  • Disabled by default.
  • Requires pskCallback on both client and server.
  • Suitable only when secure key distribution is possible.

7. Renegotiation Attack Mitigation


Client‑initiated renegotiation is limited to prevent DoS attacks.


  • tls.CLIENT_RENEG_LIMIT: Default 3.
  • tls.CLIENT_RENEG_WINDOW: Default 600 seconds.

8. Session Resumption


Speeds up TLS handshakes by reusing session state.


8.1 Session Identifiers


  • Client and server store session state.
  • Server must handle newSession and resumeSession.

8.2 Session Tickets


  • Server encrypts session state and sends it to the client.
  • No server‑side session cache required.
  • Multiple tickets may be sent in TLS 1.3.

9. Modifying Cipher Suites


Node.js ships with a secure default cipher suite.


  • View defaults: crypto.constants.defaultCoreCipherList
  • Override via --tls-cipher-list or tls.DEFAULT_CIPHERS
  • Use ciphers option in tls.createSecureContext() for per‑server control.

10. OpenSSL Security Levels


Security levels range from 0 to 5. Default is 2.


Legacy protocols (e.g., TLSv1) require lowering the level:


ciphers: 'DEFAULT@SECLEVEL=0'

11. X509 Certificate Error Codes


OpenSSL may return errors such as:


  • UNABLE_TO_VERIFY_LEAF_SIGNATURE
  • CERT_HAS_EXPIRED
  • SELF_SIGNED_CERT_IN_CHAIN
  • HOSTNAME_MISMATCH

12. The tls.Server Class


Extends net.Server and provides TLS‑specific events and methods.


12.1 Key Events


  • connection: Before handshake.
  • secureConnection: After handshake completes.
  • newSession: New session created.
  • resumeSession: Attempt to resume a session.
  • OCSPRequest: Client requests certificate status.
  • keylog: Emits key material for debugging (e.g., Wireshark).
  • tlsClientError: Error before handshake.

12.2 Important Methods


  • server.addContext(): Add SNI‑based certificate contexts.
  • server.setSecureContext(): Replace server certificates at runtime.
  • server.getTicketKeys(): Retrieve session ticket keys.
  • server.listen(): Start listening for TLS connections.
  • server.close(): Stop accepting new connections.

Conclusion


The node:tls module is a foundational security component in Node.js. It enables encrypted communication, certificate management, authentication, perfect forward secrecy, ALPN, SNI, PSK, session resumption, and fine‑grained control over cipher suites and OpenSSL security levels. With its extensive features and strong defaults, it is well‑suited for building secure, production‑grade network services.


Written & researched by Dr. Shahin Siami

Related Articles

Comprehensive Guide to the Node.js VM Module (node:vm)

The node:vm module allows you to compile and execute JavaScript code inside isolated V8 contexts — essentially creating lightweight sandboxes within your Node.js application. These contexts have their own global scope and can run code independently from the main environment. However, vm is NOT a security sandbox. It is powerful for dynamic code execution, template engines, REPLs, plugin systems, and controlled module execution, but it must never be used to run untrusted code.

Continue

Comprehensive Guide to the V8 Module in Node.js (node:v8)

The node:v8 module exposes low-level APIs that interact directly with the V8 JavaScript engine embedded in Node.js. . These APIs provide access to heap statistics, heap snapshots, coverage tools, serialization mechanisms, V8 flags, object queries, and promise lifecycle hooks. The module is essential for performance analysis, memory debugging, tooling, and advanced Node.js internals work.

Continue

Comprehensive Guide to Node.js Worker Threads (node:worker_threads)

The node:worker_threads module enables true multithreading in Node.js by running JavaScript in separate threads. While Node.js is traditionally single‑threaded, worker threads allow CPU‑intensive tasks to run in parallel without blocking the event loop. They support shared memory, zero‑copy transfers, worker pools, resource limits, and advanced synchronization APIs. Worker threads are ideal for heavy computation, data processing, and parallel workloads—while async I/O remains best handled by the main thread.

Continue

Comprehensive Guide to the Node.js util Module (node:util)

The node:util module provides a powerful collection of helper functions used throughout Node.js core and extremely useful for application developers. These utilities support debugging, inspection, formatting, type checking, callback/Promise conversions, argument parsing, text encoding, MIME handling, and more. It is one of the most versatile and essential toolkits in the Node.js ecosystem.

Continue

Comprehensive Guide to the URL Module in Node.js

The node:url module provides tools for parsing, constructing, and manipulating URLs. Node.js supports two URL APIs: WHATWG URL API — modern, browser‑compatible, standards‑based. Legacy Node.js URL API — older, Node‑specific, now discouraged. The WHATWG API is the recommended approach for all modern applications. It provides a clean, consistent interface for working with URL components, query parameters, and structured URL patterns.

Continue

راهنمای جامع UDP / Datagram Sockets در Node.js

ماژول node:dgram پیاده‌سازی کامل سوکت‌های UDP را در Node.js فراهم می‌کند. UDP یک پروتکل سبک، بدون اتصال (connectionless) و مناسب برای برنامه‌های بلادرنگ مانند VoIP، بازی‌ها، IoT، سیستم‌های پخش (broadcast) و چندپخشی (multicast) است. این ماژول امکان ساخت سوکت، ارسال و دریافت دیتاگرام، مدیریت TTL، عضویت در گروه‌های multicast، کنترل بافرها، و مدیریت رفتار سطح پایین شبکه را فراهم می‌کند.

Continue