Topic 26 of 40
HTTP Status Codes
Overview
If an API request fails, you shouldn't just return { error: 'Not found' } with a 200 OK status. Browsers, caching layers (Cloudflare), and frontend libraries (Axios) rely entirely on standard 3-digit HTTP Status Codes to understand what happened. They are bucketed into 5 groups: 1xx (Info), 2xx (Success), 3xx (Redirect), 4xx (Client Error - The frontend messed up), and 5xx (Server Error - The backend crashed).
Syntax
javascript
// --- 2xx SUCCESS ---
res.status(200).json(data); // 200 OK (Standard success)
res.status(201).json(data); // 201 Created (Perfect for successful POSTs)
res.status(204).end(); // 204 No Content (Perfect for DELETEs - sends no body)
// --- 4xx CLIENT ERRORS ---
res.status(400).json(err); // 400 Bad Request (Invalid JSON, failed validation)
res.status(401).json(err); // 401 Unauthorized (Missing or invalid JWT token)
res.status(403).json(err); // 403 Forbidden (Valid token, but you lack Admin rights)
res.status(404).json(err); // 404 Not Found (Resource doesn't exist)
res.status(429).json(err); // 429 Too Many Requests (Rate Limiter triggered)
// --- 5xx SERVER ERRORS ---
res.status(500).json(err); // 500 Internal Server Error (Database crashed, Null pointer)Common Pitfalls
- Returning
200 OKfor an error. This is notoriously known as a 'Soft 404'. If a user requests a profile that doesn't exist, and you returnres.status(200).json({ error: 'User not found' }), the frontend thinks it succeeded, Google will cache the error page as a success, and monitoring tools (Datadog) will completely fail to log the error. - Confusing 401 and 403. 401 means 'I don't know who you are' (You are not logged in). 403 means 'I know exactly who you are, but you are not allowed to do this' (You are logged in, but you aren't an Admin).
Interview Questions
Q:
If a user attempts to update their profile, but the JSON payload is missing the required 'email' field, which status code should the backend return?
A:
400 Bad Request. The 400 range specifically implies that the Client (frontend) made a mistake in formatting the request, and the server refuses to process the invalid data.
Real-World Example
Using standard HTTP status codes in a login endpoint.
example
javascript
app.post('/api/login', async (req, res) => {
const { email, password } = req.body;
// 400: The client forgot to send data!
if (!email || !password) return res.status(400).json({ error: "Missing fields" });
const user = await db.findUser(email);
// 401: We don't know who this is!
if (!user || user.password !== password) {
return res.status(401).json({ error: "Invalid credentials" });
}
// 200: Success!
res.status(200).json({ token: "jwt_token" });
});Check Your Knowledge
Test your understanding of HTTP Status Codes with these quick questions.