TExcelTAD
Home › Express & NestJS › Status Codes & Headers

Status Codes & Headers

The status code is the first thing a client checks: it decides whether the body is data or an error. Headers carry everything else — content type, caching rules, redirects, rate limits. Getting both right makes your API predictable for every client.

Status code families

Range Meaning Most used
1xx informational rarely used directly
2xx success 200 OK, 201 Created, 204 No Content
3xx redirection 301 Moved Permanently, 302 Found, 304 Not Modified
4xx client made a mistake 400, 401, 403, 404, 409, 422, 429
5xx server failed 500 Internal Server Error, 503 Service Unavailable

Choosing the right code

Situation Code
successful read 200
resource created by POST 201 + Location header
successful DELETE with no body 204
malformed input (bad JSON, wrong type) 400
not logged in / bad token 401
logged in but not allowed 403
resource does not exist 404
method not supported on this path 405
conflict (duplicate email, version mismatch) 409
well-formed but semantically invalid input 422
too many requests 429 + Retry-After
unexpected bug 500
maintenance / dependency down 503

Tip: 401 means "who are you?" and 403 means "I know who you are, and you can't do this". Mixing them up is one of the most common API mistakes.

Setting codes in Express

node · try it yourself
const express = require('express');

const app = express();
app.use(express.json());

const items = new Map();
let nextId = 1;

app.post('/items', (req, res) => {
  const item = { id: nextId++, name: req.body?.name };
  items.set(item.id, item);
  res.status(201).location(`/items/${item.id}`).json(item);
});

app.delete('/items/:id', (req, res) => {
  const deleted = items.delete(Number(req.params.id));
  res.sendStatus(deleted ? 204 : 404);
});

const server = app.listen(0, async () => {
  const base = `http://localhost:${server.address().port}`;
  const created = await fetch(base + '/items', {
    method: 'POST',
    headers: { 'Content-Type': 'application/json' },
    body: JSON.stringify({ name: 'lamp' }),
  });
  console.log(created.status, created.headers.get('location'), await created.text());

  const del = await fetch(base + '/items/1', { method: 'DELETE' });
  console.log(del.status, JSON.stringify(await del.text()));

  const again = await fetch(base + '/items/1', { method: 'DELETE' });
  console.log(again.status, await again.text());
  server.close();
});
201 /items/1 {"id":1,"name":"lamp"}
204 ""
404 Not Found

res.sendStatus(204) sends no body at all, as the HTTP spec requires for 204.

Note: Express 5 validates status codes. res.status(999) or res.status('200') throws a RangeError/TypeError instead of silently sending garbage.

Reading and writing headers

node · try it yourself
const express = require('express');

const app = express();
app.disable('x-powered-by'); // don't advertise the framework

app.get('/report', (req, res) => {
  res.set({
    'Cache-Control': 'no-store',
    'X-Report-Version': '3',
  });
  res.append('Vary', 'Accept');
  res.append('Vary', 'Accept-Language');
  res.type('text/csv').send('id,total\n1,99\n');
});

const server = app.listen(0, async () => {
  const res = await fetch(`http://localhost:${server.address().port}/report`);
  for (const name of ['content-type', 'cache-control', 'x-report-version', 'vary', 'x-powered-by']) {
    console.log(name.padEnd(16), res.headers.get(name));
  }
  server.close();
});
content-type     text/csv; charset=utf-8
cache-control    no-store
x-report-version 3
vary             Accept, Accept-Language
x-powered-by     null
Method Use
res.set(name, value) set (replace) a header
res.append(name, value) add another value to a header
res.get(name) read a response header you set
res.type(t) shortcut for Content-Type
res.location(url) set Location
res.vary(field) add to Vary
res.attachment(name) Content-Disposition: attachment; filename=…

ETags and 304 Not Modified

Express adds a weak ETag to res.send/res.json responses. When the client sends it back in If-None-Match and the content hasn't changed, Express answers 304 with an empty body — saving bandwidth automatically:

node · try it yourself
const express = require('express');

const app = express();
app.get('/catalog', (req, res) => res.json({ products: ['pen', 'ink', 'paper'] }));

const server = app.listen(0, async () => {
  const url = `http://localhost:${server.address().port}/catalog`;
  const first = await fetch(url);
  const etag = first.headers.get('etag');
  console.log('first :', first.status, (await first.text()).length, 'bytes');

  // fetch would add "Cache-Control: no-cache" to conditional requests; a browser revalidating sends max-age=0
  const second = await fetch(url, { headers: { 'If-None-Match': etag, 'Cache-Control': 'max-age=0' } });
  console.log('second:', second.status, (await second.text()).length, 'bytes');
  server.close();
});
first : 200 34 bytes
second: 304 0 bytes

Note: A request carrying Cache-Control: no-cache always gets a full 200 — the client is explicitly asking not to reuse its copy. That's why the example sets max-age=0, the header browsers send when revalidating.

Responding 405 with an Allow header

Express answers wrong methods with 404 by default. For APIs, 405 is more precise:

js
app.route('/items')
  .get(listItems)
  .post(createItem)
  .all((req, res) => res.set('Allow', 'GET, POST').sendStatus(405));

Test yourself

Which status should a successful POST that creates a resource return?

  1. 200
  2. 201
  3. 202
  4. 204

A logged-in user tries to delete someone else's post. Which code fits?

  1. 400
  2. 401
  3. 403
  4. 404

What does res.append('Vary', 'Accept') do differently from res.set?

  1. Nothing
  2. It adds a value instead of replacing the header
  3. It only works for cookies
  4. It sends the response