{"id":16373,"library":"http-close","title":"Graceful HTTP Server Shutdown","description":"This `http-close` package for Node.js provides a mechanism to gracefully shut down an HTTP server by managing open TCP sockets. Currently at version 1.0.0, it appears to be a stable utility, likely in maintenance mode given its focused scope and the absence of rapid version increments. It differentiates itself by intelligently handling various socket states during `server.close()`: it destroys keep-alive sockets without active responses, sends `Connection: close` headers for requests where headers haven't been sent, and applies a configurable timeout (default 5 seconds) to pending connections. If a socket times out after `server.close()` has been called, the module intervenes to respond with a 500 status code before ending the connection for requests with unsent headers, and forcefully destroys all other remaining sockets. This ensures a clean exit for the server process, mitigating the common issue of hanging connections during shutdown.","status":"maintenance","version":"1.0.0","language":"javascript","source_language":"en","source_url":"git://github.com/tellnes/http-close","tags":["javascript","typescript"],"install":[{"cmd":"npm install http-close","lang":"bash","label":"npm"},{"cmd":"yarn add http-close","lang":"bash","label":"yarn"},{"cmd":"pnpm add http-close","lang":"bash","label":"pnpm"}],"dependencies":[],"imports":[{"note":"This package ships TypeScript types and primarily uses a default export for its main function, aligning with modern ESM practices.","symbol":"httpClose","correct":"import httpClose from 'http-close';"},{"note":"The primary export is a default function; attempting to import it as a named export will result in `undefined`.","wrong":"import { httpClose } from 'http-close';","symbol":"httpClose"},{"note":"While this CommonJS `require` syntax works, using `import` is preferred in modern TypeScript and ESM-based Node.js projects.","wrong":"const httpClose = require('http-close');","symbol":"httpClose"}],"quickstart":{"code":"import http from 'http';\nimport httpClose from 'http-close';\n\nconst server = http.createServer((req, res) => {\n  // Simulate some async work that might keep the connection open\n  setTimeout(() => {\n    res.writeHead(200, { 'Content-Type': 'text/plain' });\n    res.end('Hello, World!\\n');\n  }, Math.random() * 500); // Random delay up to 500ms\n});\n\n// Add http-close hook with a custom timeout of 3 seconds\nhttpClose({ timeout: 3000 }, server);\n\nserver.listen(3000, () => {\n  console.log('Server listening on port 3000. Try hitting it with requests.');\n  console.log('Then, press Ctrl+C to initiate graceful shutdown.');\n});\n\n// Handle graceful shutdown on process termination signals\nprocess.on('SIGTERM', () => {\n  console.log('SIGTERM received. Initiating graceful shutdown...');\n  server.close(() => {\n    console.log('Server closed. Exiting process.');\n    process.exit(0);\n  });\n});\n\nprocess.on('SIGINT', () => {\n  console.log('SIGINT received. Initiating graceful shutdown...');\n  server.close(() => {\n    console.log('Server closed. Exiting process.');\n    process.exit(0);\n  });\n});","lang":"typescript","description":"This example sets up an HTTP server with `http-close` to manage graceful shutdown. It simulates asynchronous request handling and demonstrates how to hook `http-close` to the server and trigger shutdown via `server.close()` in response to OS signals (SIGTERM/SIGINT), ensuring open connections are handled gracefully with a specified timeout."},"warnings":[{"fix":"Always ensure you call `server.close()` when you intend to shut down your server. `httpClose({ timeout: X }, server)` should be called once after server creation but before `server.close()` is invoked.","message":"The `http-close` module augments the behavior of `server.close()` but does not replace it. You must still explicitly call `server.close()` on your `http.Server` instance to initiate the shutdown process; `http-close` then hooks into this event to manage active sockets.","severity":"gotcha","affected_versions":">=1.0.0"},{"fix":"Consider setting an explicit `timeout` option when initializing `httpClose`. For example: `httpClose({ timeout: 10000 }, server)` for 10 seconds, or `httpClose({ timeout: 1000 }, server)` for 1 second.","message":"The default socket timeout implemented by `http-close` is 5 seconds for pending requests after `server.close()` is called. This default might be too short for applications with long-running requests or too long for scenarios requiring very rapid server shutdowns.","severity":"gotcha","affected_versions":">=1.0.0"},{"fix":"Evaluate if its functionality meets all requirements for modern Node.js applications. Consider alternatives if your project requires active development support, advanced features, or is highly sensitive to the latest platform changes.","message":"This package appears to be in maintenance mode, with its latest version being 1.0.0 and no significant updates observed in recent years. While stable for its defined purpose, it may not actively address new Node.js features, HTTP protocol changes, or complex edge cases that newer, more actively maintained server shutdown solutions might cover.","severity":"gotcha","affected_versions":">=1.0.0"},{"fix":"Ensure client applications are designed to gracefully handle connection termination during server shutdown, especially for services relying heavily on HTTP keep-alive. This behavior is part of the graceful shutdown strategy.","message":"`http-close` is designed to immediately destroy any idle keep-alive sockets (i.e., those without an active HTTP response in progress) once `server.close()` is called. This is an intentional behavior to prevent the server from hanging on unused connections, but it's important to note that clients expecting persistent connections to remain open until explicitly closed by the client will have their idle connections terminated.","severity":"gotcha","affected_versions":">=1.0.0"}],"env_vars":null,"last_verified":"2026-04-22T00:00:00.000Z","next_check":"2026-07-21T00:00:00.000Z","problems":[{"fix":"Verify that `httpClose` is correctly applied to your `http.Server` instance. Ensure you've set an appropriate `timeout` option that allows pending requests to complete while also forcing closure within acceptable bounds. Long-running requests might still delay shutdown until their timeout is reached.","cause":"`server.close()` appears to hang or the callback takes longer than expected to execute, indicating connections are not being released.","error":"Error: server.close() callback not firing or taking too long"},{"fix":"This is expected behavior for requests that cannot complete within the specified `httpClose` timeout during shutdown. Inform clients about scheduled maintenance periods, or increase the `timeout` if these requests are critical and must always attempt to complete gracefully.","cause":"During graceful shutdown, `http-close` sends a 500 status code to pending requests where HTTP headers have not yet been sent, if the socket times out.","error":"Client received unexpected 500 Internal Server Error during server shutdown"},{"fix":"For ESM, use `import httpClose from 'http-close';`. For CommonJS, `const httpClose = require('http-close');`. Always ensure a valid instance of `http.createServer()` result is passed as the second argument: `httpClose({ timeout: 5000 }, yourHttpServerInstance);`.","cause":"This typically occurs if the `httpClose` function is not correctly imported or required, or if `server` is not a valid `http.Server` instance when passed to `httpClose`.","error":"TypeError: Cannot read properties of undefined (reading 'close') or similar errors related to `httpClose`"}],"ecosystem":"npm"}