On this page

M

Fetch

History
Source Code: lib/web/fetch/index.js
Stability: 2Stable

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
Attributes
The resource to fetch. A string or <URL> is treated as the URL to request; a <Request> is used as the request template.
(optional) An options object that customizes the request.
The request body.  Default: null .
cache:<string>
The cache mode. One of  'default' , 'force-cache' , 'no-cache' , 'no-store' , 'only-if-cached' , or 'reload' .
credentials:<string>
How credentials are sent. One of  'omit' , 'include' , or 'same-origin' .
dispatcher?:<Dispatcher>
The <Dispatcher> used to perform the request.  Default: the global dispatcher.
duplex:<string>
The duplex mode of the request. Must be  'half' when a streaming body is provided.
The request headers, as a <Headers> instance, a plain object, or an array of  [name, value] pairs.
integrity:<string>
The subresource integrity metadata of the request.
keepalive?:<boolean>
Whether the connection may outlive the page.  Default: false .
method:<string>
The request method, for example  'GET' or 'POST' .
The request mode. One of  'cors' , 'navigate' , 'no-cors' , or 'same-origin' .
redirect:<string>
How redirects are handled. One of  'error' , 'follow' , or 'manual' .
referrer:<string>
The request referrer.
referrerPolicy:<string>
The referrer policy. One of  '' , 'no-referrer' , 'no-referrer-when-downgrade' , 'origin' , 'origin-when-cross-origin' , 'same-origin' , 'strict-origin' , 'strict-origin-when-cross-origin' , or 'unsafe-url' .
An <AbortSignal> used to abort the request.  Default: null .
window:<null>
Can only be  null ; reserved by the standard.
Returns:<Promise>
Fulfills with a <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 } }),
})
C

FormData

History

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().

C

FormData Constructor

History
new FormData(): void

Creates a new, empty FormData instance. Passing any argument other than undefined throws; in particular, an HTMLFormElement argument is not supported in this environment.

M

formData.append

History
formData.append(name, value, filename?): void
Attributes
The name of the field.
The value of the field.
filename:<string>
The filename reported to the server when  value  is a <Blob> . (optional)

Appends 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.

M

formData.delete

History
formData.delete(name): void
Attributes
The name of the field to remove.

Deletes all values associated with name.

M

formData.get

History
formData.get(name): string | File | null
Attributes
The name of the field to read.
Returns:<string> | <File> | <null>
The first value associated with  name , or null if there is none.
M

formData.getAll

History
formData.getAll(name): Array
Attributes
The name of the field to read.
Returns:<Array>
All values associated with  name , as an array of <string> and <File> entries.
M

formData.has

History
formData.has(name): boolean
Attributes
The name of the field to look up.
Returns:<boolean>
true if at least one value is associated with name .
M

formData.set

History
formData.set(name, value, filename?): void
Attributes
The name of the field.
The value of the field.
filename:<string>
The filename reported to the server when  value  is a <Blob> . (optional)

Sets a new value for an existing key, or adds the key if it does not exist, replacing any values previously associated with name.

C

Response

History
class Response extends BodyMixin

Represents 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.

C

Response Constructor

History
new Response(body?, init?): void
Attributes
The response body.  Default: null .
(optional)
status?:<number>
The response status code.  Default: 200 .
statusText?:<string>
The response status message.  Default: '' .
The response headers.

Creates a new Response.

S

Response.error

History
Response.error(): Response
Returns:<Response>
A network-error response.

Returns a new Response representing a network error, with its type set to 'error'.

S

Response.json

History
Response.json(data, init?): Response
Attributes
data:<any>
The value to serialize as JSON.
(optional)
status?:<number>
The response status code.  Default: 200 .
statusText?:<string>
The response status message.  Default: '' .
The response headers.
Returns:<Response>
A response whose body is the JSON serialization of  data and whose Content-Type is application/json .
import { Response } from 'undici'

const response = Response.json({ ok: true }, { status: 201 })
S

Response.redirect

History
Response.redirect(url, status?): Response
Attributes
The URL to redirect to.
status?:<number>
The redirect status code. One of  301 , 302 , 303 , 307 , or 308 . Default: 302 .
Returns:<Response>
A redirect response with the  Location header set to url .
M

response.clone

History
response.clone(): Response
Returns:<Response>
A copy of the response.

Creates a clone of the response. Throws a TypeError if the body has already been read or is locked.

