Node.js v26.0.0 documentation
- Node.js v26.0.0
- Table of contents
- HTTP
- Class:
http.Agent - Class:
http.ClientRequest- Event:
'abort' - Event:
'close' - Event:
'connect' - Event:
'continue' - Event:
'finish' - Event:
'information' - Event:
'response' - Event:
'socket' - Event:
'timeout' - Event:
'upgrade' request.abort()request.abortedrequest.connectionrequest.cork()request.end([data[, encoding]][, callback])request.destroy([error])request.finishedrequest.flushHeaders()request.getHeader(name)request.getHeaderNames()request.getHeaders()request.getRawHeaderNames()request.hasHeader(name)request.maxHeadersCountrequest.pathrequest.methodrequest.hostrequest.protocolrequest.removeHeader(name)request.reusedSocketrequest.setHeader(name, value)request.setNoDelay([noDelay])request.setSocketKeepAlive([enable][, initialDelay])request.setTimeout(timeout[, callback])request.socketrequest.uncork()request.writableEndedrequest.writableFinishedrequest.write(chunk[, encoding][, callback])
- Event:
- Class:
http.Server- Event:
'checkContinue' - Event:
'checkExpectation' - Event:
'clientError' - Event:
'close' - Event:
'connect' - Event:
'connection' - Event:
'dropRequest' - Event:
'request' - Event:
'upgrade' server.close([callback])server.closeAllConnections()server.closeIdleConnections()server.headersTimeoutserver.listen()server.listeningserver.maxHeadersCountserver.requestTimeoutserver.setTimeout([msecs][, callback])server.maxRequestsPerSocketserver.timeoutserver.keepAliveTimeoutserver.keepAliveTimeoutBufferserver[Symbol.asyncDispose]()
- Event:
- Class:
http.ServerResponse- Event:
'close' - Event:
'finish' response.addTrailers(headers)response.connectionresponse.cork()response.end([data[, encoding]][, callback])response.finishedresponse.flushHeaders()response.getHeader(name)response.getHeaderNames()response.getHeaders()response.hasHeader(name)response.headersSentresponse.removeHeader(name)response.reqresponse.sendDateresponse.setHeader(name, value)response.setTimeout(msecs[, callback])response.socketresponse.statusCoderesponse.statusMessageresponse.strictContentLengthresponse.uncork()response.writableEndedresponse.writableFinishedresponse.write(chunk[, encoding][, callback])response.writeContinue()response.writeEarlyHints(hints[, callback])response.writeHead(statusCode[, statusMessage][, headers])response.writeProcessing()
- Event:
- Class:
http.IncomingMessage- Event:
'aborted' - Event:
'close' message.abortedmessage.completemessage.connectionmessage.destroy([error])message.headersmessage.headersDistinctmessage.httpVersionmessage.methodmessage.rawHeadersmessage.rawTrailersmessage.setTimeout(msecs[, callback])message.socketmessage.statusCodemessage.statusMessagemessage.trailersmessage.trailersDistinctmessage.url
- Event:
- Class:
http.OutgoingMessage- Event:
'drain' - Event:
'finish' - Event:
'prefinish' outgoingMessage.addTrailers(headers)outgoingMessage.appendHeader(name, value)outgoingMessage.connectionoutgoingMessage.cork()outgoingMessage.destroy([error])outgoingMessage.end(chunk[, encoding][, callback])outgoingMessage.flushHeaders()outgoingMessage.getHeader(name)outgoingMessage.getHeaderNames()outgoingMessage.getHeaders()outgoingMessage.hasHeader(name)outgoingMessage.headersSentoutgoingMessage.pipe()outgoingMessage.removeHeader(name)outgoingMessage.setHeader(name, value)outgoingMessage.setHeaders(headers)outgoingMessage.setTimeout(msecs[, callback])outgoingMessage.socketoutgoingMessage.uncork()outgoingMessage.writableCorkedoutgoingMessage.writableEndedoutgoingMessage.writableFinishedoutgoingMessage.writableHighWaterMarkoutgoingMessage.writableLengthoutgoingMessage.writableObjectModeoutgoingMessage.write(chunk[, encoding][, callback])
- Event:
http.METHODShttp.STATUS_CODEShttp.createServer([options][, requestListener])http.get(options[, callback])http.get(url[, options][, callback])http.globalAgenthttp.maxHeaderSizehttp.request(options[, callback])http.request(url[, options][, callback])http.validateHeaderName(name[, label])http.validateHeaderValue(name, value)http.setMaxIdleHTTPParsers(max)http.setGlobalProxyFromEnv([proxyEnv])- Class:
WebSocket - Built-in Proxy Support
- Class:
- HTTP
- Index
- About this documentation
- Usage and example
- Assertion testing
- Asynchronous context tracking
- Async hooks
- Buffer
- C++ addons
- C/C++ addons with Node-API
- C++ embedder API
- Child processes
- Cluster
- Command-line options
- Console
- Crypto
- Debugger
- Deprecated APIs
- Diagnostics Channel
- DNS
- Domain
- Environment Variables
- Errors
- Events
- File system
- Globals
- HTTP
- HTTP/2
- HTTPS
- Inspector
- Internationalization
- Modules: CommonJS modules
- Modules: ECMAScript modules
- Modules:
node:moduleAPI - Modules: Packages
- Modules: TypeScript
- Net
- Iterable Streams API
- OS
- Path
- Performance hooks
- Permissions
- Process
- Punycode
- Query strings
- Readline
- REPL
- Report
- Single executable applications
- SQLite
- Stream
- String decoder
- Test runner
- Timers
- TLS/SSL
- Trace events
- TTY
- UDP/datagram
- URL
- Utilities
- V8
- VM
- WASI
- Web Crypto API
- Web Streams API
- Worker threads
- Zlib
- Zlib Iterable Compression
- Other versions
- Options
HTTP#
Stability: 2 - Stable
This module, containing both a client and server, can be imported via
require('node:http') (CommonJS) or import * as http from 'node:http' (ES module).
The HTTP interfaces in Node.js are designed to support many features of the protocol which have been traditionally difficult to use. In particular, large, possibly chunk-encoded, messages. The interface is careful to never buffer entire requests or responses, so the user is able to stream data.
HTTP message headers are represented by an object like this:
{ "content-length": "123",
"content-type": "text/plain",
"connection": "keep-alive",
"host": "example.com",
"accept": "*/*" }
Keys are lowercased. Values are not modified.
In order to support the full spectrum of possible HTTP applications, the Node.js HTTP API is very low-level. It deals with stream handling and message parsing only. It parses a message into headers and body but it does not parse the actual headers or the body.
See message.headers for details on how duplicate headers are handled.
The raw headers as they were received are retained in the rawHeaders
property, which is an array of [key, value, key2, value2, ...]. For
example, the previous message header object might have a rawHeaders
list like the following:
[ 'ConTent-Length', '123456',
'content-LENGTH', '123',
'content-type', 'text/plain',
'CONNECTION', 'keep-alive',
'Host', 'example.com',
'accepT', '*/*' ]
Class: http.Agent#
An Agent is responsible for managing connection persistence
and reuse for HTTP clients. It maintains a queue of pending requests
for a given host and port, reusing a single socket connection for each
until the queue is empty, at which time the socket is either destroyed
or put into a pool where it is kept to be used again for requests to the
same host and port. Whether it is destroyed or pooled depends on the
keepAlive option.
Pooled connections have TCP Keep-Alive enabled for them, but servers may
still close idle connections, in which case they will be removed from the
pool and a new connection will be made when a new HTTP request is made for
that host and port. Servers may also refuse to allow multiple requests
over the same connection, in which case the connection will have to be
remade for every request and cannot be pooled. The Agent will still make
the requests to that server, but each one will occur over a new connection.
When a connection is closed by the client or the server, it is removed
from the pool. Any unused sockets in the pool will be unrefed so as not
to keep the Node.js process running when there are no outstanding requests.
(see socket.unref()).
It is good practice, to destroy() an Agent instance when it is no
longer in use, because unused sockets consume OS resources.
Sockets are removed from an agent when the socket emits either
a 'close' event or an 'agentRemove' event. When intending to keep one
HTTP request open for a long time without keeping it in the agent, something
like the following may be done:
http.get(options, (res) => {
// Do stuff
}).on('socket', (socket) => {
socket.emit('agentRemove');
});
An agent may also be used for an individual request. By providing
{agent: false} as an option to the http.get() or http.request()
functions, a one-time use Agent with default options will be used
for the client connection.
agent:false:
http.get({
hostname: 'localhost',
port: 80,
path: '/',
agent: false, // Create a new agent just for this one request
}, (res) => {
// Do stuff with response
});
new Agent([options])#
options<Object>Set of configurable options to set on the agent. Can have the following fields:keepAlive<boolean>Keep sockets around even when there are no outstanding requests, so they can be used for future requests without having to reestablish a TCP connection. Not to be confused with thekeep-alivevalue of theConnectionheader. TheConnection: keep-aliveheader is always sent when using an agent except when theConnectionheader is explicitly specified or when thekeepAliveandmaxSocketsoptions are respectively set tofalseandInfinity, in which caseConnection: closewill be used. Default:false.keepAliveMsecs<number>When using thekeepAliveoption, specifies the initial delay for TCP Keep-Alive packets. Ignored when thekeepAliveoption isfalseorundefined. Default:1000.agentKeepAliveTimeoutBuffer<number>Milliseconds to subtract from the server-providedkeep-alive: timeout=...hint when determining socket expiration time. This buffer helps ensure the agent closes the socket slightly before the server does, reducing the chance of sending a request on a socket that’s about to be closed by the server. Default:1000.maxSockets<number>Maximum number of sockets to allow per host. If the same host opens multiple concurrent connections, each request will use new socket until themaxSocketsvalue is reached. If the host attempts to open more connections thanmaxSockets, the additional requests will enter into a pending request queue, and will enter active connection state when an existing connection terminates. This makes sure there are at mostmaxSocketsactive connections at any point in time, from a given host. Default:Infinity.maxTotalSockets<number>Maximum number of sockets allowed for all hosts in total. Each request will use a new socket until the maximum is reached. Default:Infinity.maxFreeSockets<number>Maximum number of sockets per host to leave open in a free state. Only relevant ifkeepAliveis set totrue. Default:256.scheduling<string>Scheduling strategy to apply when picking the next free socket to use. It can be'fifo'or'lifo'. The main difference between the two scheduling strategies is that'lifo'selects the most recently used socket, while'fifo'selects the least recently used socket. In case of a low rate of request per second, the'lifo'scheduling will lower the risk of picking a socket that might have been closed by the server due to inactivity. In case of a high rate of request per second, the'fifo'scheduling will maximize the number of open sockets, while the'lifo'scheduling will keep it as low as possible. Default:'lifo'.timeout<number>Socket timeout in milliseconds. This will set the timeout when the socket is created.proxyEnv<Object>|<undefined>Environment variables for proxy configuration. See Built-in Proxy Support for details. Default:undefinedHTTP_PROXY<string>|<undefined>URL for the proxy server that HTTP requests should use. If undefined, no proxy is used for HTTP requests.HTTPS_PROXY<string>|<undefined>URL for the proxy server that HTTPS requests should use. If undefined, no proxy is used for HTTPS requests.NO_PROXY<string>|<undefined>Patterns specifying the endpoints that should not be routed through a proxy.http_proxy<string>|<undefined>Same asHTTP_PROXY. If both are set,http_proxytakes precedence.https_proxy<string>|<undefined>Same asHTTPS_PROXY. If both are set,https_proxytakes precedence.no_proxy<string>|<undefined>Same asNO_PROXY. If both are set,no_proxytakes precedence.
defaultPort<number>Default port to use when the port is not specified in requests. Default:80.protocol<string>The protocol to use for the agent. Default:'http:'.
options in socket.connect() are also supported.
To configure any of them, a custom http.Agent instance must be created.
import { Agent, request } from 'node:http'; const keepAliveAgent = new Agent({ keepAlive: true }); options.agent = keepAliveAgent; request(options, onResponseCallback);const http = require('node:http'); const keepAliveAgent = new http.Agent({ keepAlive: true }); options.agent = keepAliveAgent; http.request(options, onResponseCallback);
agent.createConnection(options[, callback])#
options<Object>Options containing connection details. Checknet.createConnection()for the format of the options. For custom agents, this object is passed to the customcreateConnectionfunction.callback<Function>(Optional, primarily for custom agents) A function to be called by a customcreateConnectionimplementation when the socket is created, especially for asynchronous operations.err<Error>|<null>An error object if socket creation failed.socket<stream.Duplex>The created socket.
- Returns:
<stream.Duplex>The created socket. This is returned by the default implementation or by a custom synchronouscreateConnectionimplementation. If a customcreateConnectionuses thecallbackfor asynchronous operation, this return value might not be the primary way to obtain the socket.
Produces a socket/stream to be used for HTTP requests.
By default, this function behaves identically to net.createConnection(),
synchronously returning the created socket. The optional callback parameter in the
signature is not used by this default implementation.
However, custom agents may override this method to provide greater flexibility,
for example, to create sockets asynchronously. When overriding createConnection:
- Synchronous socket creation: The overriding method can return the socket/stream directly.
- Asynchronous socket creation: The overriding method can accept the
callbackand pass the created socket/stream to it (e.g.,callback(null, newSocket)). If an error occurs during socket creation, it should be passed as the first argument to thecallback(e.g.,callback(err)).
The agent will call the provided createConnection function with options and
this internal callback. The callback provided by the agent has a signature
of (err, stream).
agent.keepSocketAlive(socket)#
socket<stream.Duplex>
Called when socket is detached from a request and could be persisted by the
Agent. Default behavior is to:
socket.setKeepAlive(true, this.keepAliveMsecs);
socket.unref();
return true;
This method can be overridden by a particular Agent subclass. If this
method returns a falsy value, the socket will be destroyed instead of persisting
it for use with the next request.
The socket argument can be an instance of <net.Socket>, a subclass of
<stream.Duplex>.
agent.reuseSocket(socket, request)#
socket<stream.Duplex>request<http.ClientRequest>
Called when socket is attached to request after being persisted because of
the keep-alive options. Default behavior is to:
socket.ref();
This method can be overridden by a particular Agent subclass.
The socket argument can be an instance of <net.Socket>, a subclass of
<stream.Duplex>.
agent.destroy()#
Destroy any sockets that are currently in use by the agent.
It is usually not necessary to do this. However, if using an
agent with keepAlive enabled, then it is best to explicitly shut down
the agent when it is no longer needed. Otherwise,
sockets might stay open for quite a long time before the server
terminates them.
agent.freeSockets#
- Type:
<Object>
An object which contains arrays of sockets currently awaiting use by
the agent when keepAlive is enabled. Do not modify.
Sockets in the freeSockets list will be automatically destroyed and
removed from the array on 'timeout'.
agent.getName([options])#
Get a unique name for a set of request options, to determine whether a
connection can be reused. For an HTTP agent, this returns
host:port:localAddress or host:port:localAddress:family. For an HTTPS agent,
the name includes the CA, cert, ciphers, and other HTTPS/TLS-specific options
that determine socket reusability.
agent.maxFreeSockets#
- Type:
<number>
By default set to 256. For agents with keepAlive enabled, this
sets the maximum number of sockets that will be left open in the free
state.
agent.maxSockets#
- Type:
<number>
By default set to Infinity. Determines how many concurrent sockets the agent
can have open per origin. Origin is the returned value of agent.getName().
agent.maxTotalSockets#
- Type:
<number>
By default set to Infinity. Determines how many concurrent sockets the agent
can have open. Unlike maxSockets, this parameter applies across all origins.
agent.requests#
- Type:
<Object>
An object which contains queues of requests that have not yet been assigned to sockets. Do not modify.
agent.sockets#
- Type:
<Object>
An object which contains arrays of sockets currently in use by the agent. Do not modify.
Class: http.ClientRequest#
- Extends:
<http.OutgoingMessage>
This object is created internally and returned from http.request(). It
represents an in-progress request whose header has already been queued. The
header is still mutable using the setHeader(name, value),
getHeader(name), removeHeader(name) API. The actual header will
be sent along with the first data chunk or when calling request.end().
To get the response, add a listener for 'response' to the request object.
'response' will be emitted from the request object when the response
headers have been received. The 'response' event is executed with one
argument which is an instance of http.IncomingMessage.
During the 'response' event, one can add listeners to the
response object; particularly to listen for the 'data' event.
If no 'response' handler is added, then the response will be
entirely discarded. However, if a 'response' event handler is added,
then the data from the response object must be consumed, either by
calling response.read() whenever there is a 'readable' event, or
by adding a 'data' handler, or by calling the .resume() method.
Until the data is consumed, the 'end' event will not fire. Also, until
the data is read it will consume memory that can eventually lead to a
'process out of memory' error.
For backward compatibility, res will only emit 'error' if there is an
'error' listener registered.
Set Content-Length header to limit the response body size.
If response.strictContentLength is set to true, mismatching the
Content-Length header value will result in an Error being thrown,
identified by code: 'ERR_HTTP_CONTENT_LENGTH_MISMATCH'.
Content-Length value should be in bytes, not characters. Use
Buffer.byteLength() to determine the length of the body in bytes.
Event: 'abort'#
Stability: 0 - Deprecated. Listen for the 'close' event instead.
Emitted when the request has been aborted by the client. This event is only
emitted on the first call to abort().
Event: 'close'#
Indicates that the request is completed, or its underlying connection was terminated prematurely (before the response completion).
Event: 'connect'#
response<http.IncomingMessage>socket<stream.Duplex>head<Buffer>
Emitted each time a server responds to a request with a CONNECT method. If
this event is not being listened for, clients receiving a CONNECT method will
have their connections closed.
This event is guaranteed to be passed an instance of the <net.Socket> class,
a subclass of <stream.Duplex>, unless the user specifies a socket
type other than <net.Socket>.
A client and server pair demonstrating how to listen for the 'connect' event:
import { createServer, request } from 'node:http'; import { connect } from 'node:net'; import { URL } from 'node:url'; // Create an HTTP tunneling proxy const proxy = createServer((req, res) => { res.writeHead(200, { 'Content-Type': 'text/plain' }); res.end('okay'); }); proxy.on('connect', (req, clientSocket, head) => { // Connect to an origin server const { port, hostname } = new URL(`http://${req.url}`); const serverSocket = connect(port || 80, hostname, () => { clientSocket.write('HTTP/1.1 200 Connection Established\r\n' + 'Proxy-agent: Node.js-Proxy\r\n' + '\r\n'); serverSocket.write(head); serverSocket.pipe(clientSocket); clientSocket.pipe(serverSocket); }); }); // Now that proxy is running proxy.listen(1337, '127.0.0.1', () => { // Make a request to a tunneling proxy const options = { port: 1337, host: '127.0.0.1', method: 'CONNECT', path: 'www.google.com:80', }; const req = request(options); req.end(); req.on('connect', (res, socket, head) => { console.log('got connected!'); // Make a request over an HTTP tunnel socket.write('GET / HTTP/1.1\r\n' + 'Host: www.google.com:80\r\n' + 'Connection: close\r\n' + '\r\n'); socket.on('data', (chunk) => { console.log(chunk.toString()); }); socket.on('end', () => { proxy.close(); }); }); });const http = require('node:http'); const net = require('node:net'); const { URL } = require('node:url'); // Create an HTTP tunneling proxy const proxy = http.createServer((req, res) => { res.writeHead(200, { 'Content-Type': 'text/plain' }); res.end('okay'); }); proxy.on('connect', (req, clientSocket, head) => { // Connect to an origin server const { port, hostname } = new URL(`http://${req.url}`); const serverSocket = net.connect(port || 80, hostname, () => { clientSocket.write('HTTP/1.1 200 Connection Established\r\n' + 'Proxy-agent: Node.js-Proxy\r\n' + '\r\n'); serverSocket.write(head); serverSocket.pipe(clientSocket); clientSocket.pipe(serverSocket); }); }); // Now that proxy is running proxy.listen(1337, '127.0.0.1', () => { // Make a request to a tunneling proxy const options = { port: 1337, host: '127.0.0.1', method: 'CONNECT', path: 'www.google.com:80', }; const req = http.request(options); req.end(); req.on('connect', (res, socket, head) => { console.log('got connected!'); // Make a request over an HTTP tunnel socket.write('GET / HTTP/1.1\r\n' + 'Host: www.google.com:80\r\n' + 'Connection: close\r\n' + '\r\n'); socket.on('data', (chunk) => { console.log(chunk.toString()); }