{"id":11058,"library":"http-shutdown","title":"HTTP Shutdown","description":"http-shutdown is a Node.js library designed for gracefully shutting down HTTP servers, addressing shortcomings of the native `server.close()` method. Unlike `server.close()` which only terminates the listening socket and waits for existing connections, `http-shutdown` actively closes idle keep-alive sockets and waits for all in-flight requests to complete before closing their associated sockets. This ensures no new requests are accepted and all current requests finish cleanly. The library, currently at version 1.2.2, appears to be in a maintenance phase with infrequent but stable releases. It offers two primary integration methods: explicitly wrapping an `http.Server` instance or extending the `http.Server` prototype with a `withShutdown()` method. It ships with TypeScript types, facilitating its use in modern TypeScript projects.","status":"maintenance","version":"1.2.2","language":"javascript","source_language":"en","source_url":"https://github.com/thedillonb/http-shutdown","tags":["javascript","http","https","graceful","force","shutdown","typescript"],"install":[{"cmd":"npm install http-shutdown","lang":"bash","label":"npm"},{"cmd":"yarn add http-shutdown","lang":"bash","label":"yarn"},{"cmd":"pnpm add http-shutdown","lang":"bash","label":"pnpm"}],"dependencies":[],"imports":[{"note":"The package is primarily a CommonJS module. For ESM, use a default import. It's a function that takes an `http.Server` instance and returns an augmented server.","wrong":"import { httpShutdown } from 'http-shutdown';","symbol":"httpShutdown (function)","correct":"import httpShutdown from 'http-shutdown';"},{"note":"The `extend` method modifies the `http.Server.prototype` globally to add a `.withShutdown()` method. It is not a named export.","wrong":"import { extend } from 'http-shutdown';","symbol":"extend()","correct":"import httpShutdown from 'http-shutdown'; httpShutdown.extend();"},{"note":"Use this type for `http.Server` instances that have been augmented with `http-shutdown` functionality, providing access to the `.shutdown()` method.","symbol":"WithShutdownServer (type)","correct":"import type { WithShutdownServer } from 'http-shutdown';"}],"quickstart":{"code":"import * as http from 'http';\nimport httpShutdown, { WithShutdownServer } from 'http-shutdown';\n\n// Create the http server\nlet server: http.Server | WithShutdownServer = http.createServer((req, res) => {\n  if (req.url === '/heavy-task') {\n    // Simulate a long-running request\n    console.log('Incoming heavy task request...');\n    setTimeout(() => {\n      res.writeHead(200, { 'Content-Type': 'text/plain' });\n      res.end('Heavy task completed!');\n      console.log('Heavy task finished.');\n    }, 2500);\n  } else {\n    res.writeHead(200, { 'Content-Type': 'text/plain' });\n    res.end('Hello from http-shutdown!');\n  }\n});\n\n// Wrap the server object with additional functionality.\nserver = httpShutdown(server);\n\nconst PORT = 3000;\n\n// Listen on a port and start taking requests.\nserver.listen(PORT, () => {\n  console.log(`Server listening on http://localhost:${PORT}`);\n  console.log('Try accessing / and /heavy-task. Server will attempt graceful shutdown in 7 seconds...');\n\n  // Sometime later... initiate graceful shutdown.\n  setTimeout(() => {\n    console.log('Initiating graceful shutdown...');\n    (server as WithShutdownServer).shutdown((err) => {\n      if (err) {\n        console.error('Shutdown failed:', err.message);\n        process.exit(1);\n        return;\n      }\n      console.log('Everything is cleanly shutdown.');\n      process.exit(0);\n    });\n  }, 7000);\n});\n\n// Handle common process termination signals for robust shutdown\nprocess.on('SIGTERM', () => {\n  console.log('SIGTERM received, initiating shutdown.');\n  (server as WithShutdownServer).shutdown((err) => {\n    if (err) {\n      console.error('Shutdown failed on SIGTERM:', err.message);\n      process.exit(1);\n      return;\n    }\n    console.log('Everything is cleanly shutdown after SIGTERM.');\n    process.exit(0);\n  });\n});\n\nprocess.on('SIGINT', () => {\n  console.log('SIGINT received, initiating shutdown.');\n  (server as WithShutdownServer).shutdown((err) => {\n    if (err) {\n      console.error('Shutdown failed on SIGINT:', err.message);\n      process.exit(1);\n      return;\n    }\n    console.log('Everything is cleanly shutdown after SIGINT.');\n    process.exit(0);\n  });\n});","lang":"typescript","description":"Demonstrates how to explicitly wrap an `http.Server` instance with `http-shutdown` for graceful termination. This example includes simulating a long-running request, initiating shutdown after a delay, and correctly handling common OS termination signals (`SIGINT`, `SIGTERM`) to ensure all connections are closed cleanly."},"warnings":[{"fix":"Thoroughly test `http-shutdown` with your `https.Server` setup. The core logic typically applies, but any HTTPS-specific connection management or protocol nuances might require extra consideration.","message":"The library is primarily designed for `http.Server`. While it often works with `https.Server` due to underlying `net.Server` wrapping, ensure thorough testing for your specific HTTPS configuration.","severity":"gotcha","affected_versions":">=1.0.0"},{"fix":"Choose one integration method: either explicitly wrap each `http.Server` instance (`server = httpShutdown(server);`) or use `require('http-shutdown').extend();` once to augment the `http.Server.prototype` globally, then call `.withShutdown()` on your server instances. Do not do both for the same server or in the same application.","message":"Mixing the `extend()` method with direct server wrapping (`server = httpShutdown(server)`) can lead to confusing behavior or conflicts.","severity":"gotcha","affected_versions":">=1.0.0"},{"fix":"Ensure the `http.Server` is in a listening state before invoking `shutdown()`. While the library generally handles multiple calls gracefully, it's best practice to design your application's shutdown logic to trigger `shutdown()` only once, typically in response to process signals like `SIGINT` or `SIGTERM`.","message":"Calling `shutdown()` too early (e.g., before the server is fully listening) or multiple times on the same instance can lead to unexpected behavior or redundant operations.","severity":"gotcha","affected_versions":">=1.0.0"},{"fix":"For ESM environments, use the default import syntax: `import httpShutdown from 'http-shutdown';`. If you need to access `.extend()`, call it from the default import: `httpShutdown.extend();`. Ensure your `tsconfig.json` or bundler settings (e.g., `esModuleInterop`) are configured correctly for interoperability.","message":"As a CommonJS-first library, direct ESM named imports might not work as expected without proper configuration or bundler handling.","severity":"gotcha","affected_versions":">=1.0.0"}],"env_vars":null,"last_verified":"2026-04-19T00:00:00.000Z","next_check":"2026-07-18T00:00:00.000Z","problems":[{"fix":"Ensure you have either explicitly wrapped your server with `server = httpShutdown(server);` or called `require('http-shutdown').extend();` and subsequently `server = http.createServer(...).withShutdown();` before attempting to call `server.shutdown()`.","cause":"The `http.Server` instance was not properly augmented with `http-shutdown` functionality.","error":"`server.shutdown is not a function`"},{"fix":"Make sure you call `require('http-shutdown').extend();` (or `httpShutdown.extend();` for ESM) once at the application's entry point, and then chain `.withShutdown()` directly after creating your server: `server = http.createServer(...).withShutdown();`.","cause":"When using the `extend()` method, the `withShutdown()` method was not chained onto the `http.Server` instance, or `extend()` itself was not called globally.","error":"`TypeError: Cannot read properties of undefined (reading 'shutdown')` (or similar related to `withShutdown`)"},{"fix":"Always rely exclusively on the callback provided to `httpShutdown.shutdown(callback)` for knowing when the server has gracefully and completely shut down. Place all post-shutdown cleanup logic within this callback.","cause":"Relying on the native `server.on('close', ...)` event for post-shutdown cleanup logic can cause race conditions, as `server.close()` might be called internally before `http-shutdown` has finished closing all active and idle connections.","error":"Server `close` event fires unexpectedly early, before all connections are handled by `http-shutdown`."}],"ecosystem":"npm"}