P

response.type

History
The response type. One of  'basic' , 'cors' , 'default' , 'error' , 'opaque' , or 'opaqueredirect' .
P

response.url

History
The final URL of the response after any redirects, or the empty string if not available.
P

response.redirected

History
true if the response is the result of one or more redirects.
P

response.status

History
The HTTP status code of the response.
P

response.ok

History
true when status is in the range 200299 .
P

response.statusText

History
The status message corresponding to the status code.
P

response.headers

History
The <Headers> object associated with the response.
C

Request

History
class Request extends BodyMixin

Represents 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.

C

Request Constructor

History
new Request(input, init?): Request
Attributes
The resource to request, as a URL string, <URL> , or another <Request> to copy.
(optional) An options object with the same fields as the  init argument of fetch() .
Returns:<Request>

Creates a new Request.

M

request.clone

History
request.clone(): Request
Returns:<Request>
A copy of the request.

Creates a clone of the request. Throws a TypeError if the body has already been read or is locked.

P

request.method

History
The request method, for example  'GET' .
P

request.url

History
The serialized URL of the request.
P

request.headers

History
The <Headers> object associated with the request.
P

request.destination

History
The request destination, indicating the type of content being requested, for example  '' , 'image' , or 'script' .
P

request.referrer

History
The referrer of the request. May be  'about:client' or a URL string.
P

request.referrerPolicy

History
The referrer policy of the request.
P

request.mode

History
The mode of the request. One of  'cors' , 'navigate' , 'no-cors' , or 'same-origin' .
P

request.credentials

History
The credentials mode of the request. One of  'omit' , 'include' , or 'same-origin' .
P

request.cache

History
The cache mode of the request.
P

request.redirect

History
The redirect mode of the request. One of  'error' , 'follow' , or 'manual' .
P

request.integrity

History
The subresource integrity metadata of the request.
P

request.keepalive

History
Whether the request may outlive the environment that created it.
P

request.isReloadNavigation

History
true if the request is a reload navigation.
P

request.isHistoryNavigation

History
true if the request is a history navigation.
P

request.signal

History
The <AbortSignal> associated with the request.
P

request.duplex

History
The duplex mode of the request. Always  'half' .
C

Headers

History

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.

C

Headers Constructor

History
new Headers(init?): void
Attributes
(optional) Initial headers, as a <Headers> instance, a plain object of name/value pairs, or an array of  [name, value] pairs.

Creates a new Headers object.

M

headers.append

History
headers.append(name, value): void
Attributes
The name of the header.
value:<string>
The value of the header.

Appends a value to a header, or adds the header if it does not exist. Existing values for name are preserved.

M

headers.delete

History
headers.delete(name): void
Attributes
The name of the header to remove.

Removes the header named name.

M

headers.get

History
headers.get(name): string | null
Attributes
The name of the header to read.
Returns:<string> | <null>
The combined values of the header, or  null if it is not present.
M

headers.has

History
headers.has(name): boolean
Attributes
The name of the header to look up.
Returns:<boolean>
true if the header is present.
M

headers.set

History
headers.set(name, value): void
Attributes
The name of the header.
value:<string>
The value of the header.

Sets a header to a single value, replacing any existing values for name.

M

headers.getSetCookie

History
headers.getSetCookie(): string
Returns:<string>
[] An array of the values of all  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.

M

body.arrayBuffer

History
body.arrayBuffer(): Promise
Returns:<Promise>
Fulfills with an <ArrayBuffer> containing the body bytes.
M

body.blob

History
body.blob(): Promise
Returns:<Promise>
Fulfills with a <Blob> containing the body.
M

body.bytes

History
body.bytes(): Promise
Returns:<Promise>
Fulfills with a <Uint8Array> containing the body bytes.
M

body.formData

History
body.formData(): Promise
Stability: 0Deprecated
Returns:<Promise>
Fulfills with a <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)
M

body.json

History
body.json(): Promise
Returns:<Promise>
Fulfills with the result of parsing the body as JSON.
M

body.text

History
body.text(): Promise
Returns:<Promise>
Fulfills with a <string> containing the body decoded as UTF-8.
M

body.textStream

History
body.textStream(): ReadableStream
Stability: 1Experimental
A <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.

P

body

History
The body as a <ReadableStream> , or  null if the message has no body.
P

body.bodyUsed

History
true once the body has been read.