Graceful HTTP(S) Server Terminator

1.2.3 · active · verified Wed Apr 22

lil-http-terminator is a minimalistic, zero-dependency Node.js library designed for gracefully shutting down HTTP and HTTPS servers. Currently at stable version 1.2.3, it offers a consistent, promise-based API for managing server connections during shutdown. Its core differentiator lies in its low footprint (11 KB), absence of external dependencies, and a design that prioritizes robustness: it never throws exceptions during termination, instead resolving with a `{success, code, message, error}` object. Unlike some alternatives, it guarantees termination by timing out if connections linger, and it avoids monkey-patching Node.js core APIs. The library is actively maintained, with recent updates ensuring compatibility with newer Node.js features like `server.closeIdleConnections()`.

Common errors

Warnings

Install

Imports

Quickstart

This quickstart demonstrates how to set up a basic HTTP server and integrate `lil-http-terminator` for graceful shutdown upon receiving SIGTERM or SIGINT signals, logging the termination result.

const http = require('http');
const createHttpTerminator = require('lil-http-terminator');

const server = http.createServer((req, res) => {
  console.log(`Request received: ${req.method} ${req.url}`);
  setTimeout(() => {
    res.writeHead(200, { 'Content-Type': 'text/plain' });
    res.end('Hello from lil-http-terminator!\n');
  }, 500);
});

const httpTerminator = createHttpTerminator({
  server: server,
  gracefulTerminationTimeout: 1000,
  maxWaitTimeout: 5000,
  logger: console,
});

server.listen(3000, () => {
  console.log('Server listening on http://localhost:3000');
  console.log('Send SIGTERM or SIGINT to gracefully shut down.');
});

async function shutdown(signal) {
  console.log(`\nReceived ${signal}. Initiating graceful shutdown...`);
  const { success, code, message, error } = await httpTerminator.terminate();
  if (success) {
    console.log(`HTTP server closure successful.`);
  } else {
    console.error(`HTTP server closure failed: ${code} - ${message}`, error || '');
  }
  process.exit(success ? 0 : 1);
}

process.on('SIGTERM', shutdown); // Used by K8s, AWS ECS, etc.
process.on('SIGINT', shutdown);  // Atom, VSCode, WebStorm or Terminal Ctrl+C

view raw JSON →