Node.js Reference ยท HTTP, HTTPS, net, TLS, dgram and dns
Node.js http.Server class
Reference for the http.Server class: listen(), close(), closeIdleConnections(), address(), events like request and clientError, and timeout properties.
http.Server is the object that http.createServer() returns. It extends net.Server, so it owns a listening TCP socket, and it adds HTTP parsing: when a complete request header arrives, the server emits a request event with a request and response object.
You control a server through a few methods (listen(), close(), address()), a set of events, and timeout properties that protect it from slow or stuck clients. You normally create it with http.createServer(), not with new http.Server().
import http from "node:http"; const server = http.createServer((req, res) => res.end("ok")); server.listen(0, "127.0.0.1", () => { console.log(server.address().address); server.close(); });
Try it
Press Run (or Ctrl + Enter) to see the result here.
Program input ยท what you'd type while the program runs
Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or process.stdin), it gets the next line from this box.
Press Run (or Ctrl + Enter) to see the result here.
Program input ยท what you'd type while the program runs
Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or process.stdin), it gets the next line from this box.
Syntax
server.listen(port?: number, host?: string, backlog?: number, callback?: () => void): this server.close(callback?: (err?: Error) => void): this server.closeIdleConnections(): void server.closeAllConnections(): void server.address(): { address: string, family: string, port: number } | string | null server.setTimeout(ms?: number, callback?): this server.listening: boolean
| Property | Description |
|---|---|
keepAliveTimeout |
Idle time before a keep-alive connection is closed. Default 5000 ms. |
headersTimeout |
Time to receive complete request headers. Default 60000 ms. |
requestTimeout |
Time to receive the whole request. Default 300000 ms; 0 disables. |
timeout |
Socket inactivity timeout. Default 0 (none) since Node.js 13. |
maxHeadersCount |
Limit on incoming headers. null means no limit. |
maxRequestsPerSocket |
Requests allowed on one keep-alive connection. Default 0 (unlimited). |
| Event | When it fires |
|---|---|
request |
A complete request header arrived. Arguments: req, res. |
connection |
A new TCP connection opened (before any request). |
listening |
The server started listening. |
close |
The server closed and all connections ended. |
clientError |
A client sent bad HTTP or its socket errored. |
checkContinue |
The client sent Expect: 100-continue. |
upgrade, connect |
Protocol upgrade (WebSocket) or CONNECT request. |
Errors and edge cases:
listen()reports failures such asEADDRINUSEorEACCESthrough anerrorevent, not an exception. Without a listener, the process crashes.address()returnsnullbefore listening and after closing, a string for a Unix socket or pipe, and an object for TCP.close()stops accepting new connections; the callback runs after existing connections end.
Usage notes
server.close()stops new connections and, since Node.js 19, also closes idle keep-alive connections, but it still waits for active requests. UsecloseIdleConnections()orcloseAllConnections()(added in 18.2) when you need a fast, graceful shutdown.- Always listen for
clientErrorin production. The default closes the socket with a400response; a custom handler can send its own reply. - Set
requestTimeoutandheadersTimeoutdeliberately. Together they defend against slow-loris clients that hold connections open with a trickle of bytes. keepAliveTimeoutshould be larger than the idle timeout of any load balancer in front of you, otherwise the balancer can reuse a connection the server just closed and users see random502errors.- A server can listen on a Unix socket path,
listen("/tmp/app.sock"), or take an existing handle. server.listen()is asynchronous. Wait for thelisteningevent (or use its callback) before readingaddress().