{ "type": "module", "source": "doc/api/http.md", "modules": [ { "textRaw": "HTTP", "name": "http", "introduced_in": "v0.10.0", "type": "module", "stability": 2, "stabilityText": "Stable", "desc": "
This module, containing both a client and server, can be imported via\nrequire('node:http') (CommonJS) or import * as http from 'node:http' (ES module).
The HTTP interfaces in Node.js are designed to support many features\nof the protocol which have been traditionally difficult to use.\nIn particular, large, possibly chunk-encoded, messages. The interface is\ncareful to never buffer entire requests or responses, so the\nuser is able to stream data.
\nHTTP message headers are represented by an object like this:
\n{ \"content-length\": \"123\",\n \"content-type\": \"text/plain\",\n \"connection\": \"keep-alive\",\n \"host\": \"example.com\",\n \"accept\": \"*/*\" }\n\nKeys are lowercased. Values are not modified.
\nIn order to support the full spectrum of possible HTTP applications, the Node.js\nHTTP API is very low-level. It deals with stream handling and message\nparsing only. It parses a message into headers and body but it does not\nparse the actual headers or the body.
\nSee message.headers for details on how duplicate headers are handled.
The raw headers as they were received are retained in the rawHeaders\nproperty, which is an array of [key, value, key2, value2, ...]. For\nexample, the previous message header object might have a rawHeaders\nlist like the following:
[ \"ConTent-Length\", \"123456\",\n \"content-LENGTH\", \"123\",\n \"content-type\", \"text/plain\",\n \"CONNECTION\", \"keep-alive\",\n \"Host\", \"example.com\",\n \"accepT\", \"*/*\" ]\n",
"classes": [
{
"textRaw": "Class: `http.Agent`",
"name": "http.Agent",
"type": "class",
"meta": {
"added": [
"v0.3.4"
],
"changes": []
},
"desc": "An Agent is responsible for managing connection persistence\nand reuse for HTTP clients. It maintains a queue of pending requests\nfor a given host and port, reusing a single socket connection for each\nuntil the queue is empty, at which time the socket is either destroyed\nor put into a pool where it is kept to be used again for requests to the\nsame host and port. Whether it is destroyed or pooled depends on the\nkeepAlive option.
Pooled connections have TCP Keep-Alive enabled for them, but servers may\nstill close idle connections, in which case they will be removed from the\npool and a new connection will be made when a new HTTP request is made for\nthat host and port. Servers may also refuse to allow multiple requests\nover the same connection, in which case the connection will have to be\nremade for every request and cannot be pooled. The Agent will still make\nthe requests to that server, but each one will occur over a new connection.
On a reused HTTP/1.1 keep-alive connection, responses are associated with\nrequests by their order on that connection. HTTP/1.1 keep-alive does not provide\nper-request response attribution beyond that ordering. Applications that require\nper-request connection isolation can use a separate Agent, disable keep-alive,\nor pass agent: false.
When a connection is closed by the client or the server, it is removed\nfrom the pool. Any unused sockets in the pool will be unrefed so as not\nto keep the Node.js process running when there are no outstanding requests.\n(see socket.unref()).
It is good practice, to destroy() an Agent instance when it is no\nlonger in use, because unused sockets consume OS resources.
Sockets are removed from an agent when the socket emits either\na 'close' event or an 'agentRemove' event. When intending to keep one\nHTTP request open for a long time without keeping it in the agent, something\nlike the following may be done:
http.get(options, (res) => {\n // Do stuff\n}).on('socket', (socket) => {\n socket.emit('agentRemove');\n});\n\nAn agent may also be used for an individual request. By providing\n{agent: false} as an option to the http.get() or http.request()\nfunctions, a one-time use Agent with default options will be used\nfor the client connection.
agent:false:
http.get({\n hostname: 'localhost',\n port: 80,\n path: '/',\n agent: false, // Create a new agent just for this one request\n}, (res) => {\n // Do stuff with response\n});\n\nUse agent: false to avoid connection reuse for a request.
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';\nconst keepAliveAgent = new Agent({ keepAlive: true });\noptions.agent = keepAliveAgent;\nrequest(options, onResponseCallback);\n\nconst http = require('node:http');\nconst keepAliveAgent = new http.Agent({ keepAlive: true });\noptions.agent = keepAliveAgent;\nhttp.request(options, onResponseCallback);\n"
}
],
"methods": [
{
"textRaw": "`agent.createConnection(options[, callback])`",
"name": "createConnection",
"type": "method",
"meta": {
"added": [
"v0.11.4"
],
"changes": []
},
"signatures": [
{
"params": [
{
"textRaw": "`options` {Object} Options containing connection details. Check `net.createConnection()` for the format of the options. For custom agents, this object is passed to the custom `createConnection` function.",
"name": "options",
"type": "Object",
"desc": "Options containing connection details. Check `net.createConnection()` for the format of the options. For custom agents, this object is passed to the custom `createConnection` function."
},
{
"textRaw": "`callback` {Function} (Optional, primarily for custom agents) A function to be called by a custom `createConnection` implementation when the socket is created, especially for asynchronous operations.",
"name": "callback",
"type": "Function",
"desc": "(Optional, primarily for custom agents) A function to be called by a custom `createConnection` implementation when the socket is created, especially for asynchronous operations.",
"options": [
{
"textRaw": "`err` {Error | null} An error object if socket creation failed.",
"name": "err",
"type": "Error | null",
"desc": "An error object if socket creation failed."
},
{
"textRaw": "`socket` {stream.Duplex} The created socket.",
"name": "socket",
"type": "stream.Duplex",
"desc": "The created socket."
}
],
"optional": true
}
],
"return": {
"textRaw": "Returns: {stream.Duplex} The created socket. This is returned by the default implementation or by a custom synchronous `createConnection` implementation. If a custom `createConnection` uses the `callback` for asynchronous operation, this return value might not be the primary way to obtain the socket.",
"name": "return",
"type": "stream.Duplex",
"desc": "The created socket. This is returned by the default implementation or by a custom synchronous `createConnection` implementation. If a custom `createConnection` uses the `callback` for asynchronous operation, this return value might not be the primary way to obtain the socket."
}
}
],
"desc": "Produces a socket/stream to be used for HTTP requests.
\nBy default, this function behaves identically to net.createConnection(),\nsynchronously returning the created socket. The optional callback parameter in the\nsignature is not used by this default implementation.
However, custom agents may override this method to provide greater flexibility,\nfor example, to create sockets asynchronously. When overriding createConnection:
callback\nand pass the created socket/stream to it (e.g., callback(null, newSocket)).\nIf an error occurs during socket creation, it should be passed as the first\nargument to the callback (e.g., callback(err)).The agent will call the provided createConnection function with options and\nthis internal callback. The callback provided by the agent has a signature\nof (err, stream).
Called when socket is detached from a request and could be persisted by the\nAgent. Default behavior is to:
socket.setKeepAlive(true, this.keepAliveMsecs);\nsocket.unref();\nreturn true;\n\nThis method can be overridden by a particular Agent subclass. If this\nmethod returns a falsy value, the socket will be destroyed instead of persisting\nit for use with the next request.
The socket argument can be an instance of net.Socket, a subclass of\nstream.Duplex.
Called when socket is attached to request after being persisted because of\nthe keep-alive options. Default behavior is to:
socket.ref();\n\nThis method can be overridden by a particular Agent subclass.
The socket argument can be an instance of net.Socket, a subclass of\nstream.Duplex.
Destroy any sockets that are currently in use by the agent.
\nIt is usually not necessary to do this. However, if using an\nagent with keepAlive enabled, then it is best to explicitly shut down\nthe agent when it is no longer needed. Otherwise,\nsockets might stay open for quite a long time before the server\nterminates them.
Get a unique name for a set of request options, to determine whether a\nconnection can be reused. For an HTTP agent, this returns\nhost:port:localAddress or host:port:localAddress:family. For an HTTPS agent,\nthe name includes the CA, cert, ciphers, and other HTTPS/TLS-specific options\nthat determine socket reusability.
An object which contains arrays of sockets currently awaiting use by\nthe agent when keepAlive is enabled. Do not modify.
Sockets in the freeSockets list will be automatically destroyed and\nremoved from the array on 'timeout'.
By default set to 256. For agents with keepAlive enabled, this\nsets the maximum number of sockets that will be left open in the free\nstate.
By default set to Infinity. Determines how many concurrent sockets the agent\ncan have open per origin. Origin is the returned value of agent.getName().
By default set to Infinity. Determines how many concurrent sockets the agent\ncan have open. Unlike maxSockets, this parameter applies across all origins.
An object which contains queues of requests that have not yet been assigned to\nsockets. Do not modify.
" }, { "textRaw": "Type: {Object}", "name": "sockets", "type": "Object", "meta": { "added": [ "v0.3.6" ], "changes": [ { "version": "v16.0.0", "pr-url": "https://github.com/nodejs/node/pull/36409", "description": "The property now has a `null` prototype." } ] }, "desc": "An object which contains arrays of sockets currently in use by the\nagent. Do not modify.
" } ] }, { "textRaw": "Class: `http.ClientRequest`", "name": "http.ClientRequest", "type": "class", "meta": { "added": [ "v0.1.17" ], "changes": [] }, "desc": "http.OutgoingMessageThis object is created internally and returned from http.request(). It\nrepresents an in-progress request whose header has already been queued. The\nheader is still mutable using the setHeader(name, value),\ngetHeader(name), removeHeader(name) API. The actual header will\nbe 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.\n'response' will be emitted from the request object when the response\nheaders have been received. The 'response' event is executed with one\nargument which is an instance of http.IncomingMessage.
During the 'response' event, one can add listeners to the\nresponse object; particularly to listen for the 'data' event.
If no 'response' handler is added, then the response will be\nentirely discarded. However, if a 'response' event handler is added,\nthen the data from the response object must be consumed, either by\ncalling response.read() whenever there is a 'readable' event, or\nby adding a 'data' handler, or by calling the .resume() method.\nUntil the data is consumed, the 'end' event will not fire. Also, until\nthe data is read it will consume memory that can eventually lead to a\n'process out of memory' error.
For backward compatibility, res will only emit 'error' if there is an\n'error' listener registered.
Set Content-Length header to limit the response body size.\nIf response.strictContentLength is set to true, mismatching the\nContent-Length header value will result in an Error being thrown,\nidentified by code: 'ERR_HTTP_CONTENT_LENGTH_MISMATCH'.
Content-Length value should be in bytes, not characters. Use\nBuffer.byteLength() to determine the length of the body in bytes.
Emitted when the request has been aborted by the client. This event is only\nemitted on the first call to abort().
Indicates that the request is completed, or its underlying connection was\nterminated prematurely (before the response completion).
" }, { "textRaw": "Event: `'connect'`", "name": "connect", "type": "event", "meta": { "added": [ "v0.7.0" ], "changes": [] }, "params": [ { "textRaw": "`response` {http.IncomingMessage}", "name": "response", "type": "http.IncomingMessage" }, { "textRaw": "`socket` {stream.Duplex}", "name": "socket", "type": "stream.Duplex" }, { "textRaw": "`head` {Buffer}", "name": "head", "type": "Buffer" } ], "desc": "Emitted each time a server responds to a request with a CONNECT method. If\nthis event is not being listened for, clients receiving a CONNECT method will\nhave their connections closed.
This event is guaranteed to be passed an instance of the net.Socket class,\na subclass of stream.Duplex, unless the user specifies a socket\ntype other than net.Socket.
A client and server pair demonstrating how to listen for the 'connect' event:
import { createServer, request } from 'node:http';\nimport { connect } from 'node:net';\nimport { URL } from 'node:url';\n\n// Create an HTTP tunneling proxy\nconst proxy = createServer((req, res) => {\n res.writeHead(200, { 'Content-Type': 'text/plain' });\n res.end('okay');\n});\nproxy.on('connect', (req, clientSocket, head) => {\n // Connect to an origin server\n const { port, hostname } = new URL(`http://${req.url}`);\n const serverSocket = connect(port || 80, hostname, () => {\n clientSocket.write('HTTP/1.1 200 Connection Established\\r\\n' +\n 'Proxy-agent: Node.js-Proxy\\r\\n' +\n '\\r\\n');\n serverSocket.write(head);\n serverSocket.pipe(clientSocket);\n clientSocket.pipe(serverSocket);\n });\n});\n\n// Now that proxy is running\nproxy.listen(1337, '127.0.0.1', () => {\n\n // Make a request to a tunneling proxy\n const options = {\n port: 1337,\n host: '127.0.0.1',\n method: 'CONNECT',\n path: 'www.google.com:80',\n };\n\n const req = request(options);\n req.end();\n\n req.on('connect', (res, socket, head) => {\n console.log('got connected!');\n\n // Make a request over an HTTP tunnel\n socket.write('GET / HTTP/1.1\\r\\n' +\n 'Host: www.google.com:80\\r\\n' +\n 'Connection: close\\r\\n' +\n '\\r\\n');\n socket.on('data', (chunk) => {\n console.log(chunk.toString());\n });\n socket.on('end', () => {\n proxy.close();\n });\n });\n});\n\nconst http = require('node:http');\nconst net = require('node:net');\nconst { URL } = require('node:url');\n\n// Create an HTTP tunneling proxy\nconst proxy = http.createServer((req, res) => {\n res.writeHead(200, { 'Content-Type': 'text/plain' });\n res.end('okay');\n});\nproxy.on('connect', (req, clientSocket, head) => {\n // Connect to an origin server\n const { port, hostname } = new URL(`http://${req.url}`);\n const serverSocket = net.connect(port || 80, hostname, () => {\n clientSocket.write('HTTP/1.1 200 Connection Established\\r\\n' +\n 'Proxy-agent: Node.js-Proxy\\r\\n' +\n '\\r\\n');\n serverSocket.write(head);\n serverSocket.pipe(clientSocket);\n clientSocket.pipe(serverSocket);\n });\n});\n\n// Now that proxy is running\nproxy.listen(1337, '127.0.0.1', () => {\n\n // Make a request to a tunneling proxy\n const options = {\n port: 1337,\n host: '127.0.0.1',\n method: 'CONNECT',\n path: 'www.google.com:80',\n };\n\n const req = http.request(options);\n req.end();\n\n req.on('connect', (res, socket, head) => {\n console.log('got connected!');\n\n // Make a request over an HTTP tunnel\n socket.write('GET / HTTP/1.1\\r\\n' +\n 'Host: www.google.com:80\\r\\n' +\n 'Connection: close\\r\\n' +\n '\\r\\n');\n socket.on('data', (chunk) => {\n console.log(chunk.toString());\n });\n socket.on('end', () => {\n proxy.close();\n });\n });\n});\n"
},
{
"textRaw": "Event: `'continue'`",
"name": "continue",
"type": "event",
"meta": {
"added": [
"v0.3.2"
],
"changes": []
},
"params": [],
"desc": "Emitted when the server sends a '100 Continue' HTTP response, usually because\nthe request contained 'Expect: 100-continue'. This is an instruction that\nthe client should send the request body.
" }, { "textRaw": "Event: `'finish'`", "name": "finish", "type": "event", "meta": { "added": [ "v0.3.6" ], "changes": [] }, "params": [], "desc": "Emitted when the request has been sent. More specifically, this event is emitted\nwhen the last segment of the request headers and body have been handed off to\nthe operating system for transmission over the network. It does not imply that\nthe server has received anything yet.
" }, { "textRaw": "Event: `'information'`", "name": "information", "type": "event", "meta": { "added": [ "v10.0.0" ], "changes": [] }, "params": [ { "textRaw": "`info` {Object}", "name": "info", "type": "Object", "options": [ { "textRaw": "`httpVersion` {string}", "name": "httpVersion", "type": "string" }, { "textRaw": "`httpVersionMajor` {integer}", "name": "httpVersionMajor", "type": "integer" }, { "textRaw": "`httpVersionMinor` {integer}", "name": "httpVersionMinor", "type": "integer" }, { "textRaw": "`statusCode` {integer}", "name": "statusCode", "type": "integer" }, { "textRaw": "`statusMessage` {string}", "name": "statusMessage", "type": "string" }, { "textRaw": "`headers` {Object}", "name": "headers", "type": "Object" }, { "textRaw": "`rawHeaders` {string[]}", "name": "rawHeaders", "type": "string[]" } ] } ], "desc": "Emitted when the server sends a 1xx intermediate response (excluding 101\nUpgrade). The listeners of this event will receive an object containing the\nHTTP version, status code, status message, key-value headers object,\nand array with the raw header names followed by their respective values.
\nimport { request } from 'node:http';\n\nconst options = {\n host: '127.0.0.1',\n port: 8080,\n path: '/length_request',\n};\n\n// Make a request\nconst req = request(options);\nreq.end();\n\nreq.on('information', (info) => {\n console.log(`Got information prior to main response: ${info.statusCode}`);\n});\n\nconst http = require('node:http');\n\nconst options = {\n host: '127.0.0.1',\n port: 8080,\n path: '/length_request',\n};\n\n// Make a request\nconst req = http.request(options);\nreq.end();\n\nreq.on('information', (info) => {\n console.log(`Got information prior to main response: ${info.statusCode}`);\n});\n\n101 Upgrade statuses do not fire this event due to their break from the\ntraditional HTTP request/response chain, such as web sockets, in-place TLS\nupgrades, or HTTP 2.0. To be notified of 101 Upgrade notices, listen for the\n'upgrade' event instead.
Emitted when a response is received to this request. This event is emitted only\nonce.
" }, { "textRaw": "Event: `'socket'`", "name": "socket", "type": "event", "meta": { "added": [ "v0.5.3" ], "changes": [] }, "params": [ { "textRaw": "`socket` {stream.Duplex}", "name": "socket", "type": "stream.Duplex" } ], "desc": "This event is guaranteed to be passed an instance of the net.Socket class,\na subclass of stream.Duplex, unless the user specifies a socket\ntype other than net.Socket.
Emitted when the underlying socket times out from inactivity. This only notifies\nthat the socket has been idle. The request must be destroyed manually.
\nSee also: request.setTimeout().
Emitted each time a server responds to a request with an upgrade. If this\nevent is not being listened for and the response status code is 101 Switching\nProtocols, clients receiving an upgrade header will have their connections\nclosed.
\nThis event is guaranteed to be passed an instance of the net.Socket class,\na subclass of stream.Duplex, unless the user specifies a socket\ntype other than net.Socket.
A client server pair demonstrating how to listen for the 'upgrade' event.
import http from 'node:http';\nimport process from 'node:process';\n\n// Create an HTTP server\nconst server = http.createServer((req, res) => {\n res.writeHead(200, { 'Content-Type': 'text/plain' });\n res.end('okay');\n});\nserver.on('upgrade', (req, stream, head) => {\n stream.write('HTTP/1.1 101 Web Socket Protocol Handshake\\r\\n' +\n 'Upgrade: WebSocket\\r\\n' +\n 'Connection: Upgrade\\r\\n' +\n '\\r\\n');\n\n stream.pipe(stream); // echo back\n});\n\n// Now that server is running\nserver.listen(1337, '127.0.0.1', () => {\n\n // make a request\n const options = {\n port: 1337,\n host: '127.0.0.1',\n headers: {\n 'Connection': 'Upgrade',\n 'Upgrade': 'websocket',\n },\n };\n\n const req = http.request(options);\n req.end();\n\n req.on('upgrade', (res, stream, upgradeHead) => {\n console.log('got upgraded!');\n stream.end();\n process.exit(0);\n });\n});\n\nconst http = require('node:http');\n\n// Create an HTTP server\nconst server = http.createServer((req, res) => {\n res.writeHead(200, { 'Content-Type': 'text/plain' });\n res.end('okay');\n});\nserver.on('upgrade', (req, stream, head) => {\n stream.write('HTTP/1.1 101 Web Socket Protocol Handshake\\r\\n' +\n 'Upgrade: WebSocket\\r\\n' +\n 'Connection: Upgrade\\r\\n' +\n '\\r\\n');\n\n stream.pipe(stream); // echo back\n});\n\n// Now that server is running\nserver.listen(1337, '127.0.0.1', () => {\n\n // make a request\n const options = {\n port: 1337,\n host: '127.0.0.1',\n headers: {\n 'Connection': 'Upgrade',\n 'Upgrade': 'websocket',\n },\n };\n\n const req = http.request(options);\n req.end();\n\n req.on('upgrade', (res, stream, upgradeHead) => {\n console.log('got upgraded!');\n stream.end();\n process.exit(0);\n });\n});\n"
}
],
"methods": [
{
"textRaw": "`request.abort()`",
"name": "abort",
"type": "method",
"meta": {
"added": [
"v0.3.8"
],
"changes": [],
"deprecated": [
"v14.1.0",
"v13.14.0"
]
},
"stability": 0,
"stabilityText": "Deprecated: Use `request.destroy()` instead.",
"signatures": [
{
"params": []
}
],
"desc": "Marks the request as aborting. Calling this will cause remaining data\nin the response to be dropped and the socket to be destroyed.
" }, { "textRaw": "`request.cork()`", "name": "cork", "type": "method", "meta": { "added": [ "v13.2.0", "v12.16.0" ], "changes": [] }, "signatures": [ { "params": [] } ], "desc": "See writable.cork().
Finishes sending the request. If any parts of the body are\nunsent, it will flush them to the stream. If the request is\nchunked, this will send the terminating '0\\r\\n\\r\\n'.
If data is specified, it is equivalent to calling\nrequest.write(data, encoding) followed by request.end(callback).
If callback is specified, it will be called when the request stream\nis finished.
Destroy the request. Optionally emit an 'error' event,\nand emit a 'close' event. Calling this will cause remaining data\nin the response to be dropped, and the socket to be destroyed if used,\nor returned to the corresponding Agent pool otherwise if possible.
See writable.destroy() for further details.
Is true after request.destroy() has been called.
See writable.destroyed for further details.
Flushes the request headers.
\nFor efficiency reasons, Node.js normally buffers the request headers until\nrequest.end() is called or the first chunk of request data is written. It\nthen tries to pack the request headers and data into a single TCP packet.
That's usually desired (it saves a TCP round-trip), but not when the first\ndata is not sent until possibly much later. request.flushHeaders() bypasses\nthe optimization and kickstarts the request.
Reads out a header on the request. The name is case-insensitive.\nThe type of the return value depends on the arguments provided to\nrequest.setHeader().
request.setHeader('content-type', 'text/html');\nrequest.setHeader('Content-Length', Buffer.byteLength(body));\nrequest.setHeader('Cookie', ['type=ninja', 'language=javascript']);\nconst contentType = request.getHeader('Content-Type');\n// 'contentType' is 'text/html'\nconst contentLength = request.getHeader('Content-Length');\n// 'contentLength' is of type number\nconst cookie = request.getHeader('Cookie');\n// 'cookie' is of type string[]\n"
},
{
"textRaw": "`request.getHeaderNames()`",
"name": "getHeaderNames",
"type": "method",
"meta": {
"added": [
"v7.7.0"
],
"changes": []
},
"signatures": [
{
"params": [],
"return": {
"textRaw": "Returns: {string[]}",
"name": "return",
"type": "string[]"
}
}
],
"desc": "Returns an array containing the unique names of the current outgoing headers.\nAll header names are lowercase.
\nrequest.setHeader('Foo', 'bar');\nrequest.setHeader('Cookie', ['foo=bar', 'bar=baz']);\n\nconst headerNames = request.getHeaderNames();\n// headerNames === ['foo', 'cookie']\n"
},
{
"textRaw": "`request.getHeaders()`",
"name": "getHeaders",
"type": "method",
"meta": {
"added": [
"v7.7.0"
],
"changes": []
},
"signatures": [
{
"params": [],
"return": {
"textRaw": "Returns: {Object}",
"name": "return",
"type": "Object"
}
}
],
"desc": "Returns a shallow copy of the current outgoing headers. Since a shallow copy\nis used, array values may be mutated without additional calls to various\nheader-related http module methods. The keys of the returned object are the\nheader names and the values are the respective header values. All header names\nare lowercase.
\nThe object returned by the request.getHeaders() method does not\nprototypically inherit from the JavaScript Object. This means that typical\nObject methods such as obj.toString(), obj.hasOwnProperty(), and others\nare not defined and will not work.
request.setHeader('Foo', 'bar');\nrequest.setHeader('Cookie', ['foo=bar', 'bar=baz']);\n\nconst headers = request.getHeaders();\n// headers === { foo: 'bar', 'cookie': ['foo=bar', 'bar=baz'] }\n"
},
{
"textRaw": "`request.getRawHeaderNames()`",
"name": "getRawHeaderNames",
"type": "method",
"meta": {
"added": [
"v15.13.0",
"v14.17.0"
],
"changes": []
},
"signatures": [
{
"params": [],
"return": {
"textRaw": "Returns: {string[]}",
"name": "return",
"type": "string[]"
}
}
],
"desc": "Returns an array containing the unique names of the current outgoing raw\nheaders. Header names are returned with their exact casing being set.
\nrequest.setHeader('Foo', 'bar');\nrequest.setHeader('Set-Cookie', ['foo=bar', 'bar=baz']);\n\nconst headerNames = request.getRawHeaderNames();\n// headerNames === ['Foo', 'Set-Cookie']\n"
},
{
"textRaw": "`request.hasHeader(name)`",
"name": "hasHeader",
"type": "method",
"meta": {
"added": [
"v7.7.0"
],
"changes": []
},
"signatures": [
{
"params": [
{
"textRaw": "`name` {string}",
"name": "name",
"type": "string"
}
],
"return": {
"textRaw": "Returns: {boolean}",
"name": "return",
"type": "boolean"
}
}
],
"desc": "Returns true if the header identified by name is currently set in the\noutgoing headers. The header name matching is case-insensitive.
const hasContentType = request.hasHeader('content-type');\n"
},
{
"textRaw": "`request.removeHeader(name)`",
"name": "removeHeader",
"type": "method",
"meta": {
"added": [
"v1.6.0"
],
"changes": []
},
"signatures": [
{
"params": [
{
"textRaw": "`name` {string}",
"name": "name",
"type": "string"
}
]
}
],
"desc": "Removes a header that's already defined into headers object.
\nrequest.removeHeader('Content-Type');\n"
},
{
"textRaw": "`request.setHeader(name, value)`",
"name": "setHeader",
"type": "method",
"meta": {
"added": [
"v1.6.0"
],
"changes": []
},
"signatures": [
{
"params": [
{
"textRaw": "`name` {string}",
"name": "name",
"type": "string"
},
{
"textRaw": "`value` {any}",
"name": "value",
"type": "any"
}
]
}
],
"desc": "Sets a single header value for headers object. If this header already exists in\nthe to-be-sent headers, its value will be replaced. Use an array of strings\nhere to send multiple headers with the same name. Non-string values will be\nstored without modification. Therefore, request.getHeader() may return\nnon-string values. However, the non-string values will be converted to strings\nfor network transmission.
request.setHeader('Content-Type', 'application/json');\n\nor
\nrequest.setHeader('Cookie', ['type=ninja', 'language=javascript']);\n\nWhen the value is a string an exception will be thrown if it contains\ncharacters outside the latin1 encoding.
If you need to pass UTF-8 characters in the value please encode the value\nusing the RFC 8187 standard.
\nconst filename = 'Rock ðµ.txt';\nrequest.setHeader('Content-Disposition', `attachment; filename*=utf-8''${encodeURIComponent(filename)}`);\n"
},
{
"textRaw": "`request.setNoDelay([noDelay])`",
"name": "setNoDelay",
"type": "method",
"meta": {
"added": [
"v0.5.9"
],
"changes": []
},
"signatures": [
{
"params": [
{
"textRaw": "`noDelay` {boolean}",
"name": "noDelay",
"type": "boolean",
"optional": true
}
]
}
],
"desc": "Once a socket is assigned to this request and is connected\nsocket.setNoDelay() will be called.
Once a socket is assigned to this request and is connected\nsocket.setKeepAlive() will be called.
Once a socket is assigned to this request and is connected\nsocket.setTimeout() will be called.
See writable.uncork().
Sends a chunk of the body. This method can be called multiple times. If no\nContent-Length is set, data will automatically be encoded in HTTP Chunked\ntransfer encoding, so that server knows when the data ends. The\nTransfer-Encoding: chunked header is added. Calling request.end()\nis necessary to finish sending the request.
The encoding argument is optional and only applies when chunk is a string.\nDefaults to 'utf8'.
The callback argument is optional and will be called when this chunk of data\nis flushed, but only if the chunk is non-empty.
Returns true if the entire data was flushed successfully to the kernel\nbuffer. Returns false if all or part of the data was queued in user memory.\n'drain' will be emitted when the buffer is free again.
When write function is called with empty string or buffer, it does\nnothing and waits for more input.
The request.aborted property will be true if the request has\nbeen aborted.
See request.socket.
The request.finished property will be true if request.end()\nhas been called. request.end() will automatically be called if the\nrequest was initiated via http.get().
Limits maximum response headers count. If set to 0, no limit will be applied.
" }, { "textRaw": "Type: {string} The request path.", "name": "path", "type": "string", "meta": { "added": [ "v0.4.0" ], "changes": [] }, "desc": "The request path." }, { "textRaw": "Type: {string} The request method.", "name": "method", "type": "string", "meta": { "added": [ "v0.1.97" ], "changes": [] }, "desc": "The request method." }, { "textRaw": "Type: {string} The request host.", "name": "host", "type": "string", "meta": { "added": [ "v14.5.0", "v12.19.0" ], "changes": [] }, "desc": "The request host." }, { "textRaw": "Type: {string} The request protocol.", "name": "protocol", "type": "string", "meta": { "added": [ "v14.5.0", "v12.19.0" ], "changes": [] }, "desc": "The request protocol." }, { "textRaw": "Type: {boolean} Whether the request is sent through a reused socket.", "name": "reusedSocket", "type": "boolean", "meta": { "added": [ "v13.0.0", "v12.16.0" ], "changes": [] }, "desc": "When sending request through a keep-alive enabled agent, the underlying socket\nmight be reused. But if server closes connection at unfortunate time, client\nmay run into a 'ECONNRESET' error.
\nimport http from 'node:http';\nconst agent = new http.Agent({ keepAlive: true });\n\n// Server has a 5 seconds keep-alive timeout by default\nhttp\n .createServer((req, res) => {\n res.write('hello\\n');\n res.end();\n })\n .listen(3000);\n\nsetInterval(() => {\n // Adapting a keep-alive agent\n http.get('http://localhost:3000', { agent }, (res) => {\n res.on('data', (data) => {\n // Do nothing\n });\n });\n}, 5000); // Sending request on 5s interval so it's easy to hit idle timeout\n\nconst http = require('node:http');\nconst agent = new http.Agent({ keepAlive: true });\n\n// Server has a 5 seconds keep-alive timeout by default\nhttp\n .createServer((req, res) => {\n res.write('hello\\n');\n res.end();\n })\n .listen(3000);\n\nsetInterval(() => {\n // Adapting a keep-alive agent\n http.get('http://localhost:3000', { agent }, (res) => {\n res.on('data', (data) => {\n // Do nothing\n });\n });\n}, 5000); // Sending request on 5s interval so it's easy to hit idle timeout\n\nBy marking a request whether it reused socket or not, we can do\nautomatic error retry base on it.
\nimport http from 'node:http';\nconst agent = new http.Agent({ keepAlive: true });\n\nfunction retriableRequest() {\n const req = http\n .get('http://localhost:3000', { agent }, (res) => {\n // ...\n })\n .on('error', (err) => {\n // Check if retry is needed\n if (req.reusedSocket && err.code === 'ECONNRESET') {\n retriableRequest();\n }\n });\n}\n\nretriableRequest();\n\nconst http = require('node:http');\nconst agent = new http.Agent({ keepAlive: true });\n\nfunction retriableRequest() {\n const req = http\n .get('http://localhost:3000', { agent }, (res) => {\n // ...\n })\n .on('error', (err) => {\n // Check if retry is needed\n if (req.reusedSocket && err.code === 'ECONNRESET') {\n retriableRequest();\n }\n });\n}\n\nretriableRequest();\n",
"shortDesc": "Whether the request is sent through a reused socket."
},
{
"textRaw": "Type: {stream.Duplex}",
"name": "socket",
"type": "stream.Duplex",
"meta": {
"added": [
"v0.3.0"
],
"changes": []
},
"desc": "Reference to the underlying socket. Usually users will not want to access\nthis property. In particular, the socket will not emit 'readable' events\nbecause of how the protocol parser attaches to the socket.
import http from 'node:http';\nconst options = {\n host: 'www.google.com',\n};\nconst req = http.get(options);\nreq.end();\nreq.once('response', (res) => {\n const ip = req.socket.localAddress;\n const port = req.socket.localPort;\n console.log(`Your IP address is ${ip} and your source port is ${port}.`);\n // Consume response object\n});\n\nconst http = require('node:http');\nconst options = {\n host: 'www.google.com',\n};\nconst req = http.get(options);\nreq.end();\nreq.once('response', (res) => {\n const ip = req.socket.localAddress;\n const port = req.socket.localPort;\n console.log(`Your IP address is ${ip} and your source port is ${port}.`);\n // Consume response object\n});\n\nThis property is guaranteed to be an instance of the net.Socket class,\na subclass of stream.Duplex, unless the user specified a socket\ntype other than net.Socket.
Is true after request.end() has been called. This property\ndoes not indicate whether the data has been flushed, for this use\nrequest.writableFinished instead.
Is true if all data has been flushed to the underlying system, immediately\nbefore the 'finish' event is emitted.
net.ServerEmitted each time a request with an HTTP Expect: 100-continue is received.\nIf this event is not listened for, the server will automatically respond\nwith a 100 Continue as appropriate.
Handling this event involves calling response.writeContinue() if the\nclient should continue to send the request body, or generating an appropriate\nHTTP response (e.g. 400 Bad Request) if the client should not continue to send\nthe request body.
When this event is emitted and handled, the 'request' event will\nnot be emitted.
Emitted each time a request with an HTTP Expect header is received, where the\nvalue is not 100-continue. If this event is not listened for, the server will\nautomatically respond with a 417 Expectation Failed as appropriate.
When this event is emitted and handled, the 'request' event will\nnot be emitted.
If a client connection emits an 'error' event, it will be forwarded here.\nListener of this event is responsible for closing/destroying the underlying\nsocket. For example, one may wish to more gracefully close the socket with a\ncustom HTTP response instead of abruptly severing the connection. The socket\nmust be closed or destroyed before the listener ends.
This event is guaranteed to be passed an instance of the net.Socket class,\na subclass of stream.Duplex, unless the user specifies a socket\ntype other than net.Socket.
Default behavior is to try close the socket with an HTTP '400 Bad Request',\nor an HTTP '431 Request Header Fields Too Large' in the case of an\nHPE_HEADER_OVERFLOW error. If the socket is not writable or headers\nof the current attached http.ServerResponse has been sent, it is\nimmediately destroyed.
socket is the net.Socket object that the error originated from.
import http from 'node:http';\n\nconst server = http.createServer((req, res) => {\n res.end();\n});\nserver.on('clientError', (err, socket) => {\n socket.end('HTTP/1.1 400 Bad Request\\r\\n\\r\\n');\n});\nserver.listen(8000);\n\nconst http = require('node:http');\n\nconst server = http.createServer((req, res) => {\n res.end();\n});\nserver.on('clientError', (err, socket) => {\n socket.end('HTTP/1.1 400 Bad Request\\r\\n\\r\\n');\n});\nserver.listen(8000);\n\nWhen the 'clientError' event occurs, there is no request or response\nobject, so any HTTP response sent, including response headers and payload,\nmust be written directly to the socket object. Care must be taken to\nensure the response is a properly formatted HTTP response message.
err is an instance of Error with two extra columns:
bytesParsed: the bytes count of request packet that Node.js may have parsed\ncorrectly;rawPacket: the raw packet of current request.In some cases, the client has already received the response and/or the socket\nhas already been destroyed, like in case of ECONNRESET errors. Before\ntrying to send data to the socket, it is better to check that it is still\nwritable.
server.on('clientError', (err, socket) => {\n if (err.code === 'ECONNRESET' || !socket.writable) {\n return;\n }\n\n socket.end('HTTP/1.1 400 Bad Request\\r\\n\\r\\n');\n});\n"
},
{
"textRaw": "Event: `'close'`",
"name": "close",
"type": "event",
"meta": {
"added": [
"v0.1.4"
],
"changes": []
},
"params": [],
"desc": "Emitted when the server closes.
" }, { "textRaw": "Event: `'connect'`", "name": "connect", "type": "event", "meta": { "added": [ "v0.7.0" ], "changes": [] }, "params": [ { "textRaw": "`request` {http.IncomingMessage} Arguments for the HTTP request, as it is in the `'request'` event", "name": "request", "type": "http.IncomingMessage", "desc": "Arguments for the HTTP request, as it is in the `'request'` event" }, { "textRaw": "`socket` {stream.Duplex} Network socket between the server and client", "name": "socket", "type": "stream.Duplex", "desc": "Network socket between the server and client" }, { "textRaw": "`head` {Buffer} The first packet of the tunneling stream (may be empty)", "name": "head", "type": "Buffer", "desc": "The first packet of the tunneling stream (may be empty)" } ], "desc": "Emitted each time a client requests an HTTP CONNECT method. If this event is\nnot listened for, then clients requesting a CONNECT method will have their\nconnections closed.
This event is guaranteed to be passed an instance of the net.Socket class,\na subclass of stream.Duplex, unless the user specifies a socket\ntype other than net.Socket.
After this event is emitted, the request's socket will not have a 'data'\nevent listener, meaning it will need to be bound in order to handle data\nsent to the server on that socket.
This event is emitted when a new TCP stream is established. socket is\ntypically an object of type net.Socket. Usually users will not want to\naccess this event. In particular, the socket will not emit 'readable' events\nbecause of how the protocol parser attaches to the socket. The socket can\nalso be accessed at request.socket.
This event can also be explicitly emitted by users to inject connections\ninto the HTTP server. In that case, any Duplex stream can be passed.
If socket.setTimeout() is called here, the timeout will be replaced with\nserver.keepAliveTimeout when the socket has served a request (if\nserver.keepAliveTimeout is non-zero).
This event is guaranteed to be passed an instance of the net.Socket class,\na subclass of stream.Duplex, unless the user specifies a socket\ntype other than net.Socket.
When the number of requests on a socket reaches the threshold of\nserver.maxRequestsPerSocket, the server will drop new requests\nand emit 'dropRequest' event instead, then send 503 to client.
Emitted each time there is a request. There may be multiple requests\nper connection (in the case of HTTP Keep-Alive connections).
" }, { "textRaw": "Event: `'upgrade'`", "name": "upgrade", "type": "event", "meta": { "added": [ "v0.1.94" ], "changes": [ { "version": "v26.0.0", "pr-url": "https://github.com/nodejs/node/pull/60016", "description": "Request bodies are no longer exposed raw (unparsed) on the socket argument. Instead, if a body is received, the stream argument will be a duplex that emits socket content only after the request body, while the parsed request body data will be emitted from the request, just as in normal server `'request'` events." }, { "version": [ "v24.9.0", "v22.21.0" ], "pr-url": "https://github.com/nodejs/node/pull/59824", "description": "Whether this event is fired can now be controlled by the `shouldUpgradeCallback` and sockets will be destroyed if upgraded while no event handler is listening." }, { "version": "v10.0.0", "pr-url": "https://github.com/nodejs/node/pull/19981", "description": "Not listening to this event no longer causes the socket to be destroyed if a client sends an Upgrade header." } ] }, "params": [ { "textRaw": "`request` {http.IncomingMessage} Arguments for the HTTP request, as it is in the `'request'` event", "name": "request", "type": "http.IncomingMessage", "desc": "Arguments for the HTTP request, as it is in the `'request'` event" }, { "textRaw": "`stream` {stream.Duplex} The upgraded stream between the server and client", "name": "stream", "type": "stream.Duplex", "desc": "The upgraded stream between the server and client" }, { "textRaw": "`head` {Buffer} The first packet of the upgraded stream (may be empty)", "name": "head", "type": "Buffer", "desc": "The first packet of the upgraded stream (may be empty)" } ], "desc": "Emitted each time a client's HTTP upgrade request is accepted. By default\nall HTTP upgrade requests are ignored (i.e. only regular 'request' events\nare emitted, sticking with the normal HTTP request/response flow) unless you\nlisten to this event, in which case they are all accepted (i.e. the 'upgrade'\nevent is emitted instead, and future communication must handled directly\nthrough the raw stream). You can control this more precisely by using the\nserver shouldUpgradeCallback option.
Listening to this event is optional and clients cannot insist on a protocol\nchange.
\nIf an upgrade is accepted by shouldUpgradeCallback but no event handler\nis registered then the socket will be destroyed, resulting in an immediate\nconnection closure for the client.
In the uncommon case that the incoming request has a body, this body will be\nparsed as normal, separate to the upgrade stream, and the raw stream data will\nonly begin after it has completed. To ensure that reading from the stream isn't\nblocked by waiting for the request body to be read, any reads on the stream\nwill start the request body flowing automatically. If you want to read the\nrequest body, ensure that you do so (i.e. you attach 'data' listeners)\nbefore starting to read from the upgraded stream.
The stream argument will typically be the net.Socket instance used by the\nrequest, but in some cases (such as with a request body) it may be a duplex\nstream. If required, you can access the raw connection underlying the request\nvia request.socket, which is guaranteed to be an instance of net.Socket\nunless the user specified another socket type.
Stops the server from accepting new connections and closes all connections\nconnected to this server which are not sending a request or waiting for\na response.\nSee net.Server.close().
const http = require('node:http');\n\nconst server = http.createServer({ keepAliveTimeout: 60000 }, (req, res) => {\n res.writeHead(200, { 'Content-Type': 'application/json' });\n res.end(JSON.stringify({\n data: 'Hello World!',\n }));\n});\n\nserver.listen(8000);\n// Close the server after 10 seconds\nsetTimeout(() => {\n server.close(() => {\n console.log('server on port 8000 closed successfully');\n });\n}, 10000);\n"
},
{
"textRaw": "`server.closeAllConnections()`",
"name": "closeAllConnections",
"type": "method",
"meta": {
"added": [
"v18.2.0"
],
"changes": []
},
"signatures": [
{
"params": []
}
],
"desc": "Closes all established HTTP(S) connections connected to this server, including\nactive connections connected to this server which are sending a request or\nwaiting for a response. This does not destroy sockets upgraded to a different\nprotocol, such as WebSocket or HTTP/2.
\n\n\nThis is a forceful way of closing all connections and should be used with\ncaution. Whenever using this in conjunction with
\nserver.close, calling this\nafterserver.closeis recommended as to avoid race conditions where new\nconnections are created between a call to this and a call toserver.close.
const http = require('node:http');\n\nconst server = http.createServer({ keepAliveTimeout: 60000 }, (req, res) => {\n res.writeHead(200, { 'Content-Type': 'application/json' });\n res.end(JSON.stringify({\n data: 'Hello World!',\n }));\n});\n\nserver.listen(8000);\n// Close the server after 10 seconds\nsetTimeout(() => {\n server.close(() => {\n console.log('server on port 8000 closed successfully');\n });\n // Closes all connections, ensuring the server closes successfully\n server.closeAllConnections();\n}, 10000);\n"
},
{
"textRaw": "`server.closeIdleConnections()`",
"name": "closeIdleConnections",
"type": "method",
"meta": {
"added": [
"v18.2.0"
],
"changes": []
},
"signatures": [
{
"params": []
}
],
"desc": "Closes all connections connected to this server which are not sending a request\nor waiting for a response.
\n\n\nStarting with Node.js 19.0.0, there's no need for calling this method in\nconjunction with
\nserver.closeto reapkeep-aliveconnections. Using it\nwon't cause any harm though, and it can be useful to ensure backwards\ncompatibility for libraries and applications that need to support versions\nolder than 19.0.0. Whenever using this in conjunction withserver.close,\ncalling this afterserver.closeis recommended as to avoid race\nconditions where new connections are created between a call to this and a\ncall toserver.close.
const http = require('node:http');\n\nconst server = http.createServer({ keepAliveTimeout: 60000 }, (req, res) => {\n res.writeHead(200, { 'Content-Type': 'application/json' });\n res.end(JSON.stringify({\n data: 'Hello World!',\n }));\n});\n\nserver.listen(8000);\n// Close the server after 10 seconds\nsetTimeout(() => {\n server.close(() => {\n console.log('server on port 8000 closed successfully');\n });\n // Closes idle connections, such as keep-alive connections. Server will close\n // once remaining active connections are terminated\n server.closeIdleConnections();\n}, 10000);\n"
},
{
"textRaw": "`server.listen()`",
"name": "listen",
"type": "method",
"signatures": [
{
"params": []
}
],
"desc": "Starts the HTTP server listening for connections.\nThis method is identical to server.listen() from net.Server.
Sets the timeout value for sockets, and emits a 'timeout' event on\nthe Server object, passing the socket as an argument, if a timeout\noccurs.
If there is a 'timeout' event listener on the Server object, then it\nwill be called with the timed-out socket as an argument.
By default, the Server does not timeout sockets. However, if a callback\nis assigned to the Server's 'timeout' event, timeouts must be handled\nexplicitly.
Calls server.close() and returns a promise that fulfills when the\nserver has closed.
Limit the amount of time the parser will wait to receive the complete HTTP\nheaders.
\nIf the timeout expires, the server responds with status 408 without\nforwarding the request to the request listener and then closes the connection.
\nIt must be set to a non-zero value (e.g. 120 seconds) to protect against\npotential Denial-of-Service attacks in case the server is deployed without a\nreverse proxy in front.
" }, { "textRaw": "Type: {boolean} Indicates whether or not the server is listening for connections.", "name": "listening", "type": "boolean", "meta": { "added": [ "v5.7.0" ], "changes": [] }, "desc": "Indicates whether or not the server is listening for connections." }, { "textRaw": "Type: {number} **Default:** `2000`", "name": "maxHeadersCount", "type": "number", "meta": { "added": [ "v0.7.0" ], "changes": [] }, "default": "`2000`", "desc": "Limits maximum incoming headers count. If set to 0, no limit will be applied.
" }, { "textRaw": "Type: {number} **Default:** `300000`", "name": "requestTimeout", "type": "number", "meta": { "added": [ "v14.11.0" ], "changes": [ { "version": "v18.0.0", "pr-url": "https://github.com/nodejs/node/pull/41263", "description": "The default request timeout changed from no timeout to 300s (5 minutes)." } ] }, "default": "`300000`", "desc": "Sets the timeout value in milliseconds for receiving the entire request from\nthe client.
\nIf the timeout expires, the server responds with status 408 without\nforwarding the request to the request listener and then closes the connection.
\nIt must be set to a non-zero value (e.g. 120 seconds) to protect against\npotential Denial-of-Service attacks in case the server is deployed without a\nreverse proxy in front.
" }, { "textRaw": "Type: {number} Requests per socket. **Default:** 0 (no limit)", "name": "maxRequestsPerSocket", "type": "number", "meta": { "added": [ "v16.10.0" ], "changes": [] }, "default": "0 (no limit)", "desc": "The maximum number of requests socket can handle\nbefore closing keep alive connection.
\nA value of 0 will disable the limit.
When the limit is reached it will set the Connection header value to close,\nbut will not actually close the connection, subsequent requests sent\nafter the limit is reached will get 503 Service Unavailable as a response.
The number of milliseconds of inactivity before a socket is presumed\nto have timed out.
\nA value of 0 will disable the timeout behavior on incoming connections.
The socket timeout logic is set up on connection, so changing this\nvalue only affects new connections to the server, not any existing connections.
", "shortDesc": "Timeout in milliseconds." }, { "textRaw": "Type: {number} Timeout in milliseconds. **Default:** `5000` (5 seconds).", "name": "keepAliveTimeout", "type": "number", "meta": { "added": [ "v8.0.0" ], "changes": [] }, "default": "`5000` (5 seconds)", "desc": "The number of milliseconds of inactivity a server needs to wait for additional\nincoming data, after it has finished writing the last response, before a socket\nwill be destroyed.
\nThis timeout value is combined with the\nserver.keepAliveTimeoutBuffer option to determine the actual socket\ntimeout, calculated as:\nsocketTimeout = keepAliveTimeout + keepAliveTimeoutBuffer\nIf the server receives new data before the keep-alive timeout has fired, it\nwill reset the regular inactivity timeout, i.e., server.timeout.
A value of 0 will disable the keep-alive timeout behavior on incoming\nconnections.\nA value of 0 makes the HTTP server behave similarly to Node.js versions prior\nto 8.0.0, which did not have a keep-alive timeout.
The socket timeout logic is set up on connection, so changing this value only\naffects new connections to the server, not any existing connections.
", "shortDesc": "Timeout in milliseconds." }, { "textRaw": "Type: {number} Timeout in milliseconds. **Default:** `1000` (1 second).", "name": "keepAliveTimeoutBuffer", "type": "number", "meta": { "added": [ "v24.6.0", "v22.19.0" ], "changes": [] }, "default": "`1000` (1 second)", "desc": "An additional buffer time added to the\nserver.keepAliveTimeout to extend the internal socket timeout.
This buffer helps reduce connection reset (ECONNRESET) errors by increasing\nthe socket timeout slightly beyond the advertised keep-alive timeout.
This option applies only to new incoming connections.
", "shortDesc": "Timeout in milliseconds." } ] }, { "textRaw": "Class: `http.ServerResponse`", "name": "http.ServerResponse", "type": "class", "meta": { "added": [ "v0.1.17" ], "changes": [] }, "desc": "http.OutgoingMessageThis object is created internally by an HTTP server, not by the user. It is\npassed as the second parameter to the 'request' event.
Indicates that the response is completed, or its underlying connection was\nterminated prematurely (before the response completion).
" }, { "textRaw": "Event: `'finish'`", "name": "finish", "type": "event", "meta": { "added": [ "v0.3.6" ], "changes": [] }, "params": [], "desc": "Emitted when the response has been sent. More specifically, this event is\nemitted when the last segment of the response headers and body have been\nhanded off to the operating system for transmission over the network. It\ndoes not imply that the client has received anything yet.
" } ], "methods": [ { "textRaw": "`response.addTrailers(headers)`", "name": "addTrailers", "type": "method", "meta": { "added": [ "v0.3.0" ], "changes": [] }, "signatures": [ { "params": [ { "textRaw": "`headers` {Object}", "name": "headers", "type": "Object" } ] } ], "desc": "This method adds HTTP trailing headers (a header but at the end of the\nmessage) to the response.
\nTrailers will only be emitted if chunked encoding is used for the\nresponse; if it is not (e.g. if the request was HTTP/1.0), they will\nbe silently discarded.
\nHTTP requires the Trailer header to be sent in order to\nemit trailers, with a list of the header fields in its value. E.g.,
response.writeHead(200, { 'Content-Type': 'text/plain',\n 'Trailer': 'Content-MD5' });\nresponse.write(fileData);\nresponse.addTrailers({ 'Content-MD5': '7895bf4b8828b55ceaf47747b4bca667' });\nresponse.end();\n\nAttempting to set a header field name or value that contains invalid characters\nwill result in a TypeError being thrown.
See writable.cork().
This method signals to the server that all of the response headers and body\nhave been sent; that server should consider this message complete.\nThe method, response.end(), MUST be called on each response.
If data is specified, it is similar in effect to calling\nresponse.write(data, encoding) followed by response.end(callback).
If callback is specified, it will be called when the response stream\nis finished.
Flushes the response headers. See also: request.flushHeaders().
Reads out a header that's already been queued but not sent to the client.\nThe name is case-insensitive. The type of the return value depends\non the arguments provided to response.setHeader().
response.setHeader('Content-Type', 'text/html');\nresponse.setHeader('Content-Length', Buffer.byteLength(body));\nresponse.setHeader('Set-Cookie', ['type=ninja', 'language=javascript']);\nconst contentType = response.getHeader('content-type');\n// contentType is 'text/html'\nconst contentLength = response.getHeader('Content-Length');\n// contentLength is of type number\nconst setCookie = response.getHeader('set-cookie');\n// setCookie is of type string[]\n"
},
{
"textRaw": "`response.getHeaderNames()`",
"name": "getHeaderNames",
"type": "method",
"meta": {
"added": [
"v7.7.0"
],
"changes": []
},
"signatures": [
{
"params": [],
"return": {
"textRaw": "Returns: {string[]}",
"name": "return",
"type": "string[]"
}
}
],
"desc": "Returns an array containing the unique names of the current outgoing headers.\nAll header names are lowercase.
\nresponse.setHeader('Foo', 'bar');\nresponse.setHeader('Set-Cookie', ['foo=bar', 'bar=baz']);\n\nconst headerNames = response.getHeaderNames();\n// headerNames === ['foo', 'set-cookie']\n"
},
{
"textRaw": "`response.getHeaders()`",
"name": "getHeaders",
"type": "method",
"meta": {
"added": [
"v7.7.0"
],
"changes": []
},
"signatures": [
{
"params": [],
"return": {
"textRaw": "Returns: {Object}",
"name": "return",
"type": "Object"
}
}
],
"desc": "Returns a shallow copy of the current outgoing headers. Since a shallow copy\nis used, array values may be mutated without additional calls to various\nheader-related http module methods. The keys of the returned object are the\nheader names and the values are the respective header values. All header names\nare lowercase.
\nThe object returned by the response.getHeaders() method does not\nprototypically inherit from the JavaScript Object. This means that typical\nObject methods such as obj.toString(), obj.hasOwnProperty(), and others\nare not defined and will not work.
response.setHeader('Foo', 'bar');\nresponse.setHeader('Set-Cookie', ['foo=bar', 'bar=baz']);\n\nconst headers = response.getHeaders();\n// headers === { foo: 'bar', 'set-cookie': ['foo=bar', 'bar=baz'] }\n"
},
{
"textRaw": "`response.hasHeader(name)`",
"name": "hasHeader",
"type": "method",
"meta": {
"added": [
"v7.7.0"
],
"changes": []
},
"signatures": [
{
"params": [
{
"textRaw": "`name` {string}",
"name": "name",
"type": "string"
}
],
"return": {
"textRaw": "Returns: {boolean}",
"name": "return",
"type": "boolean"
}
}
],
"desc": "Returns true if the header identified by name is currently set in the\noutgoing headers. The header name matching is case-insensitive.
const hasContentType = response.hasHeader('content-type');\n"
},
{
"textRaw": "`response.removeHeader(name)`",
"name": "removeHeader",
"type": "method",
"meta": {
"added": [
"v0.4.0"
],
"changes": []
},
"signatures": [
{
"params": [
{
"textRaw": "`name` {string}",
"name": "name",
"type": "string"
}
]
}
],
"desc": "Removes a header that's queued for implicit sending.
\nresponse.removeHeader('Content-Encoding');\n"
},
{
"textRaw": "`response.setHeader(name, value)`",
"name": "setHeader",
"type": "method",
"meta": {
"added": [
"v0.4.0"
],
"changes": []
},
"signatures": [
{
"params": [
{
"textRaw": "`name` {string}",
"name": "name",
"type": "string"
},
{
"textRaw": "`value` {number | string | string[]}",
"name": "value",
"type": "number | string | string[]"
}
],
"return": {
"textRaw": "Returns: {http.ServerResponse}",
"name": "return",
"type": "http.ServerResponse"
}
}
],
"desc": "Returns the response object.
\nSets a single header value for implicit headers. If this header already exists\nin the to-be-sent headers, its value will be replaced. Use an array of strings\nhere to send multiple headers with the same name. Non-string values will be\nstored without modification. Therefore, response.getHeader() may return\nnon-string values. However, the non-string values will be converted to strings\nfor network transmission. The same response object is returned to the caller,\nto enable call chaining.
response.setHeader('Content-Type', 'text/html');\n\nor
\nresponse.setHeader('Set-Cookie', ['type=ninja', 'language=javascript']);\n\nAttempting to set a header field name or value that contains invalid characters\nwill result in a TypeError being thrown.
When headers have been set with response.setHeader(), they will be merged\nwith any headers passed to response.writeHead(), with the headers passed\nto response.writeHead() given precedence.
// Returns content-type = text/plain\nconst server = http.createServer((req, res) => {\n res.setHeader('Content-Type', 'text/html');\n res.setHeader('X-Foo', 'bar');\n res.writeHead(200, { 'Content-Type': 'text/plain' });\n res.end('ok');\n});\n\nIf response.writeHead() method is called and this method has not been\ncalled, it will directly write the supplied header values onto the network\nchannel without caching internally, and the response.getHeader() on the\nheader will not yield the expected result. If progressive population of headers\nis desired with potential future retrieval and modification, use\nresponse.setHeader() instead of response.writeHead().
Sets the Socket's timeout value to msecs. If a callback is\nprovided, then it is added as a listener on the 'timeout' event on\nthe response object.
If no 'timeout' listener is added to the request, the response, or\nthe server, then sockets are destroyed when they time out. If a handler is\nassigned to the request, the response, or the server's 'timeout' events,\ntimed out sockets must be handled explicitly.
See writable.uncork().
If this method is called and response.writeHead() has not been called,\nit will switch to implicit header mode and flush the implicit headers.
This sends a chunk of the response body. This method may\nbe called multiple times to provide successive parts of the body.
\nIf rejectNonStandardBodyWrites is set to true in createServer\nthen writing to the body is not allowed when the request method or response\nstatus do not support content. If an attempt is made to write to the body for a\nHEAD request or as part of a 204 or 304response, a synchronous Error\nwith the code ERR_HTTP_BODY_NOT_ALLOWED is thrown.
chunk can be a string or a buffer. If chunk is a string,\nthe second parameter specifies how to encode it into a byte stream.\ncallback will be called when this chunk of data is flushed.
This is the raw HTTP body and has nothing to do with higher-level multi-part\nbody encodings that may be used.
\nThe first time response.write() is called, it will send the buffered\nheader information and the first chunk of the body to the client. The second\ntime response.write() is called, Node.js assumes data will be streamed,\nand sends the new data separately. That is, the response is buffered up to the\nfirst chunk of the body.
Returns true if the entire data was flushed successfully to the kernel\nbuffer. Returns false if all or part of the data was queued in user memory.\n'drain' will be emitted when the buffer is free again.
Sends an HTTP/1.1 100 Continue message to the client, indicating that\nthe request body should be sent. See the 'checkContinue' event on\nServer.
Sends an HTTP/1.1 103 Early Hints message to the client with a Link header,\nindicating that the user agent can preload/preconnect the linked resources.\nThe hints is an object containing the values of headers to be sent with\nearly hints message. The optional callback argument will be called when\nthe response message has been written.
Example
\nconst earlyHintsLink = '</styles.css>; rel=preload; as=style';\nresponse.writeEarlyHints({\n 'link': earlyHintsLink,\n});\n\nconst earlyHintsLinks = [\n '</styles.css>; rel=preload; as=style',\n '</scripts.js>; rel=preload; as=script',\n];\nresponse.writeEarlyHints({\n 'link': earlyHintsLinks,\n 'x-trace-id': 'id for diagnostics',\n});\n\nconst earlyHintsCallback = () => console.log('early hints message sent');\nresponse.writeEarlyHints({\n 'link': earlyHintsLinks,\n}, earlyHintsCallback);\n"
},
{
"textRaw": "`response.writeHead(statusCode[, statusMessage][, headers])`",
"name": "writeHead",
"type": "method",
"meta": {
"added": [
"v0.1.30"
],
"changes": [
{
"version": "v14.14.0",
"pr-url": "https://github.com/nodejs/node/pull/35274",
"description": "Allow passing headers as an array."
},
{
"version": [
"v11.10.0",
"v10.17.0"
],
"pr-url": "https://github.com/nodejs/node/pull/25974",
"description": "Return `this` from `writeHead()` to allow chaining with `end()`."
},
{
"version": [
"v5.11.0",
"v4.4.5"
],
"pr-url": "https://github.com/nodejs/node/pull/6291",
"description": "A `RangeError` is thrown if `statusCode` is not a number in the range `[100, 999]`."
}
]
},
"signatures": [
{
"params": [
{
"textRaw": "`statusCode` {number}",
"name": "statusCode",
"type": "number"
},
{
"textRaw": "`statusMessage` {string}",
"name": "statusMessage",
"type": "string",
"optional": true
},
{
"textRaw": "`headers` {Object | Array}",
"name": "headers",
"type": "Object | Array",
"optional": true
}
],
"return": {
"textRaw": "Returns: {http.ServerResponse}",
"name": "return",
"type": "http.ServerResponse"
}
}
],
"desc": "Sends a response header to the request. The status code is a 3-digit HTTP\nstatus code, like 404. The last argument, headers, are the response headers.\nOptionally one can give a human-readable statusMessage as the second\nargument.
headers may be an Array where the keys and values are in the same list.\nIt is not a list of tuples. So, the even-numbered offsets are key values,\nand the odd-numbered offsets are the associated values. The array is in the same\nformat as request.rawHeaders.
Returns a reference to the ServerResponse, so that calls can be chained.
const body = 'hello world';\nresponse\n .writeHead(200, {\n 'Content-Length': Buffer.byteLength(body),\n 'Content-Type': 'text/plain',\n })\n .end(body);\n\nThis method must only be called once on a message and it must\nbe called before response.end() is called.
If response.write() or response.end() are called before calling\nthis, the implicit/mutable headers will be calculated and call this function.
When headers have been set with response.setHeader(), they will be merged\nwith any headers passed to response.writeHead(), with the headers passed\nto response.writeHead() given precedence.
If this method is called and response.setHeader() has not been called,\nit will directly write the supplied header values onto the network channel\nwithout caching internally, and the response.getHeader() on the header\nwill not yield the expected result. If progressive population of headers is\ndesired with potential future retrieval and modification, use\nresponse.setHeader() instead.
// Returns content-type = text/plain\nconst server = http.createServer((req, res) => {\n res.setHeader('Content-Type', 'text/html');\n res.setHeader('X-Foo', 'bar');\n res.writeHead(200, { 'Content-Type': 'text/plain' });\n res.end('ok');\n});\n\nContent-Length is read in bytes, not characters. Use\nBuffer.byteLength() to determine the length of the body in bytes. Node.js\nwill check whether Content-Length and the length of the body which has\nbeen transmitted are equal or not.
Attempting to set a header field name or value that contains invalid characters\nwill result in a TypeError being thrown.
Sends an arbitrary HTTP/1.1 1xx informational response to the client. This\nis a generic equivalent of response.writeContinue(),\nresponse.writeProcessing() and response.writeEarlyHints(), and\ncan be called multiple times before the final response. After the final\nresponse headers have been sent (via response.writeHead() or an\nimplicit header), calling this method throws ERR_HTTP_HEADERS_SENT.
Clients receive these responses via the 'information'\nevent on http.ClientRequest.
response.writeInformation(110, { 'X-Progress': '50%' });\n"
},
{
"textRaw": "`response.writeProcessing()`",
"name": "writeProcessing",
"type": "method",
"meta": {
"added": [
"v10.0.0"
],
"changes": []
},
"signatures": [
{
"params": []
}
],
"desc": "Sends an HTTP/1.1 102 Processing message to the client, indicating that\nthe request body should be sent.
" } ], "properties": [ { "textRaw": "Type: {stream.Duplex}", "name": "connection", "type": "stream.Duplex", "meta": { "added": [ "v0.3.0" ], "changes": [], "deprecated": [ "v13.0.0" ] }, "stability": 0, "stabilityText": "Deprecated. Use `response.socket`.", "desc": "See response.socket.
The response.finished property will be true if response.end()\nhas been called.
Boolean (read-only). True if headers were sent, false otherwise.
" }, { "textRaw": "Type: {http.IncomingMessage}", "name": "req", "type": "http.IncomingMessage", "meta": { "added": [ "v15.7.0" ], "changes": [] }, "desc": "A reference to the original HTTP request object.
When true, the Date header will be automatically generated and sent in\nthe response if it is not already present in the headers. Defaults to true.
\nThis should only be disabled for testing; the Date header is required in\nmost HTTP responses (see RFC 9110 Section 6.6.1 for details).
" }, { "textRaw": "Type: {stream.Duplex}", "name": "socket", "type": "stream.Duplex", "meta": { "added": [ "v0.3.0" ], "changes": [] }, "desc": "Reference to the underlying socket. Usually users will not want to access\nthis property. In particular, the socket will not emit 'readable' events\nbecause of how the protocol parser attaches to the socket. After\nresponse.end(), the property is nulled.
import http from 'node:http';\nconst server = http.createServer((req, res) => {\n const ip = res.socket.remoteAddress;\n const port = res.socket.remotePort;\n res.end(`Your IP address is ${ip} and your source port is ${port}.`);\n}).listen(3000);\n\nconst http = require('node:http');\nconst server = http.createServer((req, res) => {\n const ip = res.socket.remoteAddress;\n const port = res.socket.remotePort;\n res.end(`Your IP address is ${ip} and your source port is ${port}.`);\n}).listen(3000);\n\nThis property is guaranteed to be an instance of the net.Socket class,\na subclass of stream.Duplex, unless the user specified a socket\ntype other than net.Socket.
When using implicit headers (not calling response.writeHead() explicitly),\nthis property controls the status code that will be sent to the client when\nthe headers get flushed.
response.statusCode = 404;\n\nAfter response header was sent to the client, this property indicates the\nstatus code which was sent out.
" }, { "textRaw": "Type: {string}", "name": "statusMessage", "type": "string", "meta": { "added": [ "v0.11.8" ], "changes": [] }, "desc": "When using implicit headers (not calling response.writeHead() explicitly),\nthis property controls the status message that will be sent to the client when\nthe headers get flushed. If this is left as undefined then the standard\nmessage for the status code will be used.
response.statusMessage = 'Not found';\n\nAfter response header was sent to the client, this property indicates the\nstatus message which was sent out.
" }, { "textRaw": "Type: {boolean} **Default:** `false`", "name": "strictContentLength", "type": "boolean", "meta": { "added": [ "v18.10.0", "v16.18.0" ], "changes": [] }, "default": "`false`", "desc": "If set to true, Node.js will check whether the Content-Length\nheader value and the size of the body, in bytes, are equal.\nMismatching the Content-Length header value will result\nin an Error being thrown, identified by code: 'ERR_HTTP_CONTENT_LENGTH_MISMATCH'.
Is true after response.end() has been called. This property\ndoes not indicate whether the data has been flushed, for this use\nresponse.writableFinished instead.
Is true if all data has been flushed to the underlying system, immediately\nbefore the 'finish' event is emitted.
stream.ReadableAn IncomingMessage object is created by http.Server or\nhttp.ClientRequest and passed as the first argument to the 'request'\nand 'response' event respectively. It may be used to access response\nstatus, headers, and data.
Different from its socket value which is a subclass of stream.Duplex, the\nIncomingMessage itself extends stream.Readable and is created separately to\nparse and emit the incoming HTTP headers and payload, as the underlying socket\nmay be reused multiple times in case of keep-alive.
Emitted when the request has been aborted.
" }, { "textRaw": "Event: `'close'`", "name": "close", "type": "event", "meta": { "added": [ "v0.4.2" ], "changes": [ { "version": "v16.0.0", "pr-url": "https://github.com/nodejs/node/pull/33035", "description": "The close event is now emitted when the request has been completed and not when the underlying socket is closed." } ] }, "params": [], "desc": "Emitted when the request has been completed.
" } ], "properties": [ { "textRaw": "Type: {boolean}", "name": "aborted", "type": "boolean", "meta": { "added": [ "v10.1.0" ], "changes": [], "deprecated": [ "v17.0.0", "v16.12.0" ] }, "stability": 0, "stabilityText": "Deprecated. Check `message.destroyed` from {stream.Readable}.", "desc": "The message.aborted property will be true if the request has\nbeen aborted.
The message.complete property will be true if a complete HTTP message has\nbeen received and successfully parsed.
This property is particularly useful as a means of determining if a client or\nserver fully transmitted a message before a connection was terminated:
\nconst req = http.request({\n host: '127.0.0.1',\n port: 8080,\n method: 'POST',\n}, (res) => {\n res.resume();\n res.on('end', () => {\n if (!res.complete)\n console.error(\n 'The connection was terminated while the message was still being sent');\n });\n});\n"
},
{
"textRaw": "`message.connection`",
"name": "connection",
"type": "property",
"meta": {
"added": [
"v0.1.90"
],
"changes": [],
"deprecated": [
"v16.0.0"
]
},
"stability": 0,
"stabilityText": "Deprecated. Use `message.socket`.",
"desc": "Alias for message.socket.
The request/response headers object.
\nKey-value pairs of header names and values. Header names are lower-cased.
\n// Prints something like:\n//\n// { 'user-agent': 'curl/7.22.0',\n// host: '127.0.0.1:8000',\n// accept: '*/*' }\nconsole.log(request.headers);\n\nDuplicates in raw headers are handled in the following ways, depending on the\nheader name:
\nage, authorization, content-length, content-type,\netag, expires, from, host, if-modified-since, if-unmodified-since,\nlast-modified, location, max-forwards, proxy-authorization, referer,\nretry-after, server, or user-agent are discarded.\nTo allow duplicate values of the headers listed above to be joined,\nuse the option joinDuplicateHeaders in http.request()\nand http.createServer(). See RFC 9110 Section 5.3 for more\ninformation.set-cookie is always an array. Duplicates are added to the array.cookie headers, the values are joined together with ; ., .Similar to message.headers, but there is no join logic and the values are\nalways arrays of strings, even for headers received just once.
// Prints something like:\n//\n// { 'user-agent': ['curl/7.22.0'],\n// host: ['127.0.0.1:8000'],\n// accept: ['*/*'] }\nconsole.log(request.headersDistinct);\n"
},
{
"textRaw": "Type: {string}",
"name": "httpVersion",
"type": "string",
"meta": {
"added": [
"v0.1.1"
],
"changes": []
},
"desc": "In case of server request, the HTTP version sent by the client. In the case of\nclient response, the HTTP version of the connected-to server.\nProbably either '1.1' or '1.0'.
Also message.httpVersionMajor is the first integer and\nmessage.httpVersionMinor is the second.
Only valid for request obtained from http.Server.
The request method as a string. Read only. Examples: 'GET', 'DELETE'.
The raw request/response headers list exactly as they were received.
\nThe keys and values are in the same list. It is not a\nlist of tuples. So, the even-numbered offsets are key values, and the\nodd-numbered offsets are the associated values.
\nHeader names are not lowercased, and duplicates are not merged.
\n// Prints something like:\n//\n// [ 'user-agent',\n// 'this is invalid because there can be only one',\n// 'User-Agent',\n// 'curl/7.22.0',\n// 'Host',\n// '127.0.0.1:8000',\n// 'ACCEPT',\n// '*/*' ]\nconsole.log(request.rawHeaders);\n"
},
{
"textRaw": "Type: {string[]}",
"name": "rawTrailers",
"type": "string[]",
"meta": {
"added": [
"v0.11.6"
],
"changes": []
},
"desc": "The raw request/response trailer keys and values exactly as they were\nreceived. Only populated at the 'end' event.
An AbortSignal that is aborted when the message is destroyed before\ncompletion or when its underlying socket closes before request handling or\nresponse reading completes.\nThe signal is created lazily on first access â no AbortController is allocated\nfor requests that never use this property.
This is useful for cancelling downstream asynchronous work such as database\nqueries or fetch calls when a client disconnects mid-request.
import http from 'node:http';\n\nhttp.createServer(async (req, res) => {\n try {\n const data = await fetch('https://example.com/api', { signal: req.signal });\n res.end(JSON.stringify(await data.json()));\n } catch (err) {\n if (err.name === 'AbortError') return;\n res.statusCode = 500;\n res.end('Internal Server Error');\n }\n}).listen(3000);\n\nconst http = require('node:http');\n\nhttp.createServer(async (req, res) => {\n try {\n const data = await fetch('https://example.com/api', { signal: req.signal });\n res.end(JSON.stringify(await data.json()));\n } catch (err) {\n if (err.name === 'AbortError') return;\n res.statusCode = 500;\n res.end('Internal Server Error');\n }\n}).listen(3000);\n"
},
{
"textRaw": "Type: {stream.Duplex}",
"name": "socket",
"type": "stream.Duplex",
"meta": {
"added": [
"v0.3.0"
],
"changes": []
},
"desc": "The net.Socket object associated with the connection.
With HTTPS support, use request.socket.getPeerCertificate() to obtain the\nclient's authentication details.
This property is guaranteed to be an instance of the net.Socket class,\na subclass of stream.Duplex, unless the user specified a socket\ntype other than net.Socket or internally nulled.
Only valid for response obtained from http.ClientRequest.
The 3-digit HTTP response status code. E.G. 404.
Only valid for response obtained from http.ClientRequest.
The HTTP response status message (reason phrase). E.G. OK or Internal Server Error.
The request/response trailers object. Only populated at the 'end' event.
Similar to message.trailers, but there is no join logic and the values are\nalways arrays of strings, even for headers received just once.\nOnly populated at the 'end' event.
Only valid for request obtained from http.Server.
Request URL string. This contains only the URL that is present in the actual\nHTTP request. Take the following request:
\nGET /status?name=ryan HTTP/1.1\nAccept: text/plain\n\nTo parse the URL into its parts:
\nnew URL(`http://${process.env.HOST ?? 'localhost'}${request.url}`);\n\nWhen request.url is '/status?name=ryan' and process.env.HOST is undefined:
$ node\n> new URL(`http://${process.env.HOST ?? 'localhost'}${request.url}`);\nURL {\n href: 'http://localhost/status?name=ryan',\n origin: 'http://localhost',\n protocol: 'http:',\n username: '',\n password: '',\n host: 'localhost',\n hostname: 'localhost',\n port: '',\n pathname: '/status',\n search: '?name=ryan',\n searchParams: URLSearchParams { 'name' => 'ryan' },\n hash: ''\n}\n\nEnsure that you set process.env.HOST to the server's host name, or consider\nreplacing this part entirely. If using req.headers.host, ensure proper\nvalidation is used, as clients may specify a custom Host header.
Calls destroy() on the socket that received the IncomingMessage. If error\nis provided, an 'error' event is emitted on the socket and error is passed\nas an argument to any listeners on the event.
Calls message.socket.setTimeout(msecs, callback).
StreamThis class serves as the parent class of http.ClientRequest\nand http.ServerResponse. It is an abstract outgoing message from\nthe perspective of the participants of an HTTP transaction.
Emitted when the buffer of the message is free again.
" }, { "textRaw": "Event: `'finish'`", "name": "finish", "type": "event", "meta": { "added": [ "v0.1.17" ], "changes": [] }, "params": [], "desc": "Emitted when the transmission is finished successfully.
" }, { "textRaw": "Event: `'prefinish'`", "name": "prefinish", "type": "event", "meta": { "added": [ "v0.11.6" ], "changes": [] }, "params": [], "desc": "Emitted after outgoingMessage.end() is called.\nWhen the event is emitted, all data has been processed but not necessarily\ncompletely flushed.
Adds HTTP trailers (headers but at the end of the message) to the message.
\nTrailers will only be emitted if the message is chunked encoded. If not,\nthe trailers will be silently discarded.
\nHTTP requires the Trailer header to be sent to emit trailers,\nwith a list of header field names in its value, e.g.
message.writeHead(200, { 'Content-Type': 'text/plain',\n 'Trailer': 'Content-MD5' });\nmessage.write(fileData);\nmessage.addTrailers({ 'Content-MD5': '7895bf4b8828b55ceaf47747b4bca667' });\nmessage.end();\n\nAttempting to set a header field name or value that contains invalid characters\nwill result in a TypeError being thrown.
Append a single header value to the header object.
\nIf the value is an array, this is equivalent to calling this method multiple\ntimes.
\nIf there were no previous values for the header, this is equivalent to calling\noutgoingMessage.setHeader(name, value).
Depending of the value of options.uniqueHeaders when the client request or the\nserver were created, this will end up in the header being sent multiple times or\na single time with values joined using ; .
See writable.cork().
Destroys the message. Once a socket is associated with the message\nand is connected, that socket will be destroyed as well.
" }, { "textRaw": "`outgoingMessage.end(chunk[, encoding][, callback])`", "name": "end", "type": "method", "meta": { "added": [ "v0.1.90" ], "changes": [ { "version": "v15.0.0", "pr-url": "https://github.com/nodejs/node/pull/33155", "description": "The `chunk` parameter can now be a `Uint8Array`." }, { "version": "v0.11.6", "description": "add `callback` argument." } ] }, "signatures": [ { "params": [ { "textRaw": "`chunk` {string | Buffer | Uint8Array}", "name": "chunk", "type": "string | Buffer | Uint8Array" }, { "textRaw": "`encoding` {string} Optional, **Default**: `utf8`", "name": "encoding", "type": "string", "desc": "Optional, **Default**: `utf8`", "optional": true }, { "textRaw": "`callback` {Function} Optional", "name": "callback", "type": "Function", "desc": "Optional", "optional": true } ], "return": { "textRaw": "Returns: {this}", "name": "return", "type": "this" } } ], "desc": "Finishes the outgoing message. If any parts of the body are unsent, it will\nflush them to the underlying system. If the message is chunked, it will\nsend the terminating chunk 0\\r\\n\\r\\n, and send the trailers (if any).
If chunk is specified, it is equivalent to calling\noutgoingMessage.write(chunk, encoding), followed by\noutgoingMessage.end(callback).
If callback is provided, it will be called when the message is finished\n(equivalent to a listener of the 'finish' event).
Flushes the message headers.
\nFor efficiency reason, Node.js normally buffers the message headers\nuntil outgoingMessage.end() is called or the first chunk of message data\nis written. It then tries to pack the headers and data into a single TCP\npacket.
It is usually desired (it saves a TCP round-trip), but not when the first\ndata is not sent until possibly much later. outgoingMessage.flushHeaders()\nbypasses the optimization and kickstarts the message.
Gets the value of the HTTP header with the given name. If that header is not\nset, the returned value will be undefined.
Returns an array containing the unique names of the current outgoing headers.\nAll names are lowercase.
" }, { "textRaw": "`outgoingMessage.getHeaders()`", "name": "getHeaders", "type": "method", "meta": { "added": [ "v7.7.0" ], "changes": [] }, "signatures": [ { "params": [], "return": { "textRaw": "Returns: {Object}", "name": "return", "type": "Object" } } ], "desc": "Returns a shallow copy of the current outgoing headers. Since a shallow\ncopy is used, array values may be mutated without additional calls to\nvarious header-related HTTP module methods. The keys of the returned\nobject are the header names and the values are the respective header\nvalues. All header names are lowercase.
\nThe object returned by the outgoingMessage.getHeaders() method does\nnot prototypically inherit from the JavaScript Object. This means that\ntypical Object methods such as obj.toString(), obj.hasOwnProperty(),\nand others are not defined and will not work.
outgoingMessage.setHeader('Foo', 'bar');\noutgoingMessage.setHeader('Set-Cookie', ['foo=bar', 'bar=baz']);\n\nconst headers = outgoingMessage.getHeaders();\n// headers === { foo: 'bar', 'set-cookie': ['foo=bar', 'bar=baz'] }\n"
},
{
"textRaw": "`outgoingMessage.hasHeader(name)`",
"name": "hasHeader",
"type": "method",
"meta": {
"added": [
"v7.7.0"
],
"changes": []
},
"signatures": [
{
"params": [
{
"textRaw": "`name` {string}",
"name": "name",
"type": "string"
}
],
"return": {
"textRaw": "Returns: {boolean}",
"name": "return",
"type": "boolean"
}
}
],
"desc": "Returns true if the header identified by name is currently set in the\noutgoing headers. The header name is case-insensitive.
const hasContentType = outgoingMessage.hasHeader('content-type');\n"
},
{
"textRaw": "`outgoingMessage.pipe()`",
"name": "pipe",
"type": "method",
"meta": {
"added": [
"v9.0.0"
],
"changes": []
},
"signatures": [
{
"params": []
}
],
"desc": "Overrides the stream.pipe() method inherited from the legacy Stream class\nwhich is the parent class of http.OutgoingMessage.
Calling this method will throw an Error because outgoingMessage is a\nwrite-only stream.
Removes a header that is queued for implicit sending.
\noutgoingMessage.removeHeader('Content-Encoding');\n"
},
{
"textRaw": "`outgoingMessage.setHeader(name, value)`",
"name": "setHeader",
"type": "method",
"meta": {
"added": [
"v0.4.0"
],
"changes": []
},
"signatures": [
{
"params": [
{
"textRaw": "`name` {string} Header name",
"name": "name",
"type": "string",
"desc": "Header name"
},
{
"textRaw": "`value` {number | string | string[]} Header value",
"name": "value",
"type": "number | string | string[]",
"desc": "Header value"
}
],
"return": {
"textRaw": "Returns: {this}",
"name": "return",
"type": "this"
}
}
],
"desc": "Sets a single header value. If the header already exists in the to-be-sent\nheaders, its value will be replaced. Use an array of strings to send multiple\nheaders with the same name.
" }, { "textRaw": "`outgoingMessage.setHeaders(headers)`", "name": "setHeaders", "type": "method", "meta": { "added": [ "v19.6.0", "v18.15.0" ], "changes": [] }, "signatures": [ { "params": [ { "textRaw": "`headers` {Headers | Map}", "name": "headers", "type": "Headers | Map" } ], "return": { "textRaw": "Returns: {this}", "name": "return", "type": "this" } } ], "desc": "Sets multiple header values for implicit headers.\nheaders must be an instance of Headers or Map,\nif a header already exists in the to-be-sent headers,\nits value will be replaced.
const headers = new Headers({ foo: 'bar' });\noutgoingMessage.setHeaders(headers);\n\nor
\nconst headers = new Map([['foo', 'bar']]);\noutgoingMessage.setHeaders(headers);\n\nWhen headers have been set with outgoingMessage.setHeaders(),\nthey will be merged with any headers passed to response.writeHead(),\nwith the headers passed to response.writeHead() given precedence.
// Returns content-type = text/plain\nconst server = http.createServer((req, res) => {\n const headers = new Headers({ 'Content-Type': 'text/html' });\n res.setHeaders(headers);\n res.writeHead(200, { 'Content-Type': 'text/plain' });\n res.end('ok');\n});\n"
},
{
"textRaw": "`outgoingMessage.setTimeout(msecs[, callback])`",
"name": "setTimeout",
"type": "method",
"meta": {
"added": [
"v0.9.12"
],
"changes": []
},
"signatures": [
{
"params": [
{
"textRaw": "`msecs` {number}",
"name": "msecs",
"type": "number"
},
{
"textRaw": "`callback` {Function} Optional function to be called when a timeout occurs. Same as binding to the `timeout` event.",
"name": "callback",
"type": "Function",
"desc": "Optional function to be called when a timeout occurs. Same as binding to the `timeout` event.",
"optional": true
}
],
"return": {
"textRaw": "Returns: {this}",
"name": "return",
"type": "this"
}
}
],
"desc": "Once a socket is associated with the message and is connected,\nsocket.setTimeout() will be called with msecs as the first parameter.
Sends a chunk of the body. This method can be called multiple times.
\nThe encoding argument is only relevant when chunk is a string. Defaults to\n'utf8'.
The callback argument is optional and will be called when this chunk of data\nis flushed.
Returns true if the entire data was flushed successfully to the kernel\nbuffer. Returns false if all or part of the data was queued in the user\nmemory. The 'drain' event will be emitted when the buffer is free again.
Alias of outgoingMessage.socket.
Read-only. true if the headers were sent, otherwise false.
Reference to the underlying socket. Usually, users will not want to access\nthis property.
\nAfter calling outgoingMessage.end(), this property will be nulled.
The number of times outgoingMessage.cork() has been called.
Is true if outgoingMessage.end() has been called. This property does\nnot indicate whether the data has been flushed. For that purpose, use\nmessage.writableFinished instead.
Is true if all data has been flushed to the underlying system.
The highWaterMark of the underlying socket if assigned. Otherwise, the default\nbuffer level when writable.write() starts returning false (16384).
The number of buffered bytes.
" }, { "textRaw": "Type: {boolean}", "name": "writableObjectMode", "type": "boolean", "meta": { "added": [ "v12.9.0" ], "changes": [] }, "desc": "Always false.
A browser-compatible implementation of WebSocket.
A list of the HTTP methods that are supported by the parser.
" }, { "textRaw": "Type: {Object}", "name": "STATUS_CODES", "type": "Object", "meta": { "added": [ "v0.1.22" ], "changes": [] }, "desc": "A collection of all the standard HTTP response status codes, and the\nshort description of each. For example, http.STATUS_CODES[404] === 'Not Found'.
Global instance of Agent which is used as the default for all HTTP client\nrequests. Diverges from a default Agent configuration by having keepAlive\nenabled and a timeout of 5 seconds.
Read-only property specifying the maximum allowed size of HTTP headers in bytes.\nDefaults to 16 KiB. Configurable using the --max-http-header-size CLI\noption.
This can be overridden for servers and client requests by passing the\nmaxHeaderSize option.
Returns a new instance of http.Server.
The requestListener is a function which is automatically\nadded to the 'request' event.
import http from 'node:http';\n\n// Create a local server to receive data from\nconst server = http.createServer((req, res) => {\n res.writeHead(200, { 'Content-Type': 'application/json' });\n res.end(JSON.stringify({\n data: 'Hello World!',\n }));\n});\n\nserver.listen(8000);\n\nconst http = require('node:http');\n\n// Create a local server to receive data from\nconst server = http.createServer((req, res) => {\n res.writeHead(200, { 'Content-Type': 'application/json' });\n res.end(JSON.stringify({\n data: 'Hello World!',\n }));\n});\n\nserver.listen(8000);\n\nimport http from 'node:http';\n\n// Create a local server to receive data from\nconst server = http.createServer();\n\n// Listen to the request event\nserver.on('request', (request, res) => {\n res.writeHead(200, { 'Content-Type': 'application/json' });\n res.end(JSON.stringify({\n data: 'Hello World!',\n }));\n});\n\nserver.listen(8000);\n\nconst http = require('node:http');\n\n// Create a local server to receive data from\nconst server = http.createServer();\n\n// Listen to the request event\nserver.on('request', (request, res) => {\n res.writeHead(200, { 'Content-Type': 'application/json' });\n res.end(JSON.stringify({\n data: 'Hello World!',\n }));\n});\n\nserver.listen(8000);\n"
},
{
"textRaw": "`http.get(options[, callback])`",
"name": "get",
"type": "method",
"signatures": [
{
"params": [
{
"name": "options"
},
{
"name": "callback",
"optional": true
}
]
}
]
},
{
"textRaw": "`http.get(url[, options][, callback])`",
"name": "get",
"type": "method",
"meta": {
"added": [
"v0.3.6"
],
"changes": [
{
"version": "v10.9.0",
"pr-url": "https://github.com/nodejs/node/pull/21616",
"description": "The `url` parameter can now be passed along with a separate `options` object."
},
{
"version": "v7.5.0",
"pr-url": "https://github.com/nodejs/node/pull/10638",
"description": "The `options` parameter can be a WHATWG `URL` object."
}
]
},
"signatures": [
{
"params": [
{
"textRaw": "`url` {string | URL}",
"name": "url",
"type": "string | URL"
},
{
"textRaw": "`options` {Object} Accepts the same `options` as `http.request()`, with the method set to GET by default.",
"name": "options",
"type": "Object",
"desc": "Accepts the same `options` as `http.request()`, with the method set to GET by default.",
"optional": true
},
{
"textRaw": "`callback` {Function}",
"name": "callback",
"type": "Function",
"optional": true
}
],
"return": {
"textRaw": "Returns: {http.ClientRequest}",
"name": "return",
"type": "http.ClientRequest"
}
}
],
"desc": "Since most requests are GET requests without bodies, Node.js provides this\nconvenience method. The only difference between this method and\nhttp.request() is that it sets the method to GET by default and calls req.end()\nautomatically. The callback must take care to consume the response\ndata for reasons stated in http.ClientRequest section.
The callback is invoked with a single argument that is an instance of\nhttp.IncomingMessage.
JSON fetching example:
\nhttp.get('http://localhost:8000/', (res) => {\n const { statusCode } = res;\n const contentType = res.headers['content-type'];\n\n let error;\n // Any 2xx status code signals a successful response but\n // here we're only checking for 200.\n if (statusCode !== 200) {\n error = new Error('Request Failed.\\n' +\n `Status Code: ${statusCode}`);\n } else if (!/^application\\/json/.test(contentType)) {\n error = new Error('Invalid content-type.\\n' +\n `Expected application/json but received ${contentType}`);\n }\n if (error) {\n console.error(error.message);\n // Consume response data to free up memory\n res.resume();\n return;\n }\n\n res.setEncoding('utf8');\n let rawData = '';\n res.on('data', (chunk) => { rawData += chunk; });\n res.on('end', () => {\n try {\n const parsedData = JSON.parse(rawData);\n console.log(parsedData);\n } catch (e) {\n console.error(e.message);\n }\n });\n}).on('error', (e) => {\n console.error(`Got error: ${e.message}`);\n});\n\n// Create a local server to receive data from\nconst server = http.createServer((req, res) => {\n res.writeHead(200, { 'Content-Type': 'application/json' });\n res.end(JSON.stringify({\n data: 'Hello World!',\n }));\n});\n\nserver.listen(8000);\n"
},
{
"textRaw": "`http.request(options[, callback])`",
"name": "request",
"type": "method",
"signatures": [
{
"params": [
{
"name": "options"
},
{
"name": "callback",
"optional": true
}
]
}
]
},
{
"textRaw": "`http.request(url[, options][, callback])`",
"name": "request",
"type": "method",
"meta": {
"added": [
"v0.3.6"
],
"changes": [
{
"version": "v26.3.0",
"pr-url": "https://github.com/nodejs/node/pull/61597",
"description": "The `httpValidation` option is supported now."
},
{
"version": [
"v16.7.0",
"v14.18.0"
],
"pr-url": "https://github.com/nodejs/node/pull/39310",
"description": "When using a `URL` object parsed username and password will now be properly URI decoded."
},
{
"version": [
"v15.3.0",
"v14.17.0"
],
"pr-url": "https://github.com/nodejs/node/pull/36048",
"description": "It is possible to abort a request with an AbortSignal."
},
{
"version": [
"v13.8.0",
"v12.15.0",
"v10.19.0"
],
"pr-url": "https://github.com/nodejs/node/pull/31448",
"description": "The `insecureHTTPParser` option is supported now."
},
{
"version": "v13.3.0",
"pr-url": "https://github.com/nodejs/node/pull/30570",
"description": "The `maxHeaderSize` option is supported now."
},
{
"version": "v10.9.0",
"pr-url": "https://github.com/nodejs/node/pull/21616",
"description": "The `url` parameter can now be passed along with a separate `options` object."
},
{
"version": "v7.5.0",
"pr-url": "https://github.com/nodejs/node/pull/10638",
"description": "The `options` parameter can be a WHATWG `URL` object."
}
]
},
"signatures": [
{
"params": [
{
"textRaw": "`url` {string | URL}",
"name": "url",
"type": "string | URL"
},
{
"textRaw": "`options` {Object}",
"name": "options",
"type": "Object",
"options": [
{
"textRaw": "`agent` {http.Agent | boolean} Controls `Agent` behavior. Possible values:",
"name": "agent",
"type": "http.Agent | boolean",
"desc": "Controls `Agent` behavior. Possible values:",
"options": [
{
"textRaw": "`undefined` (default): use `http.globalAgent` for this host and port.",
"name": "undefined",
"desc": "(default): use `http.globalAgent` for this host and port."
},
{
"textRaw": "`Agent` object: explicitly use the passed in `Agent`.",
"name": "Agent",
"desc": "object: explicitly use the passed in `Agent`."
},
{
"textRaw": "`false`: causes a new `Agent` with default values to be used.",
"name": "false",
"desc": "causes a new `Agent` with default values to be used."
}
]
},
{
"textRaw": "`auth` {string} Basic authentication (`'user:password'`) to compute an Authorization header.",
"name": "auth",
"type": "string",
"desc": "Basic authentication (`'user:password'`) to compute an Authorization header."
},
{
"textRaw": "`createConnection` {Function} A function that produces a socket/stream to use for the request when the `agent` option is not used. This can be used to avoid creating a custom `Agent` class just to override the default `createConnection` function. See `agent.createConnection()` for more details. Any `Duplex` stream is a valid return value.",
"name": "createConnection",
"type": "Function",
"desc": "A function that produces a socket/stream to use for the request when the `agent` option is not used. This can be used to avoid creating a custom `Agent` class just to override the default `createConnection` function. See `agent.createConnection()` for more details. Any `Duplex` stream is a valid return value."
},
{
"textRaw": "`defaultPort` {number} Default port for the protocol. **Default:** `agent.defaultPort` if an `Agent` is used, else `undefined`.",
"name": "defaultPort",
"type": "number",
"default": "`agent.defaultPort` if an `Agent` is used, else `undefined`",
"desc": "Default port for the protocol."
},
{
"textRaw": "`family` {number} IP address family to use when resolving `host` or `hostname`. Valid values are `4` or `6`. When unspecified, both IP v4 and v6 will be used.",
"name": "family",
"type": "number",
"desc": "IP address family to use when resolving `host` or `hostname`. Valid values are `4` or `6`. When unspecified, both IP v4 and v6 will be used."
},
{
"textRaw": "`headers` {Object | Array} An object or an array of strings containing request headers. The array is in the same format as `message.rawHeaders`.",
"name": "headers",
"type": "Object | Array",
"desc": "An object or an array of strings containing request headers. The array is in the same format as `message.rawHeaders`."
},
{
"textRaw": "`hints` {number} Optional `dns.lookup()` hints.",
"name": "hints",
"type": "number",
"desc": "Optional `dns.lookup()` hints."
},
{
"textRaw": "`host` {string} A domain name or IP address of the server to issue the request to. **Default:** `'localhost'`.",
"name": "host",
"type": "string",
"default": "`'localhost'`",
"desc": "A domain name or IP address of the server to issue the request to."
},
{
"textRaw": "`hostname` {string} Alias for `host`. To support `url.parse()`, `hostname` will be used if both `host` and `hostname` are specified.",
"name": "hostname",
"type": "string",
"desc": "Alias for `host`. To support `url.parse()`, `hostname` will be used if both `host` and `hostname` are specified."
},
{
"textRaw": "`httpValidation` {string} Controls HTTP header value validation strictness for outgoing requests. Accepted values are:",
"name": "httpValidation",
"type": "string",
"desc": "Controls HTTP header value validation strictness for outgoing requests. Accepted values are:",
"options": [
{
"textRaw": "`'strict'`: Strictest validation; rejects any non-ASCII or control characters in header values.",
"desc": "`'strict'`: Strictest validation; rejects any non-ASCII or control characters in header values."
},
{
"textRaw": "`'relaxed'`: Allows a limited set of non-ASCII characters in header values, aligning with the Fetch specification.",
"desc": "`'relaxed'`: Allows a limited set of non-ASCII characters in header values, aligning with the Fetch specification."
},
{
"textRaw": "`'insecure'`: Disables all header value validation (equivalent to `insecureHTTPParser: true`). Cannot be used together with `insecureHTTPParser`. **Default:** `'strict'`.",
"default": "`'strict'`",
"desc": "`'insecure'`: Disables all header value validation (equivalent to `insecureHTTPParser: true`). Cannot be used together with `insecureHTTPParser`."
}
]
},
{
"textRaw": "`insecureHTTPParser` {boolean} If set to `true`, it will use an HTTP parser with leniency flags enabled. Using the insecure parser should be avoided. See `--insecure-http-parser` for more information. **Default:** `false`",
"name": "insecureHTTPParser",
"type": "boolean",
"default": "`false`",
"desc": "If set to `true`, it will use an HTTP parser with leniency flags enabled. Using the insecure parser should be avoided. See `--insecure-http-parser` for more information."
},
{
"textRaw": "`joinDuplicateHeaders` {boolean} It joins the field line values of multiple headers in a request with `, ` instead of discarding the duplicates. See `message.headers` for more information. **Default:** `false`.",
"name": "joinDuplicateHeaders",
"type": "boolean",
"default": "`false`",
"desc": "It joins the field line values of multiple headers in a request with `, ` instead of discarding the duplicates. See `message.headers` for more information."
},
{
"textRaw": "`localAddress` {string} Local interface to bind for network connections.",
"name": "localAddress",
"type": "string",
"desc": "Local interface to bind for network connections."
},
{
"textRaw": "`localPort` {number} Local port to connect from.",
"name": "localPort",
"type": "number",
"desc": "Local port to connect from."
},
{
"textRaw": "`lookup` {Function} Custom lookup function. **Default:** `dns.lookup()`.",
"name": "lookup",
"type": "Function",
"default": "`dns.lookup()`",
"desc": "Custom lookup function."
},
{
"textRaw": "`maxHeaderSize` {number} Optionally overrides the value of `--max-http-header-size` (the maximum length of response headers in bytes) for responses received from the server. **Default:** 16384 (16 KiB).",
"name": "maxHeaderSize",
"type": "number",
"default": "16384 (16 KiB)",
"desc": "Optionally overrides the value of `--max-http-header-size` (the maximum length of response headers in bytes) for responses received from the server."
},
{
"textRaw": "`method` {string} A string specifying the HTTP request method. **Default:** `'GET'`.",
"name": "method",
"type": "string",
"default": "`'GET'`",
"desc": "A string specifying the HTTP request method."
},
{
"textRaw": "`path` {string} Request path. Should include query string if any. E.G. `'/index.html?page=12'`. An exception is thrown when the request path contains illegal characters. Currently, only spaces are rejected but that may change in the future. **Default:** `'/'`. The content in `path` is sent as the request target in the HTTP 1.1 message. When `path` is an absolute URL, this means the request target in the message in absolute form. If the receiving server is a proxy, the server typically forwards the request to the destination specified in the request target, and ignores the `Host` header. The user needs to make sure that `path`, `host` and the Host headers conform to the requirement of the request target in the HTTP specification. When the receiving server is known to be a proxy because the request is routed through Built-in Proxy Support, `http.request` will additionally perform a best-effort check to see that the `host` option or `Host` in `headers` agrees with the authority in `path` during the initial construction of the request. It gives up rewriting the request target for proxying and throws an error if they don't match at request construction time, though there won't be checks for later header mutations done by the user.",
"name": "path",
"type": "string",
"default": "`'/'`. The content in `path` is sent as the request target in the HTTP 1.1 message. When `path` is an absolute URL, this means the request target in the message in absolute form. If the receiving server is a proxy, the server typically forwards the request to the destination specified in the request target, and ignores the `Host` header. The user needs to make sure that `path`, `host` and the Host headers conform to the requirement of the request target in the HTTP specification. When the receiving server is known to be a proxy because the request is routed through Built-in Proxy Support, `http.request` will additionally perform a best-effort check to see that the `host` option or `Host` in `headers` agrees with the authority in `path` during the initial construction of the request. It gives up rewriting the request target for proxying and throws an error if they don't match at request construction time, though there won't be checks for later header mutations done by the user",
"desc": "Request path. Should include query string if any. E.G. `'/index.html?page=12'`. An exception is thrown when the request path contains illegal characters. Currently, only spaces are rejected but that may change in the future."
},
{
"textRaw": "`port` {number} Port of remote server. **Default:** `defaultPort` if set, else `80`.",
"name": "port",
"type": "number",
"default": "`defaultPort` if set, else `80`",
"desc": "Port of remote server."
},
{
"textRaw": "`protocol` {string} Protocol to use. **Default:** `'http:'`.",
"name": "protocol",
"type": "string",
"default": "`'http:'`",
"desc": "Protocol to use."
},
{
"textRaw": "`setDefaultHeaders` {boolean}: Specifies whether or not to automatically add default headers such as `Connection`, `Content-Length`, `Transfer-Encoding`, and `Host`. If set to `false` then all necessary headers must be added manually. Defaults to `true`.",
"name": "setDefaultHeaders",
"type": "boolean",
"desc": ": Specifies whether or not to automatically add default headers such as `Connection`, `Content-Length`, `Transfer-Encoding`, and `Host`. If set to `false` then all necessary headers must be added manually. Defaults to `true`."
},
{
"textRaw": "`setHost` {boolean}: Specifies whether or not to automatically add the `Host` header. If provided, this overrides `setDefaultHeaders`. Defaults to `true`.",
"name": "setHost",
"type": "boolean",
"desc": ": Specifies whether or not to automatically add the `Host` header. If provided, this overrides `setDefaultHeaders`. Defaults to `true`."
},
{
"textRaw": "`signal` {AbortSignal}: An AbortSignal that may be used to abort an ongoing request.",
"name": "signal",
"type": "AbortSignal",
"desc": ": An AbortSignal that may be used to abort an ongoing request."
},
{
"textRaw": "`socketPath` {string} Unix domain socket. Cannot be used if one of `host` or `port` is specified, as those specify a TCP Socket.",
"name": "socketPath",
"type": "string",
"desc": "Unix domain socket. Cannot be used if one of `host` or `port` is specified, as those specify a TCP Socket."
},
{
"textRaw": "`timeout` {number}: A number specifying the socket timeout in milliseconds. This will set the timeout before the socket is connected.",
"name": "timeout",
"type": "number",
"desc": ": A number specifying the socket timeout in milliseconds. This will set the timeout before the socket is connected."
},
{
"textRaw": "`uniqueHeaders` {Array} A list of request headers that should be sent only once. If the header's value is an array, the items will be joined using `; `.",
"name": "uniqueHeaders",
"type": "Array",
"desc": "A list of request headers that should be sent only once. If the header's value is an array, the items will be joined using `; `."
}
],
"optional": true
},
{
"textRaw": "`callback` {Function}",
"name": "callback",
"type": "Function",
"optional": true
}
],
"return": {
"textRaw": "Returns: {http.ClientRequest}",
"name": "return",
"type": "http.ClientRequest"
}
}
],
"desc": "options in socket.connect() are also supported.
Node.js maintains several connections per server to make HTTP requests.\nThis function allows one to transparently issue requests.
\nurl can be a string or a URL object. If url is a\nstring, it is automatically parsed with new URL(). If it is a URL\nobject, it will be automatically converted to an ordinary options object.
If both url and options are specified, the objects are merged, with the\noptions properties taking precedence.
The optional callback parameter will be added as a one-time listener for\nthe 'response' event.
http.request() returns an instance of the http.ClientRequest\nclass. The ClientRequest instance is a writable stream. If one needs to\nupload a file with a POST request, then write to the ClientRequest object.
import http from 'node:http';\nimport { Buffer } from 'node:buffer';\n\nconst postData = JSON.stringify({\n 'msg': 'Hello World!',\n});\n\nconst options = {\n hostname: 'www.google.com',\n port: 80,\n path: '/upload',\n method: 'POST',\n headers: {\n 'Content-Type': 'application/json',\n 'Content-Length': Buffer.byteLength(postData),\n },\n};\n\nconst req = http.request(options, (res) => {\n console.log(`STATUS: ${res.statusCode}`);\n console.log(`HEADERS: ${JSON.stringify(res.headers)}`);\n res.setEncoding('utf8');\n res.on('data', (chunk) => {\n console.log(`BODY: ${chunk}`);\n });\n res.on('end', () => {\n console.log('No more data in response.');\n });\n});\n\nreq.on('error', (e) => {\n console.error(`problem with request: ${e.message}`);\n});\n\n// Write data to request body\nreq.write(postData);\nreq.end();\n\nconst http = require('node:http');\n\nconst postData = JSON.stringify({\n 'msg': 'Hello World!',\n});\n\nconst options = {\n hostname: 'www.google.com',\n port: 80,\n path: '/upload',\n method: 'POST',\n headers: {\n 'Content-Type': 'application/json',\n 'Content-Length': Buffer.byteLength(postData),\n },\n};\n\nconst req = http.request(options, (res) => {\n console.log(`STATUS: ${res.statusCode}`);\n console.log(`HEADERS: ${JSON.stringify(res.headers)}`);\n res.setEncoding('utf8');\n res.on('data', (chunk) => {\n console.log(`BODY: ${chunk}`);\n });\n res.on('end', () => {\n console.log('No more data in response.');\n });\n});\n\nreq.on('error', (e) => {\n console.error(`problem with request: ${e.message}`);\n});\n\n// Write data to request body\nreq.write(postData);\nreq.end();\n\nIn the example req.end() was called. With http.request() one\nmust always call req.end() to signify the end of the request -\neven if there is no data being written to the request body.
If any error is encountered during the request (be that with DNS resolution,\nTCP level errors, or actual HTTP parse errors) an 'error' event is emitted\non the returned request object. As with all 'error' events, if no listeners\nare registered the error will be thrown.
There are a few special headers that should be noted.
\nSending a 'Connection: keep-alive' will notify Node.js that the connection to\nthe server should be persisted until the next request.
\nSending a 'Content-Length' header will disable the default chunked encoding.
\nSending an 'Expect' header will immediately send the request headers.\nUsually, when sending 'Expect: 100-continue', both a timeout and a listener\nfor the 'continue' event should be set. See RFC 2616 Section 8.2.3 for more\ninformation.
Sending an Authorization header will override using the auth option\nto compute basic authentication.
Example using a URL as options:
const options = new URL('http://abc:[email protected]');\n\nconst req = http.request(options, (res) => {\n // ...\n});\n\nIn a successful request, the following events will be emitted in the following\norder:
\n'socket''response'\n'data' any number of times, on the res object\n('data' will not be emitted at all if the response body is empty, for\ninstance, in most redirects)'end' on the res object'close'In the case of a connection error, the following events will be emitted:
\n'socket''error''close'In the case of a premature connection close before the response is received,\nthe following events will be emitted in the following order:
\n'socket''error' with an error with message 'Error: socket hang up' and code\n'ECONNRESET''close'In the case of a premature connection close after the response is received,\nthe following events will be emitted in the following order:
\n'socket''response'\n'data' any number of times, on the res object'aborted' on the res object'close''error' on the res object with an error with message\n'Error: aborted' and code 'ECONNRESET''close' on the res objectIf req.destroy() is called before a socket is assigned, the following\nevents will be emitted in the following order:
req.destroy() called here)'error' with an error with message 'Error: socket hang up' and code\n'ECONNRESET', or the error with which req.destroy() was called'close'If req.destroy() is called before the connection succeeds, the following\nevents will be emitted in the following order:
'socket'req.destroy() called here)'error' with an error with message 'Error: socket hang up' and code\n'ECONNRESET', or the error with which req.destroy() was called'close'If req.destroy() is called after the response is received, the following\nevents will be emitted in the following order:
'socket''response'\n'data' any number of times, on the res objectreq.destroy() called here)'aborted' on the res object'close''error' on the res object with an error with message 'Error: aborted'\nand code 'ECONNRESET', or the error with which req.destroy() was called'close' on the res objectIf req.abort() is called before a socket is assigned, the following\nevents will be emitted in the following order:
req.abort() called here)'abort''close'If req.abort() is called before the connection succeeds, the following\nevents will be emitted in the following order:
'socket'req.abort() called here)'abort''error' with an error with message 'Error: socket hang up' and code\n'ECONNRESET''close'If req.abort() is called after the response is received, the following\nevents will be emitted in the following order:
'socket''response'\n'data' any number of times, on the res objectreq.abort() called here)'abort''aborted' on the res object'error' on the res object with an error with message\n'Error: aborted' and code 'ECONNRESET'.'close''close' on the res objectSetting the timeout option or using the setTimeout() function will\nnot abort the request or do anything besides add a 'timeout' event.
Passing an AbortSignal and then calling abort() on the corresponding\nAbortController will behave the same way as calling .destroy() on the\nrequest. Specifically, the 'error' event will be emitted with an error with\nthe message 'AbortError: The operation was aborted', the code 'ABORT_ERR'\nand the cause, if one was provided.
Performs the low-level validations on the provided name that are done when\nres.setHeader(name, value) is called.
Passing illegal value as name will result in a TypeError being thrown,\nidentified by code: 'ERR_INVALID_HTTP_TOKEN'.
It is not necessary to use this method before passing headers to an HTTP request\nor response. The HTTP module will automatically validate such headers.
\nExample:
\nimport { validateHeaderName } from 'node:http';\n\ntry {\n validateHeaderName('');\n} catch (err) {\n console.error(err instanceof TypeError); // --> true\n console.error(err.code); // --> 'ERR_INVALID_HTTP_TOKEN'\n console.error(err.message); // --> 'Header name must be a valid HTTP token [\"\"]'\n}\n\nconst { validateHeaderName } = require('node:http');\n\ntry {\n validateHeaderName('');\n} catch (err) {\n console.error(err instanceof TypeError); // --> true\n console.error(err.code); // --> 'ERR_INVALID_HTTP_TOKEN'\n console.error(err.message); // --> 'Header name must be a valid HTTP token [\"\"]'\n}\n"
},
{
"textRaw": "`http.validateHeaderValue(name, value)`",
"name": "validateHeaderValue",
"type": "method",
"meta": {
"added": [
"v14.3.0"
],
"changes": []
},
"signatures": [
{
"params": [
{
"textRaw": "`name` {string}",
"name": "name",
"type": "string"
},
{
"textRaw": "`value` {any}",
"name": "value",
"type": "any"
}
]
}
],
"desc": "Performs the low-level validations on the provided value that are done when\nres.setHeader(name, value) is called.
Passing illegal value as value will result in a TypeError being thrown.
code: 'ERR_HTTP_INVALID_HEADER_VALUE'.code: 'ERR_INVALID_CHAR'.It is not necessary to use this method before passing headers to an HTTP request\nor response. The HTTP module will automatically validate such headers.
\nExamples:
\nimport { validateHeaderValue } from 'node:http';\n\ntry {\n validateHeaderValue('x-my-header', undefined);\n} catch (err) {\n console.error(err instanceof TypeError); // --> true\n console.error(err.code === 'ERR_HTTP_INVALID_HEADER_VALUE'); // --> true\n console.error(err.message); // --> 'Invalid value \"undefined\" for header \"x-my-header\"'\n}\n\ntry {\n validateHeaderValue('x-my-header', 'oÊmɪɡÉ');\n} catch (err) {\n console.error(err instanceof TypeError); // --> true\n console.error(err.code === 'ERR_INVALID_CHAR'); // --> true\n console.error(err.message); // --> 'Invalid character in header content [\"x-my-header\"]'\n}\n\nconst { validateHeaderValue } = require('node:http');\n\ntry {\n validateHeaderValue('x-my-header', undefined);\n} catch (err) {\n console.error(err instanceof TypeError); // --> true\n console.error(err.code === 'ERR_HTTP_INVALID_HEADER_VALUE'); // --> true\n console.error(err.message); // --> 'Invalid value \"undefined\" for header \"x-my-header\"'\n}\n\ntry {\n validateHeaderValue('x-my-header', 'oÊmɪɡÉ');\n} catch (err) {\n console.error(err instanceof TypeError); // --> true\n console.error(err.code === 'ERR_INVALID_CHAR'); // --> true\n console.error(err.message); // --> 'Invalid character in header content [\"x-my-header\"]'\n}\n"
},
{
"textRaw": "`http.setMaxIdleHTTPParsers(max)`",
"name": "setMaxIdleHTTPParsers",
"type": "method",
"meta": {
"added": [
"v18.8.0",
"v16.18.0"
],
"changes": []
},
"signatures": [
{
"params": [
{
"textRaw": "`max` {number} **Default:** `1000`.",
"name": "max",
"type": "number",
"default": "`1000`"
}
]
}
],
"desc": "Set the maximum number of idle HTTP parsers.
" }, { "textRaw": "`http.setGlobalProxyFromEnv([proxyEnv])`", "name": "setGlobalProxyFromEnv", "type": "method", "meta": { "added": [ "v25.4.0", "v24.14.0" ], "changes": [] }, "signatures": [ { "params": [ { "textRaw": "`proxyEnv` {Object} An object containing proxy configuration. This accepts the same options as the `proxyEnv` option accepted by `Agent`. **Default:** `process.env`.", "name": "proxyEnv", "type": "Object", "default": "`process.env`", "desc": "An object containing proxy configuration. This accepts the same options as the `proxyEnv` option accepted by `Agent`.", "optional": true } ], "return": { "textRaw": "Returns: {Function} A function that restores the original agent and dispatcher settings to the state before this `http.setGlobalProxyFromEnv()` is invoked.", "name": "return", "type": "Function", "desc": "A function that restores the original agent and dispatcher settings to the state before this `http.setGlobalProxyFromEnv()` is invoked." } } ], "desc": "Dynamically resets the global configurations to enable built-in proxy support for\nfetch() and http.request()/https.request() at runtime, as an alternative\nto using the --use-env-proxy flag or NODE_USE_ENV_PROXY environment variable.\nIt can also be used to override settings configured from the environment variables.
As this function resets the global configurations, any previously configured\nhttp.globalAgent, https.globalAgent or undici global dispatcher would be\noverridden after this function is invoked. It's recommended to invoke it before any\nrequests are made and avoid invoking it in the middle of any requests.
See Built-in Proxy Support for details on proxy URL formats and NO_PROXY\nsyntax.
When Node.js creates the global agent, if the NODE_USE_ENV_PROXY environment variable is\nset to 1 or --use-env-proxy is enabled, the global agent will be constructed\nwith proxyEnv: process.env, enabling proxy support based on the environment variables.
To enable proxy support dynamically and globally, use http.setGlobalProxyFromEnv().
Custom agents can also be created with proxy support by passing a\nproxyEnv option when constructing the agent. The value can be process.env\nif they just want to inherit the configuration from the environment variables,\nor an object with specific setting overriding the environment.
The following properties of the proxyEnv are checked to configure proxy\nsupport.
HTTP_PROXY or http_proxy: Proxy server URL for HTTP requests. If both are set,\nhttp_proxy takes precedence.HTTPS_PROXY or https_proxy: Proxy server URL for HTTPS requests. If both are set,\nhttps_proxy takes precedence.NO_PROXY or no_proxy: Comma-separated list of hosts to bypass the proxy. If both are set,\nno_proxy takes precedence.If the request is made to a Unix domain socket, the proxy settings will be ignored.
", "modules": [ { "textRaw": "Proxy security considerations", "name": "proxy_security_considerations", "type": "module", "desc": "Built-in proxy support routes outbound requests through an HTTP(S) proxy, often\nbecause a firewall requires one to access external networks. It is not an\nanonymity or traffic-hiding feature and does not attempt to hide traffic from\nthe proxy, the local network, network operators, or authorities that govern the\ndeployment.
\nConfigure only proxies that are trusted and authorized for the deployment. A\nproxy can observe connection metadata; for plain HTTP requests, or when TLS is\nterminated or intercepted by the proxy, it can also observe request and response\ncontents. Node.js does not support treating an untrusted proxy as a privacy\nboundary. Deployment operators are responsible for controlling proxy\nconfiguration and for meeting deployment-specific network policy and legal\nrequirements.
", "displayName": "Proxy security considerations" }, { "textRaw": "Proxy URL Format", "name": "proxy_url_format", "type": "module", "desc": "Proxy URLs can use either HTTP or HTTPS protocols:
\nhttp://proxy.example.com:8080https://proxy.example.com:8080http://username:[email protected]:8080The NO_PROXY environment variable supports several formats:
* - Bypass proxy for all hostsexample.com - Exact host name match.example.com - Domain suffix match (matches sub.example.com)*.example.com - Wildcard domain match192.168.1.100 - Exact IP address match192.168.1.1-192.168.1.100 - IP address rangeexample.com:8080 - Hostname with specific portMultiple entries should be separated by commas.
", "displayName": "`NO_PROXY` Format" }, { "textRaw": "Example", "name": "example", "type": "module", "desc": "To start a Node.js process with proxy support enabled for all requests sent\nthrough the default global agent, either use the NODE_USE_ENV_PROXY environment\nvariable:
NODE_USE_ENV_PROXY=1 HTTP_PROXY=http://proxy.example.com:8080 NO_PROXY=localhost,127.0.0.1 node client.js\n\nOr the --use-env-proxy flag.
HTTP_PROXY=http://proxy.example.com:8080 NO_PROXY=localhost,127.0.0.1 node --use-env-proxy client.js\n\nTo enable proxy support dynamically and globally with process.env (the default option of http.setGlobalProxyFromEnv()):
const http = require('node:http');\n\n// Reads proxy-related environment variables from process.env\nconst restore = http.setGlobalProxyFromEnv();\n\n// Subsequent requests will use the configured proxies from environment variables\nhttp.get('http://www.example.com', (res) => {\n // This request will be proxied if HTTP_PROXY or http_proxy is set\n});\n\nfetch('https://www.example.com', (res) => {\n // This request will be proxied if HTTPS_PROXY or https_proxy is set\n});\n\n// To restore the original global agent and dispatcher settings, call the returned function.\n// restore();\n\nimport http from 'node:http';\n\n// Reads proxy-related environment variables from process.env\nhttp.setGlobalProxyFromEnv();\n\n// Subsequent requests will use the configured proxies from environment variables\nhttp.get('http://www.example.com', (res) => {\n // This request will be proxied if HTTP_PROXY or http_proxy is set\n});\n\nfetch('https://www.example.com', (res) => {\n // This request will be proxied if HTTPS_PROXY or https_proxy is set\n});\n\n// To restore the original global agent and dispatcher settings, call the returned function.\n// restore();\n\nTo enable proxy support dynamically and globally with custom settings:
\nconst http = require('node:http');\n\nconst restore = http.setGlobalProxyFromEnv({\n http_proxy: 'http://proxy.example.com:8080',\n https_proxy: 'https://proxy.example.com:8443',\n no_proxy: 'localhost,127.0.0.1,.internal.example.com',\n});\n\n// Subsequent requests will use the configured proxies\nhttp.get('http://www.example.com', (res) => {\n // This request will be proxied through proxy.example.com:8080\n});\n\nfetch('https://www.example.com', (res) => {\n // This request will be proxied through proxy.example.com:8443\n});\n\nimport http from 'node:http';\n\nhttp.setGlobalProxyFromEnv({\n http_proxy: 'http://proxy.example.com:8080',\n https_proxy: 'https://proxy.example.com:8443',\n no_proxy: 'localhost,127.0.0.1,.internal.example.com',\n});\n\n// Subsequent requests will use the configured proxies\nhttp.get('http://www.example.com', (res) => {\n // This request will be proxied through proxy.example.com:8080\n});\n\nfetch('https://www.example.com', (res) => {\n // This request will be proxied through proxy.example.com:8443\n});\n\nTo create a custom agent with built-in proxy support:
\nconst http = require('node:http');\n\n// Creating a custom agent with custom proxy support.\nconst agent = new http.Agent({ proxyEnv: { HTTP_PROXY: 'http://proxy.example.com:8080' } });\n\nhttp.request({\n hostname: 'www.example.com',\n port: 80,\n path: '/',\n agent,\n}, (res) => {\n // This request will be proxied through proxy.example.com:8080 using the HTTP protocol.\n console.log(`STATUS: ${res.statusCode}`);\n});\n\nAlternatively, the following also works:
\nconst http = require('node:http');\n// Use lower-cased option name.\nconst agent1 = new http.Agent({ proxyEnv: { http_proxy: 'http://proxy.example.com:8080' } });\n// Use values inherited from the environment variables, if the process is started with\n// HTTP_PROXY=http://proxy.example.com:8080 this will use the proxy server specified\n// in process.env.HTTP_PROXY.\nconst agent2 = new http.Agent({ proxyEnv: process.env });\n",
"displayName": "Example"
}
],
"displayName": "Built-in Proxy Support"
}
],
"displayName": "HTTP"
}
]
}