undici implements the WHATWG Fetch Standard, providing fetch() together
with the Request, Response, Headers, and FormData classes that mirror
the browser APIs. The implementation follows the standard, so the
MDN Fetch documentation applies as well.
import { fetch, Request, Response, Headers, FormData } from 'undici'
const response = await fetch('https://example.com')
const text = await response.text()When mixing these classes, keep them from the same implementation: use the
global fetch() with the global FormData, Request, Response, and
Headers, and use undici's fetch() with undici's classes. Passing a value
created by one implementation to the other can throw.
fetch(input, init?): Promise<RequestInit><string>
|
<Buffer>
|
<Uint8Array>
|
<Blob>
|
<FormData>
|
<URLSearchParams>
|
<ReadableStream>
|
<null>null
.<string>'default'
,
'force-cache'
,
'no-cache'
,
'no-store'
,
'only-if-cached'
, or
'reload'
.<string>'omit'
,
'include'
, or
'same-origin'
.<Dispatcher><Dispatcher>
used to perform the request.
Default:
the global dispatcher.<string>'half'
when a
streaming
body
is provided.<Headers>
instance, a plain object, or an array of
[name, value]
pairs.<string><boolean>false
.<string>'GET'
or
'POST'
.<string>'cors'
,
'navigate'
,
'no-cors'
, or
'same-origin'
.<string>'error'
,
'follow'
, or
'manual'
.<string><string>''
,
'no-referrer'
,
'no-referrer-when-downgrade'
,
'origin'
,
'origin-when-cross-origin'
,
'same-origin'
,
'strict-origin'
,
'strict-origin-when-cross-origin'
, or
'unsafe-url'
.<AbortSignal>
|
<null><AbortSignal>
used to abort the request.
Default:
null
.<null>null
; reserved by the standard.<Promise><Response>
once the response headers have
been received.Starts the process of fetching a resource from the network and returns a
promise that fulfills with a <Response>. The promise rejects only on network
failures; an HTTP error status such as 404 still fulfills the promise, so
inspect response.ok to detect failures.
import { fetch } from 'undici'
const response = await fetch('https://example.com', {
method: 'POST',
headers: { 'content-type': 'application/json' },
body: JSON.stringify({ hello: 'world' }),
})
console.log(response.status)
console.log(await response.json())To route the request through a custom <Dispatcher> (for example a ProxyAgent
or Agent with specific options), pass it as init.dispatcher.
import { fetch, Agent } from 'undici'
const response = await fetch('https://example.com', {
dispatcher: new Agent({ connect: { rejectUnauthorized: false } }),
})A set of key/value pairs representing form fields and their values, suitable
for use as a fetch() request body. The implementation follows the
WHATWG Fetch Standard; see the MDN FormData documentation.
When using FormData as a request body, keep fetch and FormData from the
same implementation: use the global FormData with the global fetch(), and
undici's FormData with undici's fetch().
new FormData(): voidCreates a new, empty FormData instance. Passing any argument other than
undefined throws; in particular, an HTMLFormElement argument is not
supported in this environment.
formData.append(name, value, filename?): voidAppends a new value to an existing key, or adds the key if it does not exist.
Unlike formData.set(), append() keeps
any existing values for name.
formData.delete(name): void<string>Deletes all values associated with name.
formData.get(name): string | File | null<string>formData.getAll(name): Array<string>formData.has(name): boolean<string><boolean>true
if at least one value is associated with
name
.formData.set(name, value, filename?): voidSets a new value for an existing key, or adds the key if it does not exist,
replacing any values previously associated with name.
class Response extends BodyMixinRepresents the response to a request. Instances are typically obtained by
awaiting fetch(), but can also be constructed directly. The implementation
follows the WHATWG Fetch Standard; see the
MDN Response documentation. Response inherits the body-reading methods
described in Body mixin.
new Response(body?, init?): void<string>
|
<Buffer>
|
<Uint8Array>
|
<Blob>
|
<FormData>
|
<URLSearchParams>
|
<ReadableStream>
|
<null>null
.Creates a new Response.
Response.error(): Response<Response>Returns a new Response representing a network error, with its
type set to 'error'.
Response.json(data, init?): Response<Response>data
and whose
Content-Type
is
application/json
.import { Response } from 'undici'
const response = Response.json({ ok: true }, { status: 201 })Response.redirect(url, status?): Response<Response>Location
header set to
url
.response.clone(): Response<Response>Creates a clone of the response. Throws a TypeError if the body has already
been read or is locked.
<string>'basic'
,
'cors'
,
'default'
,
'error'
,
'opaque'
, or
'opaqueredirect'
.<string><boolean>true
if the response is the result of one or more
redirects.<number><string>class Request extends BodyMixinRepresents a resource request. Instances can be passed to fetch() in place
of a URL string. The implementation follows the WHATWG Fetch Standard; see
the MDN Request documentation. Request inherits the body-reading
methods described in Body mixin.
new Request(input, init?): Request<Request>Creates a new Request.
request.clone(): Request<Request>Creates a clone of the request. Throws a TypeError if the body has already
been read or is locked.
<string>'GET'
.<string><string>''
,
'image'
, or
'script'
.<string>'about:client'
or a URL
string.<string><string>'cors'
,
'navigate'
,
'no-cors'
, or
'same-origin'
.<string>'omit'
,
'include'
, or
'same-origin'
.<string><string>'error'
,
'follow'
, or
'manual'
.<string><boolean><boolean>true
if the request is a reload navigation.<boolean>true
if the request is a history navigation.<AbortSignal><AbortSignal>
associated with the request.<string>'half'
.Represents the header list of a request or response and provides methods to
read and modify it. The implementation follows the WHATWG Fetch Standard;
see the MDN Headers documentation. Headers is iterable, yielding
[name, value] pairs sorted by name.
new Headers(init?): voidCreates a new Headers object.
headers.append(name, value): voidAppends a value to a header, or adds the header if it does not exist. Existing
values for name are preserved.
headers.delete(name): void<string>Removes the header named name.
headers.get(name): string | null<string>headers.has(name): boolean<string><boolean>true
if the header is present.headers.set(name, value): voidSets a header to a single value, replacing any existing values for name.
headers.getSetCookie(): string<string>Set-Cookie
headers.Returns each Set-Cookie header as a separate string, without combining them.
Request and Response both extend <BodyMixin>, which provides methods and
properties for reading a body. Each consuming method reads the body once; after
the body has been consumed, bodyUsed becomes true and
calling another consuming method throws a TypeError.
body.arrayBuffer(): Promise<Promise><ArrayBuffer>
containing the body bytes.body.blob(): Promisebody.bytes(): Promise<Promise><Uint8Array>
containing the body bytes.body.formData(): Promise<Promise><FormData>
parsed from the body.Buffers and parses the entire body as multipart/form-data or
application/x-www-form-urlencoded. Because multipart parsing has inherent
security risks and the whole body is buffered, this method must only be called
on responses from trusted servers.
For responses from untrusted or user-controlled servers, use a dedicated streaming parser such as @fastify/busboy and apply application-specific limits:
import { Busboy } from '@fastify/busboy'
import { Readable } from 'node:stream'
const response = await fetch('...')
const busboy = new Busboy({
headers: { 'content-type': response.headers.get('content-type') },
})
// Handle the events emitted by `busboy`.
Readable.fromWeb(response.body).pipe(busboy)body.json(): Promise<Promise>body.text(): Promisebody.textStream(): ReadableStream<ReadableStream><ReadableStream>
of
<string>
chunks produced by
decoding the body as UTF-8.An undici-specific extension that exposes the body as a stream of decoded text chunks rather than buffering it. It is not part of the WHATWG Fetch Standard.
<ReadableStream>
|
<null><ReadableStream>
, or
null
if the
message has no body.<boolean>true
once the body has been read.