{"id":11060,"library":"http-terminator","title":"Graceful HTTP Server Termination","description":"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.","status":"active","version":"3.2.0","language":"javascript","source_language":"en","source_url":"https://github.com/gajus/http-terminator","tags":["javascript","kubernetes","prometheus","typescript"],"install":[{"cmd":"npm install http-terminator","lang":"bash","label":"npm"},{"cmd":"yarn add http-terminator","lang":"bash","label":"yarn"},{"cmd":"pnpm add http-terminator","lang":"bash","label":"pnpm"}],"dependencies":[],"imports":[{"note":"The package is ESM-first since v3.0.0. Use `import` syntax.","wrong":"const createHttpTerminator = require('http-terminator');","symbol":"createHttpTerminator","correct":"import { createHttpTerminator } from 'http-terminator';"},{"note":"This is a type definition. Use `import type` for clarity and to prevent it from being bundled as a runtime dependency.","wrong":"import { HttpTerminatorType } from 'http-terminator';","symbol":"HttpTerminatorType","correct":"import type { HttpTerminatorType } from 'http-terminator';"},{"note":"This type defines the configuration object for `createHttpTerminator`. It's primarily used for type-checking when defining the configuration.","symbol":"HttpTerminatorConfigurationInputType","correct":"import type { HttpTerminatorConfigurationInputType } from 'http-terminator';"}],"quickstart":{"code":"import http from 'http';\nimport { createHttpTerminator } from 'http-terminator';\n\nconst server = http.createServer((req, res) => {\n  console.log(`Received request: ${req.method} ${req.url}`);\n  // Simulate some async work that might take time\n  setTimeout(() => {\n    res.writeHead(200, { 'Content-Type': 'text/plain' });\n    res.end('Hello, World!\\n');\n  }, Math.random() * 1000 + 500); // Between 0.5s and 1.5s\n});\n\nserver.listen(3000, () => {\n  console.log('Server listening on port 3000. Try curl http://localhost:3000');\n});\n\nconst httpTerminator = createHttpTerminator({\n  server,\n  gracefulTerminationTimeout: 10000 // Allow up to 10 seconds for requests to complete\n});\n\nasync function gracefulShutdown() {\n  console.log('Initiating graceful shutdown...');\n  try {\n    await httpTerminator.terminate();\n    console.log('Server gracefully terminated. All connections closed.');\n    process.exit(0);\n  } catch (error) {\n    console.error('Error during graceful shutdown:', error);\n    process.exit(1);\n  }\n}\n\n// Handle OS signals for graceful shutdown\nprocess.on('SIGTERM', gracefulShutdown);\nprocess.on('SIGINT', gracefulShutdown);\n\nconsole.log('Press Ctrl+C or send SIGTERM to shut down gracefully.');","lang":"typescript","description":"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."},"warnings":[{"fix":"Update your project's type definitions to use TypeScript if upgrading from a pre-v3 version. Review any custom type extensions for compatibility.","message":"Version 3.0.0 migrated the entire codebase from Flow to TypeScript. This may require adjustments in projects that rely on Flow types or the internal structure of the package.","severity":"breaking","affected_versions":">=3.0.0"},{"fix":"Ensure your project is running on Node.js v14 or newer to use http-terminator v3.1.0 and above.","message":"Support for Node.js v10 was dropped in version 3.1.0, raising the minimum required Node.js version to v12 (though the package.json specifies `>=14`).","severity":"breaking","affected_versions":">=3.1.0"},{"fix":"Always use `httpTerminator.terminate()` provided by this library for a proper graceful shutdown that handles existing connections and in-flight requests.","message":"Calling `server.close()` directly on an `http.Server` instance will stop it from accepting new connections but will not forcefully close existing ones, leading to potential indefinite hangs, especially with keep-alive connections.","severity":"gotcha","affected_versions":"all"},{"fix":"Adopt `import` statements for `http-terminator`. If your project is CommonJS, consider transpiling or using dynamic `import()`.","message":"Since version 3.0.0, `http-terminator` is primarily an ESM (ECMAScript Module) package. Attempting to use `require()` in a CommonJS module might lead to import errors in some Node.js environments or configurations.","severity":"gotcha","affected_versions":">=3.0.0"},{"fix":"Configure `gracefulTerminationTimeout` to a value appropriate for your application's expected maximum request duration: `createHttpTerminator({ server, gracefulTerminationTimeout: 30000 })`.","message":"The `gracefulTerminationTimeout` option defaults to 5000 milliseconds (5 seconds). If your server has long-running requests or slow external dependencies, this default might be too short, leading to connections being forcefully closed prematurely.","severity":"gotcha","affected_versions":"all"}],"env_vars":null,"last_verified":"2026-04-19T00:00:00.000Z","next_check":"2026-07-18T00:00:00.000Z","problems":[{"fix":"Change your import statement to `import { createHttpTerminator } from 'http-terminator';` and ensure your project is configured for ESM (e.g., `\"type\": \"module\"` in `package.json`).","cause":"`http-terminator` v3+ is an ES Module, but you are trying to import it using CommonJS `require()` syntax.","error":"Error [ERR_REQUIRE_ESM]: require() of ES Module .../node_modules/http-terminator/dist/index.js from ... not supported."},{"fix":"Implement graceful shutdown using `http-terminator.terminate()` in your `SIGTERM`/`SIGINT` handlers, ensuring `httpTerminator` is initialized with your `http.Server` instance.","cause":"You are likely calling the native `server.close()` method or no termination logic at all, which does not handle existing connections.","error":"Server is not shutting down, processes are hanging after receiving termination signals (SIGTERM/SIGINT)."},{"fix":"Increase the `gracefulTerminationTimeout` option when calling `createHttpTerminator()` to allow more time for requests to finish, or investigate why requests are taking so long.","cause":"The `gracefulTerminationTimeout` period expired before all active HTTP connections could complete their requests or close naturally.","error":"UnhandledPromiseRejectionWarning: Error: Server termination timed out. Some connections may have been forcefully closed."}],"ecosystem":"npm"}