HTTP Status Codes

Return the right status code so clients understand the outcome.

Syntaxres.status(code)

Status codes tell the client what happened. Sending the correct one is an important part of a good API.

CodeMeaning
200 OKSuccess
201 CreatedNew resource created
204 No ContentSuccess, nothing to return
400 Bad RequestInvalid input
401 UnauthorizedNot logged in
404 Not FoundResource missing
500 Server ErrorSomething crashed

Example

Example · javascript
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.

Example · js
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 Content

Client error codes

Returns 400 Bad Request for an invalid ID format and 404 Not Found when the resource does not exist.

Example · js
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.

Example · js
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

  • Be the first to comment on this lesson.