Extends: undici.Dispatcher
A basic HTTP/1.1 client, mapped on top a single TCP/TLS connection. Pipelining is disabled by default.
Requests are not guaranteed to be dispatched in order of invocation.
new Client(url, options?): voidArguments:
- url
URL | string- Should only include the protocol, hostname, and port. - options
ClientOptions(optional)
Returns: Client
- bodyTimeout
number | null(optional) - Default:300e3- The timeout after which a request will time out, in milliseconds. Monitors time between receiving body data. Use0to disable it entirely. Defaults to 300 seconds. Please note thetimeoutwill be reset if you keep writing data to the socket everytime. - headersTimeout
number | null(optional) - Default:300e3- The amount of time, in milliseconds, the parser will wait to receive the complete HTTP headers while not sending the request. Defaults to 300 seconds. - keepAliveMaxTimeout
number | null(optional) - Default:600e3- The maximum allowedkeepAliveTimeout, in milliseconds, when overridden by keep-alive hints from the server. Defaults to 10 minutes. - keepAliveTimeout
number | null(optional) - Default:4e3- The timeout, in milliseconds, after which a socket without active requests will time out. Monitors time between activity on a connected socket. This value may be overridden by keep-alive hints from the server. See MDN: HTTP - Headers - Keep-Alive directives for more details. Defaults to 4 seconds. - keepAliveTimeoutThreshold
number | null(optional) - Default:2e3- A number of milliseconds subtracted from server keep-alive hints when overridingkeepAliveTimeoutto account for timing inaccuracies caused by e.g. transport latency. Defaults to 2 seconds. - maxHeaderSize
number | null(optional) - Default:--max-http-header-sizeor16384- The maximum length of request headers in bytes. Defaults to Node.js' --max-http-header-size or 16KiB. - maxResponseSize
number | null(optional) - Default:-1- The maximum length of response body in bytes. Set to-1to disable. - webSocket
WebSocketOptions(optional) - WebSocket-specific configuration options.- maxFragments
number(optional) - Default:131072- Maximum number of fragments in a message. Set to 0 to disable the limit. - maxPayloadSize
number(optional) - Default:134217728(128 MB) - Maximum allowed payload size in bytes for WebSocket messages. Applied to uncompressed messages, compressed frame payloads, and decompressed (permessage-deflate) messages. Set to 0 to disable the limit.
- maxFragments
- pipelining
number | null(optional) - Default:1- The amount of concurrent requests to be sent over the single TCP/TLS connection according to RFC7230. Carefully consider your workload and environment before enabling concurrent requests as pipelining may reduce performance if used incorrectly. Pipelining is sensitive to network stack settings as well as head of line blocking caused by e.g. long running requests. Set to0to disable keep-alive connections. This option has no effect once HTTP/2 is negotiated — seemaxConcurrentStreamsfor the h2 dispatch ceiling. - connect
ConnectOptions | Function | null(optional) - Default:null- Configures how undici establishes TCP/TLS connections. Accepts two forms:- Object (
ConnectOptions): Options passed directly to the internalbuildConnector(). This is the simplest way to customize TLS or socket behavior (e.g., settingrejectUnauthorized,ca,socketPath). SeeConnectOptionsfor available fields. - Function: A custom connector with the signature
(options, callback), whereoptionscontains{ hostname, host, protocol, port, servername, localAddress, httpSocket }andcallbackfollows(error, socket). Useful when you need full control over socket creation, such as adding custom validation or proxy logic. When a function is provided, undici wraps it to automatically injectsocketPathandallowH2into theoptionsargument if those values are set on the client.
- Object (
- strictContentLength
Boolean(optional) - Default:true- Whether to treat request content length mismatches as errors. If true, an error is thrown when the request content-length header doesn't match the length of the request body. Security Warning: Disabling this option can expose your application to HTTP Request Smuggling attacks, where mismatched content-length headers cause servers and proxies to interpret request boundaries differently. This can lead to cache poisoning, credential hijacking, and bypassing security controls. Only disable this in controlled environments where you fully trust the request source. - autoSelectFamily:
boolean(optional) - Default: depends on local Node version, on Node 18.13.0 and above isfalse. Enables a family autodetection algorithm that loosely implements section 5 of RFC 8305. See here for more details. This option is ignored if not supported by the current Node version. - autoSelectFamilyAttemptTimeout:
number- Default: depends on local Node version, on Node 18.13.0 and above is250. The amount of time in milliseconds to wait for a connection attempt to finish before trying the next address when using theautoSelectFamilyoption. See here for more details. - allowH2:
boolean- Default:true. Enables support for H2 if the server has assigned bigger priority to it through ALPN negotiation. - useH2c:
boolean- Default:false. Enforces h2c for non-https connections. - maxConcurrentStreams:
number- Default:100. The maximum number of concurrent HTTP/2 streams per session. WhenallowH2negotiates h2, this — notpipelining(which is HTTP/1.1 only, per RFC7230) — is the ceiling the Client uses to dispatch in-flight requests on a shared session. The same value is advertised to the server aspeerMaxConcurrentStreams, capping how many streams the server may push back. The initial value is replaced by the server'sSETTINGS_MAX_CONCURRENT_STREAMSwhenever the server sends one, so a user-supplied value acts as a pre-SETTINGSdefault rather than a hard cap. - initialWindowSize:
number(optional) - Default:262144(256KB). Sets the HTTP/2 stream-level flow-control window size (SETTINGS_INITIAL_WINDOW_SIZE). Must be a positive integer greater than 0. This default is higher than Node.js core's default (65535 bytes) to improve throughput, Node's choice is very conservative for current high-bandwith networks. See RFC 7540 Section 6.9.2 for more details. - connectionWindowSize:
number(optional) - Default524288(512KB). Sets the HTTP/2 connection-level flow-control window size usingClientHttp2Session.setLocalWindowSize(). Must be a positive integer greater than 0. This provides better flow control for the entire connection across multiple streams. See Node.js HTTP/2 documentation for more details. - pingInterval:
number- Default:60e3. The time interval in milliseconds between PING frames sent to the server. Set to0to disable PING frames. This is only applicable for HTTP/2 connections. This will emit apingevent on the client with the duration of the ping in milliseconds.
Notes about HTTP/2
- It only works under TLS connections. h2c is not supported.
- The server must support HTTP/2 and choose it as the protocol during the ALPN negotiation.
- The server must not have a bigger priority for HTTP/1.1 than HTTP/2.
- Pseudo headers are automatically attached to the request. If you try to set them, they will be overwritten.
- The
:pathheader is automatically set to the request path.- The
:methodheader is automatically set to the request method.- The
:schemeheader is automatically set to the request scheme.- The
:authorityheader is automatically set to the requesthost[:port].PUSHframes are yet not supported.
Every Tls option, see here. Furthermore, the following options can be passed:
- socketPath
string | null(optional) - Default:null- An IPC endpoint, either Unix domain socket or Windows named pipe. - maxCachedSessions
number | null(optional) - Default:100- Maximum number of TLS cached sessions. Use 0 to disable TLS session caching. Default: 100. - timeout
number | null(optional) - In milliseconds, Default10e3. - servername
string | null(optional) - keepAlive
boolean | null(optional) - Default:true- TCP keep-alive enabled - keepAliveInitialDelay
number | null(optional) - Default:60000- TCP keep-alive interval for the socket in milliseconds
This will instantiate the undici Client, but it will not connect to the origin until something is queued. Consider using client.connect to prematurely connect to the origin, or just call client.request.
'use strict'
import { Client } from 'undici'
const client = new Client('http://localhost:3000')Pass a ConnectOptions object to customize the TLS connection. The options are forwarded to the internal buildConnector().
'use strict'
import { Client } from 'undici'
import fs from 'node:fs'
const client = new Client('https://localhost:3000', {
connect: {
rejectUnauthorized: false,
ca: fs.readFileSync('./ca-cert.pem')
}
})Use the socketPath option to connect through an IPC endpoint instead of a TCP connection.
'use strict'
import { Client } from 'undici'
const client = new Client('http://localhost:3000', {
connect: {
socketPath: '/var/run/docker.sock'
}
})Pass a function for full control over socket creation. This allows you to perform additional checks on the socket, use a proxy, or implement custom connection logic.
Note: When a function is provided, undici wraps it to automatically inject
socketPathandallowH2into the first argument (options) when those values are set on the client.
'use strict'
import { Client, buildConnector } from 'undici'
const connector = buildConnector({ rejectUnauthorized: false })
const client = new Client('https://localhost:3000', {
connect (opts, cb) {
connector(opts, (err, socket) => {
if (err) {
cb(err)
} else if (/* assertion */) {
socket.destroy()
cb(new Error('kaboom'))
} else {
cb(null, socket)
}
})
}
})For more details on building custom connectors, see Connector.
Client.close(callback?): voidImplements Dispatcher.close([callback]).
Client.destroy(error?, callback?): voidImplements Dispatcher.destroy([error, callback]).
Waits until socket is closed before invoking the callback (or returning a promise if no callback is provided).
Client.connect(options, callback?): voidSee Dispatcher.connect(options[, callback]).
Client.dispatch(options, handlers): voidImplements Dispatcher.dispatch(options, handlers).
Client.pipeline(options, handler): voidSee Dispatcher.pipeline(options, handler).
Client.request(options, callback?): voidSee Dispatcher.request(options [, callback]).
Client.stream(options, factory, callback?): voidSee Dispatcher.stream(options, factory[, callback]).
Client.upgrade(options, callback?): voidSee Dispatcher.upgrade(options[, callback]).
boolean
true after client.close() has been called.
boolean
true after client.destroyed() has been called or client.close() has been called and the client shutdown has completed.
number
Property to get and set the pipelining factor.
See Dispatcher Event: 'connect'.
Parameters:
- origin
URL - targets
Array<Dispatcher>
Emitted when a socket has been created and connected. The client will connect once client.size > 0.
import { createServer } from 'http'
import { Client } from 'undici'
import { once } from 'events'
const server = createServer((request, response) => {
response.end('Hello, World!')
}).listen()
await once(server, 'listening')
const client = new Client(`http://localhost:${server.address().port}`)
client.on('connect', (origin) => {
console.log(`Connected to ${origin}`) // should print before the request body statement
})
try {
const { body } = await client.request({
path: '/',
method: 'GET'
})
body.setEncoding('utf-8')
body.on('data', console.log)
client.close()
server.close()
} catch (error) {
console.error(error)
client.close()
server.close()
}See Dispatcher Event: 'disconnect'.
Parameters:
- origin
URL - targets
Array<Dispatcher> - error
Error
Emitted when socket has disconnected. The error argument of the event is the error which caused the socket to disconnect. The client will reconnect if or once client.size > 0.
import { createServer } from 'http'
import { Client } from 'undici'
import { once } from 'events'
const server = createServer((request, response) => {
response.destroy()
}).listen()
await once(server, 'listening')
const client = new Client(`http://localhost:${server.address().port}`)
client.on('disconnect', (origin) => {
console.log(`Disconnected from ${origin}`)
})
try {
await client.request({
path: '/',
method: 'GET'
})
} catch (error) {
console.error(error.message)
client.close()
server.close()
}Emitted when pipeline is no longer busy.
See Dispatcher Event: 'drain'.
import { createServer } from 'http'
import { Client } from 'undici'
import { once } from 'events'
const server = createServer((request, response) => {
response.end('Hello, World!')
}).listen()
await once(server, 'listening')
const client = new Client(`http://localhost:${server.address().port}`)
client.on('drain', () => {
console.log('drain event')
client.close()
server.close()
})
const requests = [
client.request({ path: '/', method: 'GET' }),
client.request({ path: '/', method: 'GET' }),
client.request({ path: '/', method: 'GET' })
]
await Promise.all(requests)
console.log('requests completed')Invoked for user errors such as throwing in the onResponseError handler.