Sub topic 2
Inspecting the Response
When fetch() settles, it gives you a Response object. Before you read any data from it, you should look at what kind of answer the server sent. This chapter covers the properties that describe a response: status, ok, statusText, headers, url, redirected, and type. Reading the body is covered in the next chapter, and the full error-handling pattern comes in the one after that. Here the goal is to understand what each property tells you and where it can mislead you.
This chapter assumes you know Promises and async/await, basic HTTP status codes and headers, and how to run code in the browser console. The examples use top-level await, which works in the browser console and in Node.js 18+ when the file is an ES module (.mjs).
When the Response Arrives
The Promise from fetch() resolves when the response headers arrive. The body may still be downloading at that point. This means the status line and headers are available right away, so you can decide whether you want the body before you spend time reading it.
Every property in this chapter is synchronous. You read response.status directly, with no await.
The Core Properties at a Glance
| Property | Type | What it tells you |
|---|---|---|
| `status` | number | The HTTP status code, such as `200`, `404`, or `500` |
| `ok` | boolean | `true` when `status` is between 200 and 299 inclusive |
| `statusText` | string | The reason phrase, such as `"Not Found"`, which is often empty |
| `headers` | `Headers` | The response headers the browser lets you read |
| `url` | string | The final URL after any redirects |
| `redirected` | boolean | `true` if at least one redirect was followed |
| `type` | string | `"basic"`, `"cors"`, `"opaque"`, `"opaqueredirect"`, or `"error"` |
| `bodyUsed` | boolean | Whether the body has already been read |
Status Codes and `ok`
status is the number the server sent. ok is a shortcut: it is true for any 2xx status and false for everything else. The two are tied together, and you cannot set ok on its own.
You can try this without a server by building Response objects yourself. The Response constructor takes a body and an options object:
const examples = [
new Response('fine', { status: 200, statusText: 'OK' }),
new Response(null, { status: 204 }),
new Response('moved', { status: 301 }),
new Response('missing', { status: 404, statusText: 'Not Found' }),
new Response('broken', { status: 500 })
];
for (const r of examples) {
console.log(r.status, r.ok, JSON.stringify(r.statusText));
}
// 200 true "OK"
// 204 true ""
// 301 false ""
// 404 false "Not Found"
// 500 false ""Note that a 3xx status gives ok === false. In practice you rarely see one, because fetch follows redirects automatically and hands you the final response. You only see a 3xx if the server sends one without a Location header, or if you have changed the redirect behavior.
Here is how the status classes map to what you will actually see from fetch:
| Range | Meaning | `ok` | Seen from `fetch`? |
|---|---|---|---|
| 1xx | Informational | n/a | No. The browser handles these internally |
| 2xx | Success | `true` | Yes |
| 3xx | Redirection | `false` | Rarely. Redirects are followed by default |
| 4xx | Client error | `false` | Yes, and the Promise still resolves |
| 5xx | Server error | `false` | Yes, and the Promise still resolves |
Branching on specific codes
ok works for a quick yes or no. Many APIs give specific codes different meanings, so you often need status itself:
function describe(response) {
if (response.ok) {
return response.status === 204 ? 'success, no content' : 'success';
}
switch (response.status) {
case 401: return 'not signed in';
case 403: return 'signed in but not allowed';
case 404: return 'resource does not exist';
case 409: return 'conflict with current state';
case 429: return 'rate limited, retry later';
default:
return response.status >= 500 ? 'server problem' : 'request problem';
}
}
console.log(describe(new Response(null, { status: 204 }))); // success, no content
console.log(describe(new Response('', { status: 429 }))); // rate limited, retry later
console.log(describe(new Response('', { status: 503 }))); // server problemA status of 204 (No Content) is worth handling explicitly. It counts as ok, but there is no body, so calling response.json() on it fails with a parse error.
Why `statusText` Is Often Empty
statusText holds the reason phrase from the HTTP/1.1 status line, as in HTTP/1.1 404 Not Found. HTTP/2 and HTTP/3 dropped reason phrases completely. Most production APIs and CDNs now use HTTP/2 or later, so statusText is usually an empty string even for errors.
const response = new Response('', { status: 404 });
console.log(`Error: ${response.status} ${response.statusText}`); // "Error: 404 "Use statusText only as decoration in messages. Never branch on it, and expect it to be blank. If you want readable messages, keep your own lookup table keyed by status.
Reading Headers
response.headers is a Headers object. The method you will use most is get(), which returns the header value as a string, or null if the header is missing. Name lookups ignore case.
const response = new Response('{"id":1}', {
status: 200,
headers: {
'Content-Type': 'application/json; charset=utf-8',
'Cache-Control': 'max-age=60'
}
});
console.log(response.headers.get('content-type')); // application/json; charset=utf-8
console.log(response.headers.get('CACHE-CONTROL')); // max-age=60
console.log(response.headers.get('x-missing')); // null
console.log(response.headers.has('Content-Type')); // true
for (const [name, value] of response.headers) {
console.log(name, '=', value); // names come back lowercased
}Two details matter in real code:
- Compare content types with
includesorstartsWith. The value often carries parameters such as; charset=utf-8, so=== 'application/json'fails. - Use optional chaining. Because
get()can returnnull, writeresponse.headers.get('content-type')?.includes('json')to avoid aTypeError.
The Headers interface itself, including building headers for requests, has its own chapter later. Here we only read them.
Headers you cannot see
On a cross-origin response, the browser hides most headers from JavaScript even when they are visible in the Network panel. By default you can read only the CORS-safelisted response headers:
Cache-ControlContent-LanguageContent-LengthContent-TypeExpiresLast-ModifiedPragma
Anything else, such as X-Request-Id, ETag, or Link, returns null unless the server lists it in Access-Control-Expose-Headers. Set-Cookie is never exposed to JavaScript, even on same-origin responses.
`url` and `redirected`
fetch follows up to 20 redirects by default. The Response you get describes the last hop, and two properties record what happened along the way:
response.urlis the final URL. It can differ from the one you passed in.response.redirectedistrueif any redirect occurred.
const requested = 'http://example.com/';
const response = await fetch(requested);
console.log(response.status); // 200, the status of the final hop
console.log(response.redirected); // true if, for example, http redirected to https
console.log(response.url); // the final URL after redirectsRunning this from a page served over HTTPS may be blocked as mixed content. In that case, run it from Node.js or point it at a URL you know redirects.
This matters in a few real situations:
- Login redirects. An API that has lost your session may redirect to an HTML login page that returns
200.okistrue, but parsing the body as JSON fails. Checkingredirectedor theContent-Typeheader catches this. - Resolving relative links. If the server returns relative URLs, resolve them against
response.url, not the original request URL. - Logging. Log both URLs when debugging, because the status belongs to the final one.
Response Types
response.type tells you how the browser classified the response, which decides how much of it you are allowed to see.
| `type` | Produced by | `status` | Headers | Body readable |
|---|---|---|---|---|
| `basic` | Same-origin request | Real | All except `Set-Cookie` | Yes |
| `cors` | Cross-origin request allowed by CORS | Real | Safelisted plus exposed | Yes |
| `opaque` | `mode: 'no-cors'` cross-origin request | `0` | None | No |
| `opaqueredirect` | `redirect: 'manual'` and a redirect occurred | `0` | None | No |
| `error` | `Response.error()` | `0` | None | No |
The trap here is opaque. A no-cors request to another origin resolves successfully, but you get status === 0 and ok === false, and you cannot read the body. You have no way to tell whether the server returned 200 or 500. Developers sometimes add mode: 'no-cors' to make a CORS error go away, and then wonder why the data is empty. CORS and request modes are covered in detail later. For now, remember that a status of 0 means you were not allowed to see the real status.
const opaque = await fetch('https://example.org/', { mode: 'no-cors' });
console.log(opaque.type, opaque.status, opaque.ok); // opaque 0 falseRun this one in a browser on a page from a different origin. Node.js does not enforce CORS, so there you will get a normal response.
Constructing Responses for Tests
The Response constructor used above is also useful for unit tests, because you can stub fetch without a network. A few rules apply:
statusmust be between 200 and 599. Anything else, including0, throws aRangeError.- Statuses 101, 103, 204, 205, and 304 are "null body" statuses. Passing a non-null body with them throws a
TypeError. Response.json(data, init)is a static helper that serializes data and setsContent-Type: application/json. It is available in current browsers and Node.js 18.20+.Response.error()creates atype: 'error'response with status0.
try {
new Response('x', { status: 204 });
} catch (err) {
console.log(err.name); // TypeError: 204 cannot have a body
}
try {
new Response(null, { status: 0 });
} catch (err) {
console.log(err.name); // RangeError
}
const stub = Response.json({ id: 1 }, { status: 201 });
console.log(stub.status, stub.ok, stub.headers.get('content-type'));
// 201 true application/jsonA Checklist Before Reading the Body
Before you read a body, you can answer these questions from the properties alone:
- Is
response.typeopaqueoropaqueredirect? If so, nothing is readable. - Is
response.oktrue? If not, whichstatusis it? - Is the status 204, or is
Content-Lengthequal to0? Then there is no body to parse. - Does
Content-Typematch the format you expect? - Did
redirectedtake you somewhere unexpected?
function inspect(response) {
return {
type: response.type,
status: response.status,
ok: response.ok,
statusText: response.statusText || '(empty)',
contentType: response.headers.get('content-type'),
redirected: response.redirected,
url: response.url || '(none)'
};
}
console.table(inspect(Response.json({ hello: 'world' }, { status: 200 })));A constructed Response has an empty url, which is why the helper falls back to '(none)'.
Exercise
A cross-origin API returns 200 and the Network panel shows a header X-Total-Count: 42, but response.headers.get('x-total-count') returns null. Why, and where must the fix happen?
Show answer
For cross-origin responses, JavaScript can only read the CORS-safelisted headers unless the server exposes others. The server must send Access-Control-Expose-Headers: X-Total-Count. Changing the client code cannot reveal the header.
Exercise
Your code calls fetch('/api/orders') and gets status 200 and ok true, but response.json() throws a syntax error. response.redirected is true and response.url ends in /login. What happened, and which properties could have caught it before parsing?
Show answer
The session expired and the server redirected to an HTML login page, which fetch followed automatically. The final 200 belongs to the login page. Checking response.redirected, response.url, or response.headers.get('content-type')?.includes('application/json') before parsing would have caught it.
Exercise
What do status, ok, and type contain for a cross-origin request made with mode: 'no-cors', and can you tell whether the server returned an error?
Show answer
type is "opaque", status is 0, and ok is false. You cannot tell whether the server succeeded or failed, because opaque responses hide the status, headers, and body.
Exercise
Write an expression that returns true only when a response is successful and contains JSON, without throwing if the Content-Type header is missing.
Show answer
response.ok && (response.headers.get('content-type')?.includes('application/json') ?? false). Optional chaining prevents a TypeError when get() returns null, and ?? false turns the resulting undefined into a boolean.