Sub topic 7
Reading status codes
Prerequisites and scope
This chapter assumes you can read a basic HTTP request and response (request line, headers, blank line, body) and that you know the common methods such as GET and POST. It also assumes you can run curl in a terminal. The goal is to read the status line of a response and decide what it means and what to do next.
A status code is a three-digit number in the first line of every HTTP response. It tells the client whether the server understood the request, whether it succeeded, and what the client should do next. The text after the number, such as OK, is a reason phrase. It is for humans only. Clients act on the number.
HTTP/1.1 404 Not Found
Content-Type: text/html; charset=utf-8
Content-Length: 22
<h1>Page missing</h1>The five classes
The first digit sets the class. A client that does not recognize a specific code must treat it like the x00 code of its class. For example, an unknown 499 is handled as 400.
| Class | Meaning | Who usually needs to act |
|---|---|---|
| 1xx | Informational. The request is in progress. | Nobody. The client waits for the final response. |
| 2xx | Success. The request was received and accepted. | The client uses the result. |
| 3xx | Redirection. The client must take another step. | The client, often automatically. |
| 4xx | Client error. The request is wrong or not allowed. | The client or its user must change the request. |
| 5xx | Server error. The server failed on a valid request. | The server operator. The client may retry. |
The split between 4xx and 5xx is the most useful rule for debugging. A 4xx means "look at what you sent." A 5xx means "look at the server."
Success codes (2xx)
200 OK: the request worked. For GET, the body holds the resource. For POST, the body usually describes the result.201 Created: the request created a new resource. The server normally sends aLocationheader with the new resource's URL.202 Accepted: the server accepted the request but has not finished the work. This suits background jobs.204 No Content: success, with no body. It is common for DELETE and for PUT or PATCH calls that have nothing to return.206 Partial Content: the response holds only the byte range the client asked for with aRangeheader. Video players and download managers use it.
A 204 response must not include a body. If your code calls response.json() on a 204, it fails because there is nothing to parse.
Redirects (3xx)
A redirect response carries a Location header with the next URL. Browsers follow it automatically. The codes differ in two ways: whether the redirect is permanent, and whether the client may change the method.
| Code | Name | Permanent? | Method on the next request |
|---|---|---|---|
| 301 | Moved Permanently | Yes | May change POST to GET (historical behavior) |
| 302 | Found | No | May change POST to GET (historical behavior) |
| 303 | See Other | No | Always becomes GET |
| 307 | Temporary Redirect | No | Must stay the same |
| 308 | Permanent Redirect | Yes | Must stay the same |
The historical behavior exists because early browsers turned a redirected POST into a GET, and the specification later accepted that. The newer codes 307 and 308 remove the ambiguity. Use them when a POST must stay a POST.
A common pattern is Post/Redirect/Get. A form POST succeeds, and the server answers 303 See Other pointing to a confirmation page. The browser then does a GET. Reloading the page repeats the harmless GET, not the form submission.
304 Not Modified is also in the 3xx class, but it is not a redirect. It answers a conditional request and means the cached copy is still valid. It has no body and no Location header.
You can watch a redirect with curl. Without -L, curl shows the redirect and stops.
curl -i http://example.com/old-page
curl -iL http://example.com/old-pageThe -i flag prints the response headers. The -L flag follows Location headers.
Client errors (4xx)
400 Bad Request: the server could not parse or accept the request. Examples are malformed JSON or an invalid query parameter.401 Unauthorized: the request lacks valid credentials. Despite the name, this is about authentication ("who are you?"). The response should include aWWW-Authenticateheader.403 Forbidden: the server knows who you are, or does not need to, and refuses anyway. This is about authorization ("you may not do this").404 Not Found: no resource exists at this URL, or the server does not want to reveal that it does.405 Method Not Allowed: the URL exists but not for this method. The response should include anAllowheader listing the valid methods.409 Conflict: the request conflicts with the current state of the resource, such as an edit based on an outdated version.410 Gone: the resource existed and was removed on purpose.415 Unsupported Media Type: the server does not accept the request'sContent-Type.422 Unprocessable Content: the syntax is valid but the content fails validation. Many APIs use it for form errors.429 Too Many Requests: rate limiting. ARetry-Afterheader often says how long to wait.
The two most confused pairs are 401 versus 403 and 404 versus 410. If a login would fix the problem, 401 fits. If a login would not help, 403 fits.
Server errors (5xx)
500 Internal Server Error: an unexpected failure, usually an unhandled exception in application code.501 Not Implemented: the server does not support the requested method at all.502 Bad Gateway: a proxy or gateway got an invalid response from the server behind it.503 Service Unavailable: the server is overloaded or down for maintenance. It may includeRetry-After.504 Gateway Timeout: a proxy waited too long for the server behind it.
In setups with a proxy or load balancer, 502 and 504 point to a problem between the proxy and the application, not to the client's request. Check the application logs and whether the app is running.
Choosing codes in your own server
The Node.js server from earlier in this tutorial always returns 200. A real server should pick the code that matches the outcome. This example runs as written on Node.js 18 or later.
import { createServer } from "node:http";
const notes = new Map([["1", "Buy milk"]]);
const server = createServer((req, res) => {
const url = new URL(req.url, "http://localhost:3000");
const send = (status, text, extra = {}) => {
res.writeHead(status, {
"Content-Type": "text/plain; charset=utf-8",
...extra,
});
res.end(text + "\n");
};
if (url.pathname === "/old") {
return send(308, "Moved", { Location: "/notes/1" });
}
const match = url.pathname.match(/^\/notes\/(\d+)$/);
if (!match) {
return send(404, "No such path");
}
if (req.method !== "GET") {
return send(405, "Use GET", { Allow: "GET" });
}
const note = notes.get(match[1]);
if (note === undefined) {
return send(404, "No such note");
}
send(200, note);
});
server.listen(3000);Test each branch and print only the status line and a few headers:
curl -i http://localhost:3000/notes/1
curl -i http://localhost:3000/notes/99
curl -i -X POST http://localhost:3000/notes/1
curl -i http://localhost:3000/oldExpect 200, 404, 405 with Allow: GET, and 308 with Location: /notes/1.
Reading codes on the client
The fetch API has a common trap. It rejects its promise only on network failures, such as DNS errors or refused connections. A 404 or 500 is a normal, resolved response. Check response.ok, which is true for 200 to 299.
const response = await fetch("https://example.com/missing");
if (!response.ok) {
console.error(`Request failed: ${response.status} ${response.statusText}`);
} else {
console.log(await response.text());
}For 5xx codes and 429, a client may retry. Retry only requests that are safe to repeat, such as GET, or requests the server marks as idempotent. Use a delay that grows between attempts, and honor Retry-After when present. Retrying a plain POST after a 500 can create duplicates, because the server may have completed part of the work before it failed.
Common mistakes
- Returning
200with an error message in the body. Monitoring tools, caches, and clients all read the status code, so they will treat the failure as a success. - Using
403when the user is not logged in, instead of401. - Using
302where a POST must stay a POST. Use307or308. - Using
500for bad user input. That is a400or422, and a500will trigger server alerts needlessly. - Assuming a
200from a proxy or CDN came from your application. An intermediate cache may have answered.
Exercise
A user submits a login form with a correct password but their account is suspended. Your server refuses the login. Which status code fits best, 401 or 403, and why? Then name the code you would send after a successful form POST so that reloading the result page does not resubmit the form.
Show answer
Use 403 Forbidden. The server identified the user correctly, so authentication succeeded, and the server refuses the action anyway. A 401 would suggest that different credentials could fix the problem. After a successful form POST, send 303 See Other with a Location header pointing to a result page. The browser then issues a GET, so a reload repeats the GET and not the POST.
Exercise
Your fetch call to an API returns without throwing, but the data is missing. The server responded 500. Why did no error occur, and what check would catch it?
Show answer
fetch rejects only on network-level failures. A 500 response is a completed HTTP exchange, so the promise resolves. Check response.ok (or response.status) after the call and handle the failure case explicitly.