Browse topics

fetch and Response

Version
es2025
Review
Draft

Summary#

fetch starts a request and resolves to a Response once the response is available. Body methods such as json() and text() read the content asynchronously.

Syntax#

js
const response = await fetch(url, options);
const data = await response.json();

Example#

js
const response = await fetch('data:application/json,{"name":"Ada"}');
if (!response.ok) throw new Error(`HTTP ${response.status}`);
console.log(response.status, (await response.json()).name);

const missing = new Response("not found", { status: 404 });
console.log(missing.ok, missing.status, await missing.text());
console.log(missing.bodyUsed);

Expected output#

Text
200 Ada
false 404 not found
true

The data: URL and constructed response need no network. The example checks bodyUsed on the constructed response because Node.js 17.5.0 can report false after reading a data: response. Experimental releases can also print warnings to stderr.

Common mistakes#

An HTTP error status such as 404 or 500 does not reject fetch, so check response.ok or response.status. A network error does reject. A body can be consumed only once, so a second call to json() or text() rejects.

Version applicability#

fetch and Response are Web APIs defined by the Fetch Standard. The --experimental-fetch flag enabled them starting in Node.js 16.15.0 and 17.5.0. The complete example runs without flags from 18.0.0. Save it as an .mjs file for ES2022 top-level await.

Sources#

Attribution
DevLookup contributors
License
CC-BY-4.0