HTTP Status Codes
Return the right status code so clients understand the outcome.
Syntax
res.status(code)Status codes tell the client what happened. Sending the correct one is an important part of a good API.
| Code | Meaning |
|---|---|
200 OK | Success |
201 Created | New resource created |
204 No Content | Success, nothing to return |
400 Bad Request | Invalid input |
401 Unauthorized | Not logged in |
404 Not Found | Resource missing |
500 Server Error | Something crashed |
Example
app.post('/posts', (req, res) => {
if (!req.body.title) {
return res.status(400).json({ error: 'title is required' });
}
// ... save it ...
res.status(201).json({ id: 1, title: req.body.title });
});When to use it
- A POST endpoint returns 201 Created when a new resource is successfully stored, allowing clients to distinguish creation from update.
- A validation middleware returns 422 Unprocessable Entity with field-level error details when the request body fails schema checks.
- An authentication guard returns 401 Unauthorized when no token is present and 403 Forbidden when the token exists but lacks permission.
More examples
Common success codes
Demonstrates 200, 201, and 204 — the three most common success codes for GET, POST, and DELETE.
app.get('/items', (req, res) => res.status(200).json([])); // 200 OK
app.post('/items', (req, res) => res.status(201).json({ id: 1 })); // 201 Created
app.delete('/items/1',(req, res) => res.status(204).send()); // 204 No ContentClient error codes
Returns 400 Bad Request for an invalid ID format and 404 Not Found when the resource does not exist.
app.get('/items/:id', (req, res) => {
if (isNaN(req.params.id)) return res.status(400).json({ error: 'ID must be numeric' });
const item = find(req.params.id);
if (!item) return res.status(404).json({ error: 'Not found' });
res.json(item);
});Auth error codes
Returns 401 when no token is present and 403 when the token exists but does not grant access.
function authGuard(req, res, next) {
const token = req.headers.authorization;
if (!token) return res.status(401).json({ error: 'Unauthorized' });
if (token !== 'admin') return res.status(403).json({ error: 'Forbidden' });
next();
}
app.get('/admin', authGuard, (req, res) => res.json({ secret: true }));
Discussion