Sub topic 3
Reading Response Bodies
When fetch() resolves, you have a Response object, but the data the server sent is still not in your hands. The status line and headers arrive first. The body arrives separately, possibly in many pieces, and you decide how to read it. This chapter covers the body-reading methods, what each returns, the rule that a body can be read only once, and the failures that come from getting the format wrong.
This chapter assumes you are comfortable with Promises and async/await, know what a Response object is and how to check status and headers (covered in the previous chapter), and can run code in a browser console or a recent Node.js version (18 or later), both of which provide fetch and Response globally.
Why reading the body is a separate step
fetch() resolves as soon as the response headers have arrived. At that point the body may still be downloading. A 50 MB file and a 50-byte JSON reply both resolve fetch() at about the same moment. The difference shows up when you read the body.
That is why each body method returns a Promise. Calling response.json() means "wait for the rest of the bytes, then turn them into a JavaScript value." Every request therefore involves two awaits:
const response = await fetch('https://api.example.com/users/1'); // headers arrived
const user = await response.json(); // body arrived and parsed
console.log(user);The body-reading methods
The Response object has a family of methods that all read the full body and resolve with it in a different shape. They are defined on the shared Body mixin, so Request objects have them too.
| Method | Resolves with | Typical use |
|---|---|---|
| `json()` | Any JSON value (object, array, string, number, boolean, null) | API responses |
| `text()` | A string, decoded as UTF-8 | HTML, CSV, plain text, debugging |
| `blob()` | A `Blob` with a `type` taken from `Content-Type` | Images, files to download or display |
| `arrayBuffer()` | An `ArrayBuffer` of raw bytes | Binary formats you parse yourself |
| `bytes()` | A `Uint8Array` of raw bytes | Same as `arrayBuffer()`, one step shorter (newer API) |
| `formData()` | A `FormData` object | Bodies encoded as `multipart/form-data` or `application/x-www-form-urlencoded` |
You can try all of these without a server. The Response constructor builds a response from local data, which makes it useful for experiments and tests:
const jsonRes = new Response('{"id": 1, "name": "Ada"}', {
headers: { 'Content-Type': 'application/json' }
});
console.log(await jsonRes.json()); // { id: 1, name: 'Ada' }
const textRes = new Response('line one\nline two');
console.log((await textRes.text()).split('\n')); // [ 'line one', 'line two' ]
const binRes = new Response(new Uint8Array([72, 105]));
const buffer = await binRes.arrayBuffer();
console.log(buffer.byteLength); // 2json()
json() reads the whole body as text and passes it to JSON.parse. It does not look at the Content-Type header. If the bytes are valid JSON, you get a value back. If they are not, the Promise rejects with a SyntaxError, even when the header says application/json.
The result is whatever the JSON contains, which is not always an object. A body of 42 gives you the number 42, and a body of null gives you null. Check the shape before you use it when you don't control the server.
text()
text() always decodes the bytes as UTF-8. It ignores any charset parameter in Content-Type. If a legacy server sends Windows-1252 or Shift_JIS text, text() will produce garbled characters. In that case, read the bytes and decode them yourself:
const res = new Response(new Uint8Array([0x63, 0x61, 0x66, 0xe9])); // "café" in Windows-1252
const bytes = await res.arrayBuffer();
console.log(new TextDecoder('windows-1252').decode(bytes)); // 'café'text() is also the most useful method for debugging. When an API returns something unexpected, reading it as text shows you exactly what came over the wire.
blob()
A Blob is an immutable chunk of binary data with a MIME type. blob() sets that type from the response's Content-Type. Blobs work well for handing data to other browser APIs without ever converting it to a string. This example shows an image in the page:
async function showImage(url, imgElement) {
const response = await fetch(url);
if (!response.ok) throw new Error(`HTTP ${response.status}`);
const blob = await response.blob();
console.log(blob.type, blob.size); // e.g. 'image/png' 48213
const objectUrl = URL.createObjectURL(blob);
imgElement.src = objectUrl;
imgElement.onload = () => URL.revokeObjectURL(objectUrl); // free the memory
}
showImage('https://api.example.com/avatar.png', document.querySelector('img'));Object URLs keep the blob alive until you revoke them or the page unloads. In a long-running app that loads many images, forgetting revokeObjectURL slowly leaks memory.
arrayBuffer() and bytes()
Use these when you need to inspect or transform the raw bytes. An ArrayBuffer cannot be read directly. You wrap it in a typed array or a DataView. bytes() skips that step and returns a Uint8Array, but it was added only recently (Chrome 132, Firefox 128, Safari 18, Node.js 22.3). If you support older environments, use new Uint8Array(await response.arrayBuffer()).
This function checks whether a downloaded file is really a PNG by reading its 8-byte signature:
async function isPng(response) {
const bytes = new Uint8Array(await response.arrayBuffer());
const signature = [0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a];
return signature.every((b, i) => bytes[i] === b);
}
const fake = new Response(new Uint8Array([0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a, 0x00]));
console.log(await isPng(fake)); // trueformData()
formData() parses form-encoded bodies into a FormData object. You will rarely call it on a server response in browser code. It is more common in service workers and server-side runtimes that receive form submissions as Request objects. If the body is not form-encoded, the Promise rejects with a TypeError.
Bodies can be read only once
A response body is a stream of bytes. Reading it consumes the stream, and after that the bytes are gone. Calling any second body method, even a different one, rejects with a TypeError:
const res = new Response('{"ok": true}');
console.log(res.bodyUsed); // false
console.log(await res.json()); // { ok: true }
console.log(res.bodyUsed); // true
try {
await res.text();
} catch (err) {
console.log(err.name, err.message); // TypeError, e.g. 'Body is unusable' or 'body stream already read'
}The bodyUsed property tells you whether the body has been consumed. The exact error message differs between browsers and Node.js, so don't match on it.
Using clone() when you need the body twice
If two parts of your code each need the body, call clone() before anyone reads it. The clone has its own copy of the body stream:
const original = new Response('{"items": [1, 2, 3]}');
const copy = original.clone();
const data = await original.json();
const raw = await copy.text();
console.log(data.items.length, raw.length); // 3 20clone() throws a TypeError if the body has already been used, so it must come first.
When parsing fails
The most common body-reading failure is calling json() on something that is not JSON. Typical causes:
- An error page in HTML from a proxy, load balancer, or framework, often with a 502 or 500 status.
- An empty body, such as a
204 No Contentreply or aDELETEthat returns nothing.JSON.parse('')throws. - A login redirect that landed on an HTML page.
The error you see, something like SyntaxError: Unexpected token '<', tells you the first character was <, which almost always means HTML. A trap waits here: the failed json() call has already consumed the body. You cannot fall back to text() to see what the server actually said.
There are two safe patterns. The first reads as text, then parses, so you keep the raw body for error messages:
async function readJsonSafely(response) {
const raw = await response.text();
if (raw === '') return null;
try {
return JSON.parse(raw);
} catch {
throw new Error(`Expected JSON but got: ${raw.slice(0, 100)}`);
}
}
const htmlError = new Response('<html><body>Bad Gateway</body></html>', { status: 502 });
try {
await readJsonSafely(htmlError);
} catch (err) {
console.log(err.message); // Expected JSON but got: <html><body>Bad Gateway</body></html>
}The second decides on the method from the status and Content-Type before reading anything:
async function readBody(response) {
if (response.status === 204 || response.status === 205) return null;
const type = response.headers.get('content-type') ?? '';
if (type.includes('application/json')) return response.json();
if (type.startsWith('text/')) return response.text();
return response.blob();
}
const r = new Response('{"a":1}', { headers: { 'Content-Type': 'application/json; charset=utf-8' } });
console.log(await readBody(r)); // { a: 1 }Note the includes check. Servers usually append parameters such as ; charset=utf-8, so an exact comparison with 'application/json' will miss them. Some APIs also use vendor types like application/problem+json. Widen the check if your API does.
Unread bodies and resource use
If you never read a body, the connection may stay open while the browser waits for you, and the data may sit in a buffer. For most small API calls this does not matter much, because the runtime eventually cleans up. Node.js is stricter. Its fetch implementation can keep sockets busy until unread bodies are garbage collected, which can exhaust the connection pool under load. If you check a status and decide you don't need the body, release it explicitly:
const response = await fetch('https://api.example.com/health');
if (response.ok) {
await response.body?.cancel(); // discard the body without reading it
console.log('healthy');
}response.body is the underlying ReadableStream. It is null for responses that cannot have a body. Reading it chunk by chunk, instead of all at once, is the topic of the chapter on streaming.
Common mistakes
| Symptom | Cause | Fix |
|---|---|---|
| `SyntaxError: Unexpected token '<'` | Server returned HTML, often an error page | Check `ok` and `Content-Type`, or read as text first |
| `SyntaxError: Unexpected end of JSON input` | Empty body (204, or empty 200) | Return `null` for empty bodies before parsing |
| `TypeError` mentioning body used or unusable | Body read twice, or `clone()` after reading | Read once and store the result, or clone before reading |
| Logged value is `Promise { <pending> }` | Forgot `await` on `json()` | `await response.json()` |
| Garbled accented characters | Non-UTF-8 text decoded by `text()` | `arrayBuffer()` plus `TextDecoder` with the right encoding |
| Memory grows while loading images | Object URLs never revoked | Call `URL.revokeObjectURL` when done |
Exercise
This code logs the parsed data, then throws a TypeError. Why, and what is the smallest fix that lets you log both the parsed object and the raw text? const res = await fetch('https://api.example.com/report'); const data = await res.json(); const raw = await res.text();
Show answer
The body is a single-use stream. json() consumes it, so the later text() call rejects with a TypeError. The smallest fix is to clone before the first read: const copy = res.clone(); then await res.json() and await copy.text(). An alternative that avoids buffering a second copy is to read once with const raw = await res.text(); and compute data with JSON.parse(raw).
Exercise
A DELETE endpoint returns 204 No Content. Your code calls await response.json() and gets "SyntaxError: Unexpected end of JSON input". Explain the error and write a guard that returns null instead.
Show answer
A 204 response has no body, so json() tries JSON.parse('') and throws. Check the status before parsing: if (response.status === 204) return null; return response.json(); To also handle servers that send an empty 200, read with const raw = await response.text(); and return raw === '' ? null : JSON.parse(raw).
Exercise
You download a file and want to show it in an <img> element and also log its size in bytes. Which body method should you use, and what cleanup step should follow?
Show answer
Use blob(). The Blob has a size property for the byte count and a type taken from Content-Type, and URL.createObjectURL(blob) gives you a URL to set as the image src. After the image loads, call URL.revokeObjectURL(objectUrl) so the browser can free the blob's memory.