deps/undici/src/docs/docs/api/Fetch.md
Stability: 2 - Stable
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])input {string|URL|Request} The resource to fetch. A string or {URL} is
treated as the URL to request; a {Request} is used as the request template.init {RequestInit} (optional) An options object that customizes the
request.
body {string|Buffer|Uint8Array|Blob|FormData|URLSearchParams|ReadableStream|null}
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.headers {Headers|Object|Array} 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'.mode {string} 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'.signal {AbortSignal|null} An {AbortSignal} used to abort the request.
Default: null.window {null} Can only be null; reserved by the standard.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 } }),
})
FormDataA 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()Creates 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])name {string} The name of the field.value {string|Blob} 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.
formData.delete(name)name {string} The name of the field to remove.Deletes all values associated with name.
formData.get(name)name {string} The name of the field to read.name, or
null if there is none.formData.getAll(name)name {string} The name of the field to read.name, as an array of
{string} and {File} entries.formData.has(name)name {string} The name of the field to look up.true if at least one value is associated with name.formData.set(name, value[, filename])name {string} The name of the field.value {string|Blob} 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.
ResponseRepresents 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]])body {string|Buffer|Uint8Array|Blob|FormData|URLSearchParams|ReadableStream|null}
The response body. Default: null.init {ResponseInit} (optional)
status {number} The response status code. Default: 200.statusText {string} The response status message. Default: ''.headers {Headers|Object|Array} The response headers.Creates a new Response.
Response.error()Returns a new Response representing a network error, with its
type set to 'error'.
Response.json(data[, init])data {any} The value to serialize as JSON.init {ResponseInit} (optional)
status {number} The response status code. Default: 200.statusText {string} The response status message. Default: ''.headers {Headers|Object|Array} The response headers.data and whose Content-Type is application/json.import { Response } from 'undici'
const response = Response.json({ ok: true }, { status: 201 })
Response.redirect(url[, status])url {string|URL} The URL to redirect to.status {number} The redirect status code. One of 301, 302, 303,
307, or 308. Default: 302.Location header set to
url.response.clone()Creates a clone of the response. Throws a TypeError if the body has already
been read or is locked.
response.type'basic', 'cors', 'default',
'error', 'opaque', or 'opaqueredirect'.response.urlresponse.redirectedtrue if the response is the result of one or more
redirects.response.statusresponse.oktrue when status is in the range
200–299.response.statusTextresponse.headersRequestRepresents 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])input {string|URL|Request} The resource to request, as a URL string,
{URL}, or another {Request} to copy.init {RequestInit} (optional) An options object with the same fields as
the init argument of fetch().Creates a new Request.
request.clone()Creates a clone of the request. Throws a TypeError if the body has already
been read or is locked.
request.method'GET'.request.urlrequest.headersrequest.destination'', 'image', or 'script'.request.referrer'about:client' or a URL
string.request.referrerPolicyrequest.mode'cors', 'navigate',
'no-cors', or 'same-origin'.request.credentials'omit',
'include', or 'same-origin'.request.cacherequest.redirect'error',
'follow', or 'manual'.request.integrityrequest.keepaliverequest.isReloadNavigationtrue if the request is a reload navigation.request.isHistoryNavigationtrue if the request is a history navigation.request.signalrequest.duplex'half'.HeadersRepresents 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])init {Headers|Object|Array} (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.
headers.append(name, value)name {string} 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.
headers.delete(name)name {string} The name of the header to remove.Removes the header named name.
headers.get(name)name {string} The name of the header to read.null if it is
not present.headers.has(name)name {string} The name of the header to look up.true if the header is present.headers.set(name, value)name {string} 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.
headers.getSetCookie()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()body.blob()body.bytes()body.formData()Stability: 0 - Deprecated
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()body.text()body.textStream()Stability: 1 - Experimental
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.
body.bodynull if the
message has no body.body.bodyUsedtrue once the body has been read.