Dispatcher is the abstract base class that every undici transport builds on top of. You never instantiateDocumentation Index
Fetch the complete documentation index at: https://mintlify.com/nodejs/undici/llms.txt
Use this file to discover all available pages before exploring further.
Dispatcher directly — instead you work with concrete implementations like Client, Pool, or Agent. Understanding Dispatcher matters because all methods (request, stream, pipeline, dispatch, connect, upgrade) and all events (connect, disconnect, drain, connectionError) are defined here and inherited by every dispatcher in the library.
Requests are not guaranteed to be dispatched in order of invocation.
Non-idempotent requests will not be pipelined, but idempotent requests may be
automatically retried if they fail due to head-of-line blocking.
Methods
dispatch(options, handler)
The low-level API that all higher-level methods delegate to. Use this when you need complete control over the request lifecycle via callbacks. Returns false when the dispatcher is busy — wait for the drain event before dispatching again.
Basic dispatch example
DispatchOptions
The origin to dispatch the request against. Required by
Agent; inferred
from the constructor URL for Client and Pool.The request path, including query string if not using
query.HTTP method (e.g.
'GET', 'POST', 'PUT').body.body
string | Buffer | Uint8Array | stream.Readable | Iterable | AsyncIterable | null
default:"null"
Request body.
Request headers. Can be an object, a flat string array (even-length), or any
iterable of
[name, value] pairs (e.g. Headers, Map).Query string parameters. Keys and values are encoded with
encodeURIComponent.
For unencoded query strings, embed them directly in path.When
true, sends connection: close and closes the socket after the
response. Defaults to keep-alive behavior.Whether the request can be safely retried. Non-idempotent requests are not
pipelined.
Prevents further pipelining on the same connection until response headers
arrive. Set to
true for long-running requests.Upgrade token (e.g.
'websocket'). When set, the handler must implement
onRequestUpgrade.Milliseconds to wait for complete response headers before timing out.
Set to
0 to disable.Milliseconds of inactivity on body data before timing out.
Set to
0 to disable.Abort signal or an
EventEmitter that emits 'abort'.HTTP/2 only. Appends
expect: 100-continue and holds the body until the
server acknowledges.DispatchHandler
The handler object passed to dispatch(). All methods receive a DispatchController as their first argument.
Called before the request is dispatched. May be called multiple times on
retry.
Called when the status code and headers are received. May fire multiple times
for
1xx informational responses.Called for each chunk of response body data.
Called when the response is fully received, including trailers.
Called on error. Must not throw.
Required when
upgrade is set or method is CONNECT.Controller API
TheDispatchController passed to every handler method exposes:
controller.pause()— back-pressure signal to pause data flowcontroller.resume()— resume after apause()controller.abort(reason?)— abort the requestcontroller.rawHeaders— raw response header arraycontroller.rawTrailers— raw trailer array
If you are migrating from the legacy handler API (
onConnect, onHeaders,
onData, onComplete, onError), switch to the new callbacks. Use
Dispatcher1Wrapper to expose a new dispatcher to legacy v1 handler
consumers.Legacy compatibility wrapper
request(options[, callback])
Performs an HTTP request and returns a ResponseData object. Idempotent requests are automatically retried on head-of-line failures (unless the body is a stream). All response bodies must be consumed or destroyed.
GET request
POST with JSON body
Aborting a request
RequestOptions
Extends DispatchOptions. Additional fields:
Passed through to
ResponseData and StreamFactoryData. Use to avoid
closures in factory functions.Called for each
1xx informational response before the final response.ResponseData
HTTP response status code.
Status message (e.g.
"OK", "Not Found").Response headers. All keys are lower-cased.
Response body stream. Also implements the Fetch body mixin:
.json(),
.text(), .arrayBuffer(), .blob(), .bytes(). Cannot be consumed
twice. Call body.dump() to discard without killing the socket.HTTP trailers, populated after
body emits 'end'.The value passed as
options.opaque.stream(options, factory[, callback])
A faster alternative to request that writes the response body directly to a stream.Writable returned by factory. Avoids creating an intermediate Readable.
Stream response to a Writable
pipeline(options, handler)
For use with Node.js stream.pipeline. The handler receives { statusCode, headers, body, opaque } and must return a Readable. Returns a Duplex that writes the request body and reads the response.
connect(options[, callback])
Opens a raw TCP tunnel using HTTP CONNECT. Returns { statusCode, headers, socket, opaque }.
Target host and port in the form
host:port.Additional request headers.
Abort signal.
upgrade(options[, callback])
Upgrades to a different protocol (e.g. WebSocket). Returns { headers, socket, opaque }.
Request path.
HTTP method.
Comma-separated protocol list in descending preference order.
Additional request headers.
close([callback])
Gracefully closes the dispatcher. Waits for in-flight requests to complete before resolving.
destroy([error][, callback])
Abruptly destroys the dispatcher. All pending and running requests are asynchronously aborted with the provided error (or a generic error if omitted).
compose(interceptors)
Wraps the dispatcher with one or more interceptors, returning a new Dispatcher. Interceptors are applied in reverse order — the last interceptor in the array is the first to process each request.
Adding redirect and retry interceptors
Built-in interceptors
redirect
redirect
Handles HTTP redirects automatically.
retry
retry
Retries failed requests with exponential backoff. Accepts the same options as
RetryHandler.cache
cache
Client-side HTTP caching per RFC 9111. Accepts a
CacheStore (default: MemoryCacheStore).dns
dns
Caches DNS lookups per origin to reduce resolution overhead.Options:
maxTTL (default 10000 ms), maxItems, dualStack (default true), affinity (4 or 6), lookup, pick, storage.dump
dump
Dumps (discards) response bodies up to
maxSize bytes (default 1 MB) without killing the connection.decompress
decompress
Automatically decompresses gzip, deflate, brotli, and zstd response bodies per RFC 9110.Options:
skipErrorResponses (default true), skipStatusCodes (default [204, 304]).responseError
responseError
Throws a
ResponseError for any response with a status code >= 400.deduplicate
deduplicate
Deduplicates concurrent identical requests so only one reaches the origin.Options:
methods (default ['GET']), skipHeaderNames, excludeHeaderNames, maxBufferSize.Events
Emitted when a socket connects to the origin.
Parameters:
origin: URL, targets: Dispatcher[].Emitted when a socket disconnects. For HTTP/2, also fired on
GOAWAY frames.
Parameters: origin: URL, targets: Dispatcher[], error: Error.Emitted when the dispatcher fails to connect to the origin.
Parameters:
origin: URL, targets: Dispatcher[], error: Error.Emitted when the dispatcher is no longer busy. Safe to call
dispatch()
again after this event. Parameters: origin: URL.Header formats (UndiciHeaders)
Headers can be passed in three forms:
- Object
- Array
- Iterable