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

Hot-Reloading Server Code

Design a development runtime that swaps route handlers without dropping active TCP connections.

In this lesson, you will learn how to swap route handlers in a running Node.js server without closing existing TCP connections or restarting the process.

The Challenge of Process Restarts

Normally, if you update your code, you stop the server and start it again. However, this kills all active TCP connections. If a client is in the middle of a long-running request or a WebSocket stream, their session is abruptly severed. To avoid this, we need a way to update the "logic" of our server while keeping the underlying net.Server socket alive.

The Routing Proxy Pattern

The secret is to decouple the Server Listener from the Handler Logic. Instead of assigning a request listener directly to your http.createServer() instance, you point it to a "dispatcher" function. This dispatcher acts as a proxy that forwards requests to the current version of your code.

Consider this minimal setup:

let currentHandler = (req, res) => res.end("Original logic");

const server = http.createServer((req, res) => {
  // Always invoke the handler through a wrapper
  currentHandler(req, res);
});

// Simulate an update
function hotReload(newCode) {
  currentHandler = newCode;
}

Keeping Connections Alive

Because the server object remains active, the TCP connection between the client and your server is never closed. When the http module receives a request, it invokes the currentHandler currently held in memory. When you update the logic, you simply replace the reference inside the currentHandler variable. The next request arriving on the same open TCP connection will instantly execute the new code.

This pattern is a foundational step in building "zero-downtime" development environments. By shifting the logic into a mutable container, you effectively separate the lifecycle of the infrastructure (the TCP port) from the lifecycle of the application (the business logic).

Key Takeaway: By using a mutable reference to route requests to dynamic handler functions, you can update your server logic in real-time while maintaining active TCP connections.