Course contentsShow
← Node.js
Lesson 597 of 1,9806. Networking and HTTP FundamentalsFree lesson

Dynamic TLS Certificate Loading

Update certificates at runtime without restarting the server process to ensure zero-downtime rotation.

In this lesson, you will learn how to swap out your server's TLS certificates at runtime without dropping a single connection or restarting your Node.js process.

The Problem with Static Certificates

Usually, when we start a Node.js https server, we pass a key and cert to the https.createServer() method. If those certificates expire or need rotation, the standard approach is to stop the server and start it again. In a high-traffic production environment, this causes a "blip" in availability—exactly what we want to avoid.

The SNICallback Solution

Node.js provides a powerful feature called SNICallback (Server Name Indication). Instead of providing a single static certificate at startup, you provide a callback function. This function is triggered every time a client initiates a TLS handshake.

When the handshake starts, Node.js calls your function with the domain name (servername) the client is requesting. You can then look up the appropriate certificate from your filesystem or a secure cache and return it dynamically.

Implementation Example

Here is how you configure your server to look up credentials on the fly:

const https = require('https');
const tls = require('tls');
const fs = require('fs');

const options = {
  SNICallback: (servername, callback) => {
    // Dynamically read the latest cert from disk
    const cert = fs.readFileSync(`./certs/${servername}.cert`);
    const key = fs.readFileSync(`./certs/${servername}.key`);
    
    // Create a secure context for this specific request
    const secureContext = tls.createSecureContext({ key, cert });
    callback(null, secureContext);
  }
};

https.createServer(options, (req, res) => {
  res.end('Secure, zero-downtime connection!');
}).listen(443);

Why This Matters

By using SNICallback, your server becomes a "live" system. You can update the physical files on your server (e.g., via a deployment script or a certificate manager) and the very next request will automatically pick up the new certificate. This approach is essential for maintaining high availability in micro-service architectures where certificates might rotate frequently due to automated security policies.

Key Takeaway: By using the SNICallback option in your TLS configuration, you delegate certificate retrieval to a function that runs per-handshake, allowing you to update credentials in real-time without ever restarting your server.