http
To use the HTTP server and client one must import the node:http module.
The HTTP interfaces in Node.js are designed to support many features of the protocol which have been traditionally difficult to use. In particular, large, possibly chunk-encoded, messages. The interface is careful to never buffer entire requests or responses, so the user is able to stream data.
HTTP message headers are represented by an object like this:
{ "content-length": "123",
"content-type": "text/plain",
"connection": "keep-alive",
"host": "example.com",
"accept": "*" }
Keys are lowercased. Values are not modified.
In order to support the full spectrum of possible HTTP applications, the Node.js HTTP API is very low-level. It deals with stream handling and message parsing only. It parses a message into headers and body but it does not parse the actual headers or the body.
See message.headers for details on how duplicate headers are handled.
The raw headers as they were received are retained in the rawHeaders property, which is an array of [key, value, key2, value2, ...]. For
example, the previous message header object might have a rawHeaders list like the following:
[ 'ConTent-Length', '123456',
'content-LENGTH', '123',
'content-type', 'text/plain',
'CONNECTION', 'keep-alive',
'Host', 'example.com',
'accepT', '*' ]
Usage in Deno
import * as mod from "node:http";
Classes
An Agent is responsible for managing connection persistence
and reuse for HTTP clients. It maintains a queue of pending requests
for a given host and port, reusing a single socket connection for each
until the queue is empty, at which time the socket is either destroyed
or put into a pool where it is kept to be used again for requests to the
same host and port. Whether it is destroyed or pooled depends on the keepAlive option.
An IncomingMessage object is created by Server or ClientRequest and passed as the first argument to the 'request' and 'response' event respectively. It may be used to
access response
status, headers, and data.
This class serves as the parent class of ClientRequest and ServerResponse. It is an abstract outgoing message from the perspective of the participants of an HTTP transaction.
This object is created internally by an HTTP server, not by the user. It is
passed as the second parameter to the 'request' event.
Functions
Performs the low-level validations on the provided name that are done when res.setHeader(name, value) is called.
Performs the low-level validations on the provided value that are done when res.setHeader(name, value) is called.
Interfaces
- accept
- accept-language
- accept-patch
- accept-ranges
- access-control-allow-credentials
- access-control-allow-headers
- access-control-allow-methods
- access-control-allow-origin
- access-control-expose-headers
- access-control-max-age
- access-control-request-headers
- access-control-request-method
- age
- allow
- alt-svc
- authorization
- cache-control
- connection
- content-disposition
- content-encoding
- content-language
- content-length
- content-location
- content-range
- content-type
- cookie
- date
- etag
- expect
- expires
- forwarded
- from
- host
- if-match
- if-modified-since
- if-none-match
- if-unmodified-since
- last-modified
- location
- origin
- pragma
- proxy-authenticate
- proxy-authorization
- public-key-pins
- range
- referer
- retry-after
- sec-websocket-accept
- sec-websocket-extensions
- sec-websocket-key
- sec-websocket-protocol
- sec-websocket-version
- set-cookie
- strict-transport-security
- tk
- trailer
- transfer-encoding
- upgrade
- user-agent
- vary
- via
- warning
- www-authenticate
- accept
- accept-charset
- accept-encoding
- accept-language
- accept-ranges
- access-control-allow-credentials
- access-control-allow-headers
- access-control-allow-methods
- access-control-allow-origin
- access-control-expose-headers
- access-control-max-age
- access-control-request-headers
- access-control-request-method
- age
- allow
- authorization
- cache-control
- cdn-cache-control
- connection
- content-disposition
- content-encoding
- content-language
- content-length
- content-location
- content-range
- content-security-policy
- content-security-policy-report-only
- content-type
- cookie
- date
- dav
- dnt
- etag
- expect
- expires
- forwarded
- from
- host
- if-match
- if-modified-since
- if-none-match
- if-range
- if-unmodified-since
- last-modified
- link
- location
- max-forwards
- origin
- pragma
- proxy-authenticate
- proxy-authorization
- public-key-pins
- public-key-pins-report-only
- range
- referer
- referrer-policy
- refresh
- retry-after
- sec-websocket-accept
- sec-websocket-extensions
- sec-websocket-key
- sec-websocket-protocol
- sec-websocket-version
- server
- set-cookie
- strict-transport-security
- te
- trailer
- transfer-encoding
- upgrade
- upgrade-insecure-requests
- user-agent
- vary
- via
- warning
- www-authenticate
- x-content-type-options
- x-dns-prefetch-control
- x-frame-options
- x-xss-protection
Type Aliases
Variables
Global instance of Agent which is used as the default for all HTTP client
requests. Diverges from a default Agent configuration by having keepAlive
enabled and a timeout of 5 seconds.
Read-only property specifying the maximum allowed size of HTTP headers in bytes.
Defaults to 16KB. Configurable using the --max-http-header-size CLI option.
class Agent
Usage in Deno
import { Agent } from "node:http";
An Agent is responsible for managing connection persistence
and reuse for HTTP clients. It maintains a queue of pending requests
for a given host and port, reusing a single socket connection for each
until the queue is empty, at which time the socket is either destroyed
or put into a pool where it is kept to be used again for requests to the
same host and port. Whether it is destroyed or pooled depends on the keepAlive option.
Pooled connections have TCP Keep-Alive enabled for them, but servers may
still close idle connections, in which case they will be removed from the
pool and a new connection will be made when a new HTTP request is made for
that host and port. Servers may also refuse to allow multiple requests
over the same connection, in which case the connection will have to be
remade for every request and cannot be pooled. The Agent will still make
the requests to that server, but each one will occur over a new connection.
When a connection is closed by the client or the server, it is removed
from the pool. Any unused sockets in the pool will be unrefed so as not
to keep the Node.js process running when there are no outstanding requests.
(see socket.unref()).
It is good practice, to destroy() an Agent instance when it is no
longer in use, because unused sockets consume OS resources.
Sockets are removed from an agent when the socket emits either
a 'close' event or an 'agentRemove' event. When intending to keep one
HTTP request open for a long time without keeping it in the agent, something
like the following may be done:
http.get(options, (res) => {
// Do stuff
}).on('socket', (socket) => {
socket.emit('agentRemove');
});
An agent may also be used for an individual request. By providing {agent: false} as an option to the http.get() or http.request() functions, a one-time use Agent with default options
will be used
for the client connection.
agent:false:
http.get({
hostname: 'localhost',
port: 80,
path: '/',
agent: false, // Create a new agent just for this one request
}, (res) => {
// Do stuff with response
});
options in socket.connect() are also supported.
To configure any of them, a custom Agent instance must be created.
import http from 'node:http';
const keepAliveAgent = new http.Agent({ keepAlive: true });
options.agent = keepAliveAgent;
http.request(options, onResponseCallback)
Constructors #
#Agent(opts?: AgentOptions) Properties #
#freeSockets: ReadOnlyDict<Socket[]> An object which contains arrays of sockets currently awaiting use by
the agent when keepAlive is enabled. Do not modify.
Sockets in the freeSockets list will be automatically destroyed and
removed from the array on 'timeout'.
#maxFreeSockets: number By default set to 256. For agents with keepAlive enabled, this
sets the maximum number of sockets that will be left open in the free
state.
#maxSockets: number By default set to Infinity. Determines how many concurrent sockets the agent
can have open per origin. Origin is the returned value of agent.getName().
#maxTotalSockets: number By default set to Infinity. Determines how many concurrent sockets the agent
can have open. Unlike maxSockets, this parameter applies across all origins.
#requests: ReadOnlyDict<IncomingMessage[]> An object which contains queues of requests that have not yet been assigned to sockets. Do not modify.
Methods #
Destroy any sockets that are currently in use by the agent.
It is usually not necessary to do this. However, if using an
agent with keepAlive enabled, then it is best to explicitly shut down
the agent when it is no longer needed. Otherwise,
sockets might stay open for quite a long time before the server
terminates them.
class ClientRequest
Usage in Deno
import { ClientRequest } from "node:http";
Constructor option createConnection is not supported.
This object is created internally and returned from request. It
represents an in-progress request whose header has already been queued. The
header is still mutable using the setHeader(name, value), getHeader(name), removeHeader(name) API. The actual header will
be sent along with the first data chunk or when calling request.end().
To get the response, add a listener for 'response' to the request object. 'response' will be emitted from the request object when the response
headers have been received. The 'response' event is executed with one
argument which is an instance of IncomingMessage.
During the 'response' event, one can add listeners to the
response object; particularly to listen for the 'data' event.
If no 'response' handler is added, then the response will be
entirely discarded. However, if a 'response' event handler is added,
then the data from the response object must be consumed, either by
calling response.read() whenever there is a 'readable' event, or
by adding a 'data' handler, or by calling the .resume() method.
Until the data is consumed, the 'end' event will not fire. Also, until
the data is read it will consume memory that can eventually lead to a
'process out of memory' error.
For backward compatibility, res will only emit 'error' if there is an 'error' listener registered.
Set Content-Length header to limit the response body size.
If response.strictContentLength is set to true, mismatching the Content-Length header value will result in an Error being thrown,
identified by code:``'ERR_HTTP_CONTENT_LENGTH_MISMATCH'.
Content-Length value should be in bytes, not characters. Use Buffer.byteLength() to determine the length of the body in bytes.
Constructors #
#ClientRequest(url: ,cb?: (res: IncomingMessage) => void,) Properties #
The request.aborted property will be true if the request has
been aborted.
#maxHeadersCount: number Limits maximum response headers count. If set to 0, no limit will be applied.
#reusedSocket: boolean When sending request through a keep-alive enabled agent, the underlying socket might be reused. But if server closes connection at unfortunate time, client may run into a 'ECONNRESET' error.
import http from 'node:http';
// Server has a 5 seconds keep-alive timeout by default
http
.createServer((req, res) => {
res.write('hello\n');
res.end();
})
.listen(3000);
setInterval(() => {
// Adapting a keep-alive agent
http.get('http://localhost:3000', { agent }, (res) => {
res.on('data', (data) => {
// Do nothing
});
});
}, 5000); // Sending request on 5s interval so it's easy to hit idle timeout
By marking a request whether it reused socket or not, we can do automatic error retry base on it.
import http from 'node:http';
const agent = new http.Agent({ keepAlive: true });
function retriableRequest() {
const req = http
.get('http://localhost:3000', { agent }, (res) => {
// ...
})
.on('error', (err) => {
// Check if retry is needed
if (req.reusedSocket && err.code === 'ECONNRESET') {
retriableRequest();
}
});
}
retriableRequest();
Methods #
Marks the request as aborting. Calling this will cause remaining data in the response to be dropped and the socket to be destroyed.
#addListener(event: "abort",listener: () => void,): this #addListener(event: "connect",listener: () => void,): this #addListener(event: "continue",listener: () => void,): this #addListener(event: "information",listener: (info: InformationEvent) => void,): this #addListener(event: "response",listener: (response: IncomingMessage) => void,): this #addListener(event: "socket",listener: (socket: Socket) => void,): this #addListener(event: "timeout",listener: () => void,): this #addListener(event: "upgrade",listener: () => void,): this #addListener(event: "close",listener: () => void,): this #addListener(event: "drain",listener: () => void,): this #addListener(event: "error",listener: (err: Error) => void,): this #addListener(event: "finish",listener: () => void,): this #addListener(event: "pipe",listener: (src: stream.Readable) => void,): this #addListener(event: "unpipe",listener: (src: stream.Readable) => void,): this #addListener(event: string | symbol,listener: (...args: any[]) => void,): this #getRawHeaderNames(): string[] Returns an array containing the unique names of the current outgoing raw headers. Header names are returned with their exact casing being set.
request.setHeader('Foo', 'bar');
request.setHeader('Set-Cookie', ['foo=bar', 'bar=baz']);
const headerNames = request.getRawHeaderNames();
// headerNames === ['Foo', 'Set-Cookie']
#on(event: "information",listener: (info: InformationEvent) => void,): this #on(event: "response",listener: (response: IncomingMessage) => void,): this #once(event: "information",listener: (info: InformationEvent) => void,): this #once(event: "response",listener: (response: IncomingMessage) => void,): this #prependListener(event: "abort",listener: () => void,): this #prependListener(event: "connect",listener: () => void,): this #prependListener(event: "continue",listener: () => void,): this #prependListener(event: "information",listener: (info: InformationEvent) => void,): this #prependListener(event: "response",listener: (response: IncomingMessage) => void,): this #prependListener(event: "socket",listener: (socket: Socket) => void,): this #prependListener(event: "timeout",listener: () => void,): this #prependListener(event: "upgrade",listener: () => void,): this #prependListener(event: "close",listener: () => void,): this #prependListener(event: "drain",listener: () => void,): this #prependListener(event: "error",listener: (err: Error) => void,): this #prependListener(event: "finish",listener: () => void,): this #prependListener(event: "pipe",listener: (src: stream.Readable) => void,): this #prependListener(event: "unpipe",listener: (src: stream.Readable) => void,): this #prependListener(event: string | symbol,listener: (...args: any[]) => void,): this #prependOnceListener(event: "abort",listener: () => void,): this #prependOnceListener(event: "connect",listener: () => void,): this #prependOnceListener(event: "continue",listener: () => void,): this #prependOnceListener(event: "information",listener: (info: InformationEvent) => void,): this #prependOnceListener(event: "response",listener: (response: IncomingMessage) => void,): this #prependOnceListener(event: "socket",listener: (socket: Socket) => void,): this #prependOnceListener(event: "timeout",listener: () => void,): this #prependOnceListener(event: "upgrade",listener: () => void,): this #prependOnceListener(event: "close",listener: () => void,): this #prependOnceListener(event: "drain",listener: () => void,): this #prependOnceListener(event: "error",listener: (err: Error) => void,): this #prependOnceListener(event: "finish",listener: () => void,): this #prependOnceListener(event: "pipe",listener: (src: stream.Readable) => void,): this #prependOnceListener(event: "unpipe",listener: (src: stream.Readable) => void,): this #prependOnceListener(event: string | symbol,listener: (...args: any[]) => void,): this #setNoDelay(noDelay?: boolean): void Once a socket is assigned to this request and is connected socket.setNoDelay() will be called.
#setSocketKeepAlive(enable?: boolean,initialDelay?: number,): void Once a socket is assigned to this request and is connected socket.setKeepAlive() will be called.
#setTimeout(timeout: number,callback?: () => void,): this Once a socket is assigned to this request and is connected socket.setTimeout() will be called.
class IncomingMessage
Usage in Deno
import { IncomingMessage } from "node:http";
An IncomingMessage object is created by Server or ClientRequest and passed as the first argument to the 'request' and 'response' event respectively. It may be used to
access response
status, headers, and data.
Different from its socket value which is a subclass of stream.Duplex, the IncomingMessage itself extends stream.Readable and is created separately to
parse and emit the incoming HTTP headers and payload, as the underlying socket
may be reused multiple times in case of keep-alive.
Constructors #
Properties #
The message.aborted property will be true if the request has
been aborted.
The message.complete property will be true if a complete HTTP message has
been received and successfully parsed.
This property is particularly useful as a means of determining if a client or server fully transmitted a message before a connection was terminated:
const req = http.request({
host: '127.0.0.1',
port: 8080,
method: 'POST',
}, (res) => {
res.resume();
res.on('end', () => {
if (!res.complete)
console.error(
'The connection was terminated while the message was still being sent');
});
});
#connection: Socket Alias for message.socket.
The request/response headers object.
Key-value pairs of header names and values. Header names are lower-cased.
// Prints something like:
//
// { 'user-agent': 'curl/7.22.0',
// host: '127.0.0.1:8000',
// accept: '*' }
console.log(request.headers);
Duplicates in raw headers are handled in the following ways, depending on the header name:
- Duplicates of
age,authorization,content-length,content-type,etag,expires,from,host,if-modified-since,if-unmodified-since,last-modified,location,max-forwards,proxy-authorization,referer,retry-after,server, oruser-agentare discarded. To allow duplicate values of the headers listed above to be joined, use the optionjoinDuplicateHeadersin request and createServer. See RFC 9110 Section 5.3 for more information. set-cookieis always an array. Duplicates are added to the array.- For duplicate
cookieheaders, the values are joined together with;. - For all other headers, the values are joined together with
,.
#headersDistinct: Dict<string[]> Similar to message.headers, but there is no join logic and the values are
always arrays of strings, even for headers received just once.
// Prints something like:
//
// { 'user-agent': ['curl/7.22.0'],
// host: ['127.0.0.1:8000'],
// accept: ['*'] }
console.log(request.headersDistinct);
#httpVersion: string In case of server request, the HTTP version sent by the client. In the case of
client response, the HTTP version of the connected-to server.
Probably either '1.1' or '1.0'.
Also message.httpVersionMajor is the first integer and message.httpVersionMinor is the second.
#httpVersionMajor: number #httpVersionMinor: number Only valid for request obtained from Server.
The request method as a string. Read only. Examples: 'GET', 'DELETE'.
#rawHeaders: string[] The raw request/response headers list exactly as they were received.
The keys and values are in the same list. It is not a list of tuples. So, the even-numbered offsets are key values, and the odd-numbered offsets are the associated values.
Header names are not lowercased, and duplicates are not merged.
// Prints something like:
//
// [ 'user-agent',
// 'this is invalid because there can be only one',
// 'User-Agent',
// 'curl/7.22.0',
// 'Host',
// '127.0.0.1:8000',
// 'ACCEPT',
// '*' ]
console.log(request.rawHeaders);
#rawTrailers: string[] The raw request/response trailer keys and values exactly as they were
received. Only populated at the 'end' event.
The net.Socket object associated with the connection.
With HTTPS support, use request.socket.getPeerCertificate() to obtain the
client's authentication details.
This property is guaranteed to be an instance of the net.Socket class,
a subclass of stream.Duplex, unless the user specified a socket
type other than net.Socket or internally nulled.
#statusCode: number | undefined Only valid for response obtained from ClientRequest.
The 3-digit HTTP response status code. E.G. 404.
#statusMessage: string | undefined Only valid for response obtained from ClientRequest.
The HTTP response status message (reason phrase). E.G. OK or Internal Server Error.
#trailersDistinct: Dict<string[]> Similar to message.trailers, but there is no join logic and the values are
always arrays of strings, even for headers received just once.
Only populated at the 'end' event.
Only valid for request obtained from Server.
Request URL string. This contains only the URL that is present in the actual HTTP request. Take the following request:
GET /status?name=ryan HTTP/1.1
Accept: text/plain
To parse the URL into its parts:
new URL(`http://${process.env.HOST ?? 'localhost'}${request.url}`);
When request.url is '/status?name=ryan' and process.env.HOST is undefined:
$ node
> new URL(`http://${process.env.HOST ?? 'localhost'}${request.url}`);
URL {
href: 'http://localhost/status?name=ryan',
origin: 'http://localhost',
protocol: 'http:',
username: '',
password: '',
host: 'localhost',
hostname: 'localhost',
port: '',
pathname: '/status',
search: '?name=ryan',
searchParams: URLSearchParams { 'name' => 'ryan' },
hash: ''
}
Ensure that you set process.env.HOST to the server's host name, or consider replacing this part entirely. If using req.headers.host, ensure proper
validation is used, as clients may specify a custom Host header.
Methods #
Calls destroy() on the socket that received the IncomingMessage. If error is provided, an 'error' event is emitted on the socket and error is passed
as an argument to any listeners on the event.
#setTimeout(msecs: number,callback?: () => void,): this Calls message.socket.setTimeout(msecs, callback).
class OutgoingMessage
Usage in Deno
import { OutgoingMessage } from "node:http";
This class serves as the parent class of ClientRequest and ServerResponse. It is an abstract outgoing message from the perspective of the participants of an HTTP transaction.
Constructors #
#OutgoingMessage() Type Parameters #
#Request extends IncomingMessage = IncomingMessage Properties #
#chunkedEncoding: boolean #connection: Socket | null Alias of outgoingMessage.socket.
#headersSent: boolean Read-only. true if the headers were sent, otherwise false.
#shouldKeepAlive: boolean Reference to the underlying socket. Usually, users will not want to access this property.
After calling outgoingMessage.end(), this property will be nulled.
#useChunkedEncodingByDefault: boolean Methods #
#addTrailers(headers: OutgoingHttpHeaders | ReadonlyArray<[string, string]>): void Adds HTTP trailers (headers but at the end of the message) to the message.
Trailers will only be emitted if the message is chunked encoded. If not, the trailers will be silently discarded.
HTTP requires the Trailer header to be sent to emit trailers,
with a list of header field names in its value, e.g.
message.writeHead(200, { 'Content-Type': 'text/plain',
'Trailer': 'Content-MD5' });
message.write(fileData);
message.addTrailers({ 'Content-MD5': '7895bf4b8828b55ceaf47747b4bca667' });
message.end();
Attempting to set a header field name or value that contains invalid characters
will result in a TypeError being thrown.
#appendHeader(name: string,value: string | readonly string[],): this Append a single header value to the header object.
If the value is an array, this is equivalent to calling this method multiple times.
If there were no previous values for the header, this is equivalent to calling outgoingMessage.setHeader(name, value).
Depending of the value of options.uniqueHeaders when the client request or the
server were created, this will end up in the header being sent multiple times or
a single time with values joined using ; .
#flushHeaders(): void Flushes the message headers.
For efficiency reason, Node.js normally buffers the message headers
until outgoingMessage.end() is called or the first chunk of message data
is written. It then tries to pack the headers and data into a single TCP
packet.
It is usually desired (it saves a TCP round-trip), but not when the first
data is not sent until possibly much later. outgoingMessage.flushHeaders() bypasses the optimization and kickstarts the message.
Gets the value of the HTTP header with the given name. If that header is not
set, the returned value will be undefined.
#getHeaderNames(): string[] Returns an array containing the unique names of the current outgoing headers. All names are lowercase.
Returns a shallow copy of the current outgoing headers. Since a shallow copy is used, array values may be mutated without additional calls to various header-related HTTP module methods. The keys of the returned object are the header names and the values are the respective header values. All header names are lowercase.
The object returned by the outgoingMessage.getHeaders() method does
not prototypically inherit from the JavaScript Object. This means that
typical Object methods such as obj.toString(), obj.hasOwnProperty(),
and others are not defined and will not work.
outgoingMessage.setHeader('Foo', 'bar');
outgoingMessage.setHeader('Set-Cookie', ['foo=bar', 'bar=baz']);
const headers = outgoingMessage.getHeaders();
// headers === { foo: 'bar', 'set-cookie': ['foo=bar', 'bar=baz'] }
Returns true if the header identified by name is currently set in the
outgoing headers. The header name is case-insensitive.
const hasContentType = outgoingMessage.hasHeader('content-type');
#removeHeader(name: string): void Removes a header that is queued for implicit sending.
outgoingMessage.removeHeader('Content-Encoding');
Sets a single header value. If the header already exists in the to-be-sent headers, its value will be replaced. Use an array of strings to send multiple headers with the same name.
#setHeaders(headers: Headers | Map<string, number
| string
| readonly string[]>): this Sets multiple header values for implicit headers. headers must be an instance of
Headers or Map, if a header already exists in the to-be-sent headers, its
value will be replaced.
const headers = new Headers({ foo: 'bar' });
outgoingMessage.setHeaders(headers);
or
const headers = new Map([['foo', 'bar']]);
outgoingMessage.setHeaders(headers);
When headers have been set with outgoingMessage.setHeaders(), they will be
merged with any headers passed to response.writeHead(), with the headers passed
to response.writeHead() given precedence.
// Returns content-type = text/plain
const server = http.createServer((req, res) => {
const headers = new Headers({ 'Content-Type': 'text/html' });
res.setHeaders(headers);
res.writeHead(200, { 'Content-Type': 'text/plain' });
res.end('ok');
});
#setTimeout(msecs: number,callback?: () => void,): this Once a socket is associated with the message and is connected, socket.setTimeout() will be called with msecs as the first parameter.
class Server
Usage in Deno
import { Server } from "node:http";
Constructors #
#Server(requestListener?: RequestListener<Request, Response>) #Server(options: ServerOptions<Request, Response>,requestListener?: RequestListener<Request, Response>,) Type Parameters #
#Request extends IncomingMessage = IncomingMessage #Response extends ServerResponse = ServerResponse Properties #
#headersTimeout: number Limit the amount of time the parser will wait to receive the complete HTTP headers.
If the timeout expires, the server responds with status 408 without forwarding the request to the request listener and then closes the connection.
It must be set to a non-zero value (e.g. 120 seconds) to protect against potential Denial-of-Service attacks in case the server is deployed without a reverse proxy in front.
#keepAliveTimeout: number The number of milliseconds of inactivity a server needs to wait for additional
incoming data, after it has finished writing the last response, before a socket
will be destroyed. If the server receives new data before the keep-alive
timeout has fired, it will reset the regular inactivity timeout, i.e., server.timeout.
A value of 0 will disable the keep-alive timeout behavior on incoming
connections.
A value of 0 makes the http server behave similarly to Node.js versions prior
to 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 affects new connections to the server, not any existing connections.
#maxHeadersCount: number | null Limits maximum incoming headers count. If set to 0, no limit will be applied.
#maxRequestsPerSocket: number | null The maximum number of requests socket can handle before closing keep alive connection.
A value of 0 will disable the limit.
When the limit is reached it will set the Connection header value to close,
but will not actually close the connection, subsequent requests sent
after the limit is reached will get 503 Service Unavailable as a response.
#requestTimeout: number Sets the timeout value in milliseconds for receiving the entire request from the client.
If the timeout expires, the server responds with status 408 without forwarding the request to the request listener and then closes the connection.
It must be set to a non-zero value (e.g. 120 seconds) to protect against potential Denial-of-Service attacks in case the server is deployed without a reverse proxy in front.
The number of milliseconds of inactivity before a socket is presumed to have timed out.
A value of 0 will disable the timeout behavior on incoming connections.
The socket timeout logic is set up on connection, so changing this value only affects new connections to the server, not any existing connections.
Methods #
#addListener(event: string,listener: (...args: any[]) => void,): this #addListener(event: "close",listener: () => void,): this #addListener(event: "connection",listener: (socket: Socket) => void,): this #addListener(event: "error",listener: (err: Error) => void,): this #addListener(event: "listening",listener: () => void,): this #addListener(event: "checkContinue",listener: RequestListener<Request, Response>,): this #addListener(event: "checkExpectation",listener: RequestListener<Request, Response>,): this #addListener(event: "clientError",listener: (err: Error,socket: stream.Duplex,) => void,): this #addListener(event: "connect",listener: () => void,): this #addListener(event: "dropRequest",listener: (req: InstanceType<Request>,socket: stream.Duplex,) => void,): this #addListener(event: "request",listener: RequestListener<Request, Response>,): this #addListener(event: "upgrade",listener: () => void,): this #closeAllConnections(): void Closes all connections connected to this server.
#closeIdleConnections(): void Closes all connections connected to this server which are not sending a request or waiting for a response.
#on(event: "checkContinue",listener: RequestListener<Request, Response>,): this #on(event: "checkExpectation",listener: RequestListener<Request, Response>,): this #on(event: "request",listener: RequestListener<Request, Response>,): this #once(event: "checkContinue",listener: RequestListener<Request, Response>,): this #once(event: "checkExpectation",listener: RequestListener<Request, Response>,): this #once(event: "request",listener: RequestListener<Request, Response>,): this #prependListener(event: string,listener: (...args: any[]) => void,): this #prependListener(event: "close",listener: () => void,): this #prependListener(event: "connection",listener: (socket: Socket) => void,): this #prependListener(event: "error",listener: (err: Error) => void,): this #prependListener(event: "listening",listener: () => void,): this #prependListener(event: "checkContinue",listener: RequestListener<Request, Response>,): this #prependListener(event: "checkExpectation",listener: RequestListener<Request, Response>,): this #prependListener(event: "clientError",listener: (err: Error,socket: stream.Duplex,) => void,): this #prependListener(event: "connect",listener: () => void,): this #prependListener(event: "dropRequest",listener: (req: InstanceType<Request>,socket: stream.Duplex,) => void,): this #prependListener(event: "request",listener: RequestListener<Request, Response>,): this #prependListener(event: "upgrade",listener: () => void,): this #prependOnceListener(event: string,listener: (...args: any[]) => void,): this #prependOnceListener(event: "close",listener: () => void,): this #prependOnceListener(event: "connection",listener: (socket: Socket) => void,): this #prependOnceListener(event: "error",listener: (err: Error) => void,): this #prependOnceListener(event: "listening",listener: () => void,): this #prependOnceListener(event: "checkContinue",listener: RequestListener<Request, Response>,): this #prependOnceListener(event: "checkExpectation",listener: RequestListener<Request, Response>,): this #prependOnceListener(event: "clientError",listener: (err: Error,socket: stream.Duplex,) => void,): this #prependOnceListener(event: "connect",listener: () => void,): this #prependOnceListener(event: "dropRequest",listener: (req: InstanceType<Request>,socket: stream.Duplex,) => void,): this #prependOnceListener(event: "request",listener: RequestListener<Request, Response>,): this #prependOnceListener(event: "upgrade",listener: () => void,): this #setTimeout(msecs?: number,callback?: (socket: Socket) => void,): this Sets the timeout value for sockets, and emits a 'timeout' event on
the Server object, passing the socket as an argument, if a timeout
occurs.
If there is a 'timeout' event listener on the Server object, then it
will be called with the timed-out socket as an argument.
By default, the Server does not timeout sockets. However, if a callback
is assigned to the Server's 'timeout' event, timeouts must be handled
explicitly.
#setTimeout(callback: (socket: Socket) => void): this class ServerResponse
Usage in Deno
import { ServerResponse } from "node:http";
This object is created internally by an HTTP server, not by the user. It is
passed as the second parameter to the 'request' event.
Constructors #
Type Parameters #
#Request extends IncomingMessage = IncomingMessage Properties #
#statusCode: number When using implicit headers (not calling response.writeHead() explicitly),
this property controls the status code that will be sent to the client when
the headers get flushed.
response.statusCode = 404;
After response header was sent to the client, this property indicates the status code which was sent out.
#statusMessage: string When using implicit headers (not calling response.writeHead() explicitly),
this property controls the status message that will be sent to the client when
the headers get flushed. If this is left as undefined then the standard
message for the status code will be used.
response.statusMessage = 'Not found';
After response header was sent to the client, this property indicates the status message which was sent out.
#strictContentLength: boolean If set to true, Node.js will check whether the Content-Length header value and the size of the body, in bytes, are equal.
Mismatching the Content-Length header value will result
in an Error being thrown, identified by code:``'ERR_HTTP_CONTENT_LENGTH_MISMATCH'.
Methods #
#assignSocket(socket: Socket): void #detachSocket(socket: Socket): void #writeContinue(callback?: () => void): void Sends an HTTP/1.1 100 Continue message to the client, indicating that
the request body should be sent. See the 'checkContinue' event on Server.
#writeEarlyHints(hints: Record<string, string | string[]>,callback?: () => void,): void Sends an HTTP/1.1 103 Early Hints message to the client with a Link header,
indicating that the user agent can preload/preconnect the linked resources.
The hints is an object containing the values of headers to be sent with
early hints message. The optional callback argument will be called when
the response message has been written.
Example
const earlyHintsLink = '</styles.css>; rel=preload; as=style';
response.writeEarlyHints({
'link': earlyHintsLink,
});
const earlyHintsLinks = [
'</styles.css>; rel=preload; as=style',
'</scripts.js>; rel=preload; as=script',
];
response.writeEarlyHints({
'link': earlyHintsLinks,
'x-trace-id': 'id for diagnostics',
});
const earlyHintsCallback = () => console.log('early hints message sent');
response.writeEarlyHints({
'link': earlyHintsLinks,
}, earlyHintsCallback);
Sends a response header to the request. The status code is a 3-digit HTTP
status code, like 404. The last argument, headers, are the response headers.
Optionally one can give a human-readable statusMessage as the second
argument.
headers may be an Array where the keys and values are in the same list.
It is not a list of tuples. So, the even-numbered offsets are key values,
and the odd-numbered offsets are the associated values. The array is in the same
format as request.rawHeaders.
Returns a reference to the ServerResponse, so that calls can be chained.
const body = 'hello world';
response
.writeHead(200, {
'Content-Length': Buffer.byteLength(body),
'Content-Type': 'text/plain',
})
.end(body);
This method must only be called once on a message and it must
be called before response.end() is called.
If response.write() or response.end() are called before calling
this, the implicit/mutable headers will be calculated and call this function.
When headers have been set with response.setHeader(), they will be merged
with any headers passed to response.writeHead(), with the headers passed
to response.writeHead() given precedence.
If this method is called and response.setHeader() has not been called,
it will directly write the supplied header values onto the network channel
without caching internally, and the response.getHeader() on the header
will not yield the expected result. If progressive population of headers is
desired with potential future retrieval and modification, use response.setHeader() instead.
// Returns content-type = text/plain
const server = http.createServer((req, res) => {
res.setHeader('Content-Type', 'text/html');
res.setHeader('X-Foo', 'bar');
res.writeHead(200, { 'Content-Type': 'text/plain' });
res.end('ok');
});
Content-Length is read in bytes, not characters. Use Buffer.byteLength() to determine the length of the body in bytes. Node.js
will check whether Content-Length and the length of the body which has
been transmitted are equal or not.
Attempting to set a header field name or value that contains invalid characters
will result in a [Error][] being thrown.
#writeHead(statusCode: number,headers?: OutgoingHttpHeaders | OutgoingHttpHeader[],): this #writeProcessing(): void Sends a HTTP/1.1 102 Processing message to the client, indicating that the request body should be sent.
function createServer
Usage in Deno
import { createServer } from "node:http";
Overload 1
#createServer<Request extends IncomingMessage = IncomingMessage,Response extends ServerResponse = ServerResponse,>(requestListener?: RequestListener<Request, Response>): Server<Request, Response>Returns a new instance of Server.
The requestListener is a function which is automatically
added to the 'request' event.
import http from 'node:http';
// Create a local server to receive data from
const server = http.createServer((req, res) => {
res.writeHead(200, { 'Content-Type': 'application/json' });
res.end(JSON.stringify({
data: 'Hello World!',
}));
});
server.listen(8000);
import http from 'node:http';
// Create a local server to receive data from
const server = http.createServer();
// Listen to the request event
server.on('request', (request, res) => {
res.writeHead(200, { 'Content-Type': 'application/json' });
res.end(JSON.stringify({
data: 'Hello World!',
}));
});
server.listen(8000);
Type Parameters #
#Request extends IncomingMessage = IncomingMessage #Response extends ServerResponse = ServerResponse Parameters #
#requestListener: RequestListener<Request, Response> Return Type #
Overload 2
#createServer<Request extends IncomingMessage = IncomingMessage,Response extends ServerResponse = ServerResponse,>(options: ServerOptions<Request, Response>,requestListener?: RequestListener<Request, Response>,): Server<Request, Response>Type Parameters #
#Request extends IncomingMessage = IncomingMessage #Response extends ServerResponse = ServerResponse Parameters #
#options: ServerOptions<Request, Response> #requestListener: RequestListener<Request, Response> Return Type #
function get
Usage in Deno
import { get } from "node:http";
Overload 1
#get(options: ,callback?: (res: IncomingMessage) => void,): ClientRequest
Constructor option createConnection is not supported.
Since most requests are GET requests without bodies, Node.js provides this
convenience method. The only difference between this method and request is that it sets the method to GET by default and calls req.end() automatically. The callback must take care to
consume the response
data for reasons stated in ClientRequest section.
The callback is invoked with a single argument that is an instance of IncomingMessage.
JSON fetching example:
http.get('http://localhost:8000/', (res) => {
const { statusCode } = res;
const contentType = res.headers['content-type'];
let error;
// Any 2xx status code signals a successful response but
// here we're only checking for 200.
if (statusCode !== 200) {
error = new Error('Request Failed.\n' +
`Status Code: ${statusCode}`);
} else if (!/^application\/json/.test(contentType)) {
error = new Error('Invalid content-type.\n' +
`Expected application/json but received ${contentType}`);
}
if (error) {
console.error(error.message);
// Consume response data to free up memory
res.resume();
return;
}
res.setEncoding('utf8');
let rawData = '';
res.on('data', (chunk) => { rawData += chunk; });
res.on('end', () => {
try {
const parsedData = JSON.parse(rawData);
console.log(parsedData);
} catch (e) {
console.error(e.message);
}
});
}).on('error', (e) => {
console.error(`Got error: ${e.message}`);
});
// Create a local server to receive data from
const server = http.createServer((req, res) => {
res.writeHead(200, { 'Content-Type': 'application/json' });
res.end(JSON.stringify({
data: 'Hello World!',
}));
});
server.listen(8000);
Parameters #
#callback: (res: IncomingMessage) => void Return Type #
Overload 2
#get(): ClientRequestfunction request
Usage in Deno
import { request } from "node:http";
Overload 1
#request(options: ,callback?: (res: IncomingMessage) => void,): ClientRequest
Constructor option createConnection is not supported.
options in socket.connect() are also supported.
Node.js maintains several connections per server to make HTTP requests. This function allows one to transparently issue requests.
url can be a string or a URL object. If url is a
string, it is automatically parsed with new URL(). If it is a URL object, it will be automatically converted to an ordinary options object.
If both url and options are specified, the objects are merged, with the options properties taking precedence.
The optional callback parameter will be added as a one-time listener for
the 'response' event.
http.request() returns an instance of the ClientRequest class. The ClientRequest instance is a writable stream. If one needs to
upload a file with a POST request, then write to the ClientRequest object.
import http from 'node:http';
import { Buffer } from 'node:buffer';
const postData = JSON.stringify({
'msg': 'Hello World!',
});
const options = {
hostname: 'www.google.com',
port: 80,
path: '/upload',
method: 'POST',
headers: {
'Content-Type': 'application/json',
'Content-Length': Buffer.byteLength(postData),
},
};
const req = http.request(options, (res) => {
console.log(`STATUS: ${res.statusCode}`);
console.log(`HEADERS: ${JSON.stringify(res.headers)}`);
res.setEncoding('utf8');
res.on('data', (chunk) => {
console.log(`BODY: ${chunk}`);
});
res.on('end', () => {
console.log('No more data in response.');
});
});
req.on('error', (e) => {
console.error(`problem with request: ${e.message}`);
});
// Write data to request body
req.write(postData);
req.end();
In the example req.end() was called. With http.request() one
must always call req.end() to signify the end of the request -
even if there is no data being written to the request body.
If any error is encountered during the request (be that with DNS resolution,
TCP level errors, or actual HTTP parse errors) an 'error' event is emitted
on the returned request object. As with all 'error' events, if no listeners
are registered the error will be thrown.
There are a few special headers that should be noted.
- Sending a 'Connection: keep-alive' will notify Node.js that the connection to the server should be persisted until the next request.
- Sending a 'Content-Length' header will disable the default chunked encoding.
- Sending an 'Expect' header will immediately send the request headers.
Usually, when sending 'Expect: 100-continue', both a timeout and a listener
for the
'continue'event should be set. See RFC 2616 Section 8.2.3 for more information. - Sending an Authorization header will override using the
authoption to compute basic authentication.
Example using a URL as options:
const options = new URL('http://abc:xyz@example.com');
const req = http.request(options, (res) => {
// ...
});
In a successful request, the following events will be emitted in the following order:
'socket''response''data'any number of times, on theresobject ('data'will not be emitted at all if the response body is empty, for instance, in most redirects)'end'on theresobject
'close'
In the case of a connection error, the following events will be emitted:
'socket''error''close'
In the case of a premature connection close before the response is received, the following events will be emitted in the following order:
'socket''error'with an error with message'Error: socket hang up'and code'ECONNRESET''close'
In the case of a premature connection close after the response is received, the following events will be emitted in the following order:
'socket''response''data'any number of times, on theresobject
- (connection closed here)
'aborted'on theresobject'close''error'on theresobject with an error with message'Error: aborted'and code'ECONNRESET''close'on theresobject
If req.destroy() is called before a socket is assigned, the following
events will be emitted in the following order:
- (
req.destroy()called here) 'error'with an error with message'Error: socket hang up'and code'ECONNRESET', or the error with whichreq.destroy()was called'close'
If req.destroy() is called before the connection succeeds, the following
events will be emitted in the following order:
'socket'- (
req.destroy()called here) 'error'with an error with message'Error: socket hang up'and code'ECONNRESET', or the error with whichreq.destroy()was called'close'
If req.destroy() is called after the response is received, the following
events will be emitted in the following order:
'socket''response''data'any number of times, on theresobject
- (
req.destroy()called here) 'aborted'on theresobject'close''error'on theresobject with an error with message'Error: aborted'and code'ECONNRESET', or the error with whichreq.destroy()was called'close'on theresobject
If req.abort() is called before a socket is assigned, the following
events will be emitted in the following order:
- (
req.abort()called here) 'abort''close'
If req.abort() is called before the connection succeeds, the following
events 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'ECONNRESET''close'
If req.abort() is called after the response is received, the following
events will be emitted in the following order:
'socket''response''data'any number of times, on theresobject
- (
req.abort()called here) 'abort''aborted'on theresobject'error'on theresobject with an error with message'Error: aborted'and code'ECONNRESET'.'close''close'on theresobject
Setting the timeout option or using the setTimeout() function will
not abort the request or do anything besides add a 'timeout' event.
Passing an AbortSignal and then calling abort() on the corresponding AbortController will behave the same way as calling .destroy() on the
request. Specifically, the 'error' event will be emitted with an error with
the message 'AbortError: The operation was aborted', the code 'ABORT_ERR' and the cause, if one was provided.
Parameters #
#options: #callback: (res: IncomingMessage) => void Return Type #
Overload 2
#request(): ClientRequestfunction setMaxIdleHTTPParsers
Usage in Deno
import { setMaxIdleHTTPParsers } from "node:http";
function validateHeaderName
Usage in Deno
import { validateHeaderName } from "node:http";
#validateHeaderName(name: string): voidPerforms the low-level validations on the provided name that are done when res.setHeader(name, value) is called.
Passing illegal value as name will result in a TypeError being thrown,
identified by code: 'ERR_INVALID_HTTP_TOKEN'.
It is not necessary to use this method before passing headers to an HTTP request or response. The HTTP module will automatically validate such headers.
Example:
import { validateHeaderName } from 'node:http';
try {
validateHeaderName('');
} catch (err) {
console.error(err instanceof TypeError); // --> true
console.error(err.code); // --> 'ERR_INVALID_HTTP_TOKEN'
console.error(err.message); // --> 'Header name must be a valid HTTP token [""]'
}
Parameters #
#name: string Return Type #
void function validateHeaderValue
Usage in Deno
import { validateHeaderValue } from "node:http";
#validateHeaderValue(name: string,value: string,): voidPerforms the low-level validations on the provided value that are done when res.setHeader(name, value) is called.
Passing illegal value as value will result in a TypeError being thrown.
- Undefined value error is identified by
code: 'ERR_HTTP_INVALID_HEADER_VALUE'. - Invalid value character error is identified by
code: 'ERR_INVALID_CHAR'.
It is not necessary to use this method before passing headers to an HTTP request or response. The HTTP module will automatically validate such headers.
Examples:
import { validateHeaderValue } from 'node:http';
try {
validateHeaderValue('x-my-header', undefined);
} catch (err) {
console.error(err instanceof TypeError); // --> true
console.error(err.code === 'ERR_HTTP_INVALID_HEADER_VALUE'); // --> true
console.error(err.message); // --> 'Invalid value "undefined" for header "x-my-header"'
}
try {
validateHeaderValue('x-my-header', 'oʊmɪɡə');
} catch (err) {
console.error(err instanceof TypeError); // --> true
console.error(err.code === 'ERR_INVALID_CHAR'); // --> true
console.error(err.message); // --> 'Invalid character in header content ["x-my-header"]'
}
Parameters #
Return Type #
void interface AgentOptions
Usage in Deno
import { type AgentOptions } from "node:http";
Properties #
Keep sockets around in a pool to be used by other requests in the future. Default = false
#keepAliveMsecs: number | undefined When using HTTP KeepAlive, how often to send TCP KeepAlive packets over sockets being kept alive. Default = 1000. Only relevant if keepAlive is set to true.
#maxSockets: number | undefined Maximum number of sockets to allow per host. Default for Node 0.10 is 5, default for Node 0.12 is Infinity
#maxTotalSockets: number | undefined Maximum number of sockets allowed for all hosts in total. Each request will use a new socket until the maximum is reached. Default: Infinity.
#maxFreeSockets: number | undefined Maximum number of sockets to leave open in a free state. Only relevant if keepAlive is set to true. Default = 256.
Socket timeout in milliseconds. This will set the timeout after the socket is connected.
#scheduling: "fifo"
| "lifo"
| undefined Scheduling strategy to apply when picking the next free socket to use.
interface ClientRequestArgs
Usage in Deno
import { type ClientRequestArgs } from "node:http";
Option createConnection is not supported.
Properties #
#_defaultAgent: Agent | undefined #createConnection: ((options: ClientRequestArgs,oncreate: (err: Error | null,socket: stream.Duplex,) => void,) => stream.Duplex
| null
| undefined) | undefined #defaultPort: number
| string
| undefined #headers: OutgoingHttpHeaders | undefined #hints: LookupOptions["hints"] #insecureHTTPParser: boolean | undefined #localAddress: string | undefined #lookup: LookupFunction | undefined #maxHeaderSize: number | undefined #setDefaultHeaders: boolean | undefined #socketPath: string | undefined #uniqueHeaders: Array<string | string[]> | undefined #joinDuplicateHeaders: boolean interface IncomingHttpHeaders
Usage in Deno
import { type IncomingHttpHeaders } from "node:http";
Properties #
#accept-language: string | undefined #accept-patch: string | undefined #accept-ranges: string | undefined #access-control-allow-credentials: string | undefined #access-control-allow-headers: string | undefined #access-control-allow-methods: string | undefined #access-control-allow-origin: string | undefined #access-control-expose-headers: string | undefined #access-control-max-age: string | undefined #access-control-request-headers: string | undefined #access-control-request-method: string | undefined #authorization: string | undefined #cache-control: string | undefined #connection: string | undefined #content-disposition: string | undefined #content-encoding: string | undefined #content-language: string | undefined #content-length: string | undefined #content-location: string | undefined #content-range: string | undefined #content-type: string | undefined #if-modified-since: string | undefined #if-none-match: string | undefined #if-unmodified-since: string | undefined #last-modified: string | undefined #proxy-authenticate: string | undefined #proxy-authorization: string | undefined #public-key-pins: string | undefined #retry-after: string | undefined #sec-websocket-accept: string | undefined #sec-websocket-extensions: string | undefined #sec-websocket-key: string | undefined #sec-websocket-protocol: string | undefined #sec-websocket-version: string | undefined #set-cookie: string[] | undefined #strict-transport-security: string | undefined #transfer-encoding: string | undefined #user-agent: string | undefined #www-authenticate: string | undefined interface InformationEvent
Usage in Deno
import { type InformationEvent } from "node:http";
Properties #
#statusCode: number #statusMessage: string #httpVersion: string #httpVersionMajor: number #httpVersionMinor: number #rawHeaders: string[] interface OutgoingHttpHeaders
Usage in Deno
import { type OutgoingHttpHeaders } from "node:http";
Properties #
#accept-charset: string
| string[]
| undefined #accept-encoding: string
| string[]
| undefined #accept-language: string
| string[]
| undefined #accept-ranges: string | undefined #access-control-allow-credentials: string | undefined #access-control-allow-headers: string | undefined #access-control-allow-methods: string | undefined #access-control-allow-origin: string | undefined #access-control-expose-headers: string | undefined #access-control-max-age: string | undefined #access-control-request-headers: string | undefined #access-control-request-method: string | undefined #authorization: string | undefined #cache-control: string | undefined #cdn-cache-control: string | undefined #connection: string
| string[]
| undefined #content-disposition: string | undefined #content-encoding: string | undefined #content-language: string | undefined #content-length: string
| number
| undefined #content-location: string | undefined #content-range: string | undefined #content-security-policy: string | undefined #content-security-policy-report-only: string | undefined #content-type: string | undefined #if-modified-since: string | undefined #if-none-match: string | undefined #if-unmodified-since: string | undefined #last-modified: string | undefined #max-forwards: string | undefined #proxy-authenticate: string
| string[]
| undefined #proxy-authorization: string | undefined #public-key-pins: string | undefined #public-key-pins-report-only: string | undefined #referrer-policy: string | undefined #retry-after: string | undefined #sec-websocket-accept: string | undefined #sec-websocket-extensions: string
| string[]
| undefined #sec-websocket-key: string | undefined #sec-websocket-protocol: string
| string[]
| undefined #sec-websocket-version: string | undefined #set-cookie: string
| string[]
| undefined #strict-transport-security: string | undefined #transfer-encoding: string | undefined #user-agent: string | undefined #upgrade-insecure-requests: string | undefined #www-authenticate: string
| string[]
| undefined #x-content-type-options: string | undefined #x-dns-prefetch-control: string | undefined #x-frame-options: string | undefined #x-xss-protection: string | undefined interface RequestOptions
Usage in Deno
import { type RequestOptions } from "node:http";
Option createConnection is not supported.
interface ServerOptions
Usage in Deno
import { type ServerOptions } from "node:http";
Type Parameters #
#Request extends IncomingMessage = IncomingMessage #Response extends ServerResponse = ServerResponse Properties #
#IncomingMessage: Request | undefined Specifies the IncomingMessage class to be used. Useful for extending the original IncomingMessage.
#ServerResponse: Response | undefined Specifies the ServerResponse class to be used. Useful for extending the original ServerResponse.
#requestTimeout: number | undefined Sets the timeout value in milliseconds for receiving the entire request from the client.
#joinDuplicateHeaders: boolean It joins the field line values of multiple headers in a request with , instead of discarding the duplicates.
#keepAliveTimeout: number | undefined The number of milliseconds of inactivity a server needs to wait for additional incoming data, after it has finished writing the last response, before a socket will be destroyed.
#connectionsCheckingInterval: number | undefined Sets the interval value in milliseconds to check for request and headers timeout in incomplete requests.
#highWaterMark: number | undefined Optionally overrides all sockets' readableHighWaterMark and writableHighWaterMark.
This affects highWaterMark property of both IncomingMessage and ServerResponse.
Default: @see stream.getDefaultHighWaterMark().
#insecureHTTPParser: boolean | undefined Use an insecure HTTP parser that accepts invalid HTTP headers when true.
Using the insecure parser should be avoided.
See --insecure-http-parser for more information.
#maxHeaderSize: number | undefined Optionally overrides the value of --max-http-header-size for requests received by
this server, i.e. the maximum length of request headers in bytes.
If set to true, it disables the use of Nagle's algorithm immediately after a new incoming connection is received.
If set to true, it enables keep-alive functionality on the socket immediately after a new incoming connection is received,
similarly on what is done in socket.setKeepAlive([enable][, initialDelay]).
#keepAliveInitialDelay: number | undefined If set to a positive number, it sets the initial delay before the first keepalive probe is sent on an idle socket.
#uniqueHeaders: Array<string | string[]> | undefined A list of response headers that should be sent only once.
If the header's value is an array, the items will be joined using ; .
type alias OutgoingHttpHeader
Usage in Deno
import { type OutgoingHttpHeader } from "node:http";
Definition #
number
| string
| string[] type alias RequestListener
Usage in Deno
import { type RequestListener } from "node:http";
Type Parameters #
#Request extends IncomingMessage = IncomingMessage #Response extends ServerResponse = ServerResponse Definition #
variable CloseEvent
Usage in Deno
import { CloseEvent } from "node:http";
Type #
import("undici-types").CloseEvent variable globalAgent
Usage in Deno
import { globalAgent } from "node:http";
variable maxHeaderSize
Usage in Deno
import { maxHeaderSize } from "node:http";
Read-only property specifying the maximum allowed size of HTTP headers in bytes.
Defaults to 16KB. Configurable using the --max-http-header-size CLI option.
Type #
number variable MessageEvent
Usage in Deno
import { MessageEvent } from "node:http";
Type #
import("undici-types").MessageEvent variable STATUS_CODES
Usage in Deno
import { STATUS_CODES } from "node:http";