When you call server.close(), it stops the server from accepting new connections, but it keeps the existing connections open indefinitely. This can result in your server hanging indefinitely due to keep-alive connections or because of the ongoing requests that do not produce a response. Therefore, in order to close the server, you must track creation of all connections and terminate them yourself.
http-terminator implements the logic for tracking all connections and their termination upon a timeout. http-terminator also ensures graceful communication of the server intention to shutdown to any clients that are currently receiving response from this server.
API
import { createHttpTerminator,} from 'http-terminator';/** * @property gracefulTerminationTimeout Number of milliseconds to allow for the active sockets to complete serving the response (default: 5000). * @property server Instance of http.Server. */type HttpTerminatorConfigurationInputType = {| +gracefulTerminationTimeout?: number, +server: Server,|};/** * @property terminate Terminates HTTP server. */type HttpTerminatorType = {| +terminate: () => Promise<void
Usage
Use createHttpTerminator to create an instance of http-terminator and instead of using server.close(), use httpTerminator.terminate(), e.g.
import http from 'http';import { createHttpTerminator,} from 'http-terminator';const server = http.createServer();const httpTerminator = createHttpTerminator({ server,});await httpTerminator.terminate();
import Koa from 'koa';import { createHttpTerminator,} from 'http-terminator';const app = new Koa();const server = app.listen();const httpTerminator = createHttpTerminator({ server,});await httpTerminator.terminate();
Usage with other HTTP frameworks
As it should be clear from the usage examples for Node.js HTTP server, Express and Koa, http-terminator works by accessing an instance of a Node.js http.Server. To understand how to use http-terminator with your framework, identify how to access an instance of http.Server and use it to create a http-terminator instance.
Alternative libraries
There are several alternative libraries that implement comparable functionality, e.g.