Graceful HTTP Server Termination

3.2.0 · active · verified Sun Apr 19

http-terminator provides a robust solution for gracefully shutting down Node.js HTTP(S) servers. Unlike the native `server.close()` method, which simply stops accepting new connections but leaves existing connections open indefinitely (potentially hanging due to keep-alive or long-running requests), this library actively tracks and terminates all connections after a configurable timeout. It ensures that in-flight requests complete their responses and communicates shutdown intent to clients. The current stable version is `3.2.0`, with a release cadence that includes minor and patch updates every few months, reflecting ongoing maintenance and feature additions. Key differentiators include its explicit handling of all connection types, including `http`, `https`, and `http2` servers (since v3.2.0), and its rewrite to TypeScript in v3.0.0, providing robust type definitions.

Common errors

Warnings

Install

Imports

Quickstart

This example demonstrates how to set up a basic HTTP server, integrate `http-terminator` for graceful shutdown, and respond to common OS signals (SIGTERM, SIGINT). It includes a simulated asynchronous request to showcase the termination timeout.

import http from 'http';
import { createHttpTerminator } from 'http-terminator';

const server = http.createServer((req, res) => {
  console.log(`Received request: ${req.method} ${req.url}`);
  // Simulate some async work that might take time
  setTimeout(() => {
    res.writeHead(200, { 'Content-Type': 'text/plain' });
    res.end('Hello, World!\n');
  }, Math.random() * 1000 + 500); // Between 0.5s and 1.5s
});

server.listen(3000, () => {
  console.log('Server listening on port 3000. Try curl http://localhost:3000');
});

const httpTerminator = createHttpTerminator({
  server,
  gracefulTerminationTimeout: 10000 // Allow up to 10 seconds for requests to complete
});

async function gracefulShutdown() {
  console.log('Initiating graceful shutdown...');
  try {
    await httpTerminator.terminate();
    console.log('Server gracefully terminated. All connections closed.');
    process.exit(0);
  } catch (error) {
    console.error('Error during graceful shutdown:', error);
    process.exit(1);
  }
}

// Handle OS signals for graceful shutdown
process.on('SIGTERM', gracefulShutdown);
process.on('SIGINT', gracefulShutdown);

console.log('Press Ctrl+C or send SIGTERM to shut down gracefully.');

view raw JSON →