API requests
Retrieve JSON from an HTTP API and convert it into a JavaScript value.
Node.js · Function
Node.js provides a browser-compatible global fetch() for making HTTP requests. It returns a promise for a Response, whose status and body can be inspected asynchronously.
fetch() is a browser-compatible global that starts an HTTP request and returns a promise for a Response. Await the response, inspect its status, then consume the body with a response method such as json(); request behavior can be customized through the options object.
fetch(input[, init])| Name | Type | Description |
|---|---|---|
input | string | URL | Request | The resource URL or request input accepted by the Fetch API. |
init | RequestInit | Optional request configuration, including headers, method, body, and a compatible dispatcher. |
A Promise that fulfills with a Response object.
FormData, Headers, Request, and Response.const response = await fetch('https://nodejs.org/api/documentation.json');
if (!response.ok) throw new Error(`HTTP ${response.status}`);
const data = await response.json();
console.log(data.title);Fetches Node.js documentation, rejects non-successful HTTP statuses, parses the JSON body, and prints its title.
Retrieve JSON from an HTTP API and convert it into a JavaScript value.
Send HTTP requests from backend services without adding a separate fetch package.
Configure Undici-based request routing or connection behavior with a custom dispatcher.
fetch() return and how is the body read?fetch() is a browser-compatible global in Node.js. It returns a promise for a Response, and the response body must be consumed separately, for example with json().
Follow-up: How can request dispatch be customized? Pass a compatible Undici dispatcher in the fetch options, such as { dispatcher: myDispatcher }.
fetch() built into Node.js, and what implementation does it use?The API is available globally, so code can call fetch(url) without importing a separate Node.js module. It is implemented using Undici, an HTTP/1.1 client built for Node.js.
Follow-up: How can the implementation version be inspected? Read process.versions.undici in the running Node.js process.
fetch() become stable?The API became available without the --experimental-fetch flag in Node.js 18. It was marked no longer experimental in Node.js 21.0.0.
Follow-up: Which related globals accompany it? Node.js documents FormData, Headers, Request, and Response as globals available for use with fetch.
FormDataHeadersRequestResponseprocess.versions.undici