skip to content

In Express 5, how do you send 201 with a Location header on create and 204 on delete, and what do response helpers add?

level: middleimportance: should knowfreq 50%

answer

  1. status first, then the body
  2. res.location for the new URL
  3. 204 drops the body
  4. integers only in res.status

basics

~10 s

Chain the status before the body: res.status(201).location(url).json(order) on create, res.sendStatus(204) or res.status(204).end() on delete. A helper fixes each pairing once, so no route forgets the Location header or sends a body with 204.

solid answer

~40 s

On create: `res.status(201).location(req.baseUrl + '/' + order.id).json(order)` — `res.status` sets the code and returns `res`, `res.location` sets the `Location` header, `res.json` sends. On delete: `res.sendStatus(204)` or `res.status(204).end()`. Express's `res.send` strips the body and `Content-Type` for a 204, so `res.status(204).json(x)` sends nothing and hides the mistake. Express 5 is also stricter: `res.status` throws unless it gets an integer from 100 to 999, so a status held as the string `'201'` throws a `TypeError`, and the removed 4.x forms fail quietly — `res.send(201)` now sends `201` as a JSON body with status 200, and `res.json(obj, 201)` ignores the 201. Small helpers such as `sendCreated(res, location, body)` and `sendNoContent(res)` make each pairing one tested call.

code

javascript · 27 lines
javascript
const express = require('express');

const sendCreated = (res, location, body) => res.status(201).location(location).json(body);
const sendNoContent = (res) => res.status(204).end();

const store = new Map();
let nextId = 1;
const orders = express.Router();

orders.post('/', (req, res) => {
  const order = { id: nextId++, ...req.body };
  store.set(String(order.id), order);
  sendCreated(res, `${req.baseUrl}/${order.id}`, order);
});

orders.delete('/:id', (req, res) => {
  if (!store.delete(req.params.id)) return res.status(404).json({ error: 'not_found' });
  sendNoContent(res);
});

const app = express();
app.use(express.json());
app.use('/v1/orders', orders);

module.exports = app;
// POST /v1/orders -> 201, Location: /v1/orders/1
// DELETE /v1/orders/1 -> 204, no body

go deeper

for a junior

Recall that res.status sets the code and returns res, so it chains before res.json, and that res.sendStatus sends a status with its standard text.

for a middle

Explain how 201 with res.location and 204 with res.end are written, why a body sent with 204 disappears, and what Express 5 does with the removed res.send(status) and res.json(obj, status) forms.

for a senior

Show the upgrade judgment: find the silent 4.x signatures, guard error handlers against non-integer statuses, derive Location from req.baseUrl, and prove each route's status with HTTP tests.

for a principal

Weigh thin per-status helpers against inline res calls or a generic send helper: what consistency they buy, what they hide from newcomers, and how a team keeps routes on them.

## Status first, body second An Express response is sent by one of the **terminal methods** — `res.json`, `res.send`, `res.end`, `res.sendStatus` — and everything about the status line and headers has to be set before that call. The setters return `res`, so they chain: - `res.status(code)` sets `res.statusCode` and returns `res`. - `res.location(path)` sets the `Location` header, URL-encoding the value. - `res.set(name, value)` sets any other header. - `res.json(body)` serialises the body, sets `Content-Type: application/json` and ends the response. Which status each operation deserves — 201 for a create, 204 for a delete with nothing to say, 200 for a read — is HTTP and REST material. This answer is how an Express route actually emits the code it chose. ## 201 Created with Location A create route answers **201** and points at the new resource with a `Location` header: ```js res.status(201).location(req.baseUrl + '/' + order.id).json(order); ``` Building the URL from `req.baseUrl` rather than a literal `/v1/orders` keeps it right if the router is mounted under another prefix. `res.status(201)` alone does **not** add `Location`; nothing in Express infers it. ## 204 No Content A delete route that returns nothing answers **204**: 1. `res.sendStatus(204)` sets the code and sends the status message as the body — but for 204 the body is dropped. 2. `res.status(204).end()` ends the response with no body at all. `res.send`, which `res.json` calls, **removes `Content-Type`, `Content-Length` and `Transfer-Encoding` and empties the body** whenever the status is 204 or 304. So `res.status(204).json({ deleted: true })` sends a bare 204: no error, no body, and a client that expected the JSON gets nothing. If the client needs a body, the route needs 200. ## What Express 5 removed or tightened | Call | Express 4 | Express 5 | |---|---|---| | `res.send(201)` | deprecated; sent status 201 | sends the number `201` as a JSON body with status 200 | | `res.json(obj, 201)` | deprecated; used 201 as the status | ignores the second argument; status 200 | | `res.status('201')` | deprecated for non-integers | throws `TypeError: Invalid status code` | | `res.status(1000)` | passed to Node | throws `RangeError`; only 100 to 999 are accepted | The replacements are the chained forms: `res.status(201).send(body)`, `res.status(201).json(obj)`, and `res.sendStatus(code)` for a status with its standard text. The silent rows are the dangerous ones in an upgrade: the route still returns 200 and only a test of the status code notices. ## What a response helper adds A **response helper** is a small function that wraps one pairing: ```js const sendCreated = (res, location, body) => res.status(201).location(location).json(body); const sendNoContent = (res) => res.status(204).end(); ``` - Every create route sets 201 **and** `Location` the same way; nobody forgets the header. - No delete route can accidentally attach a body that Express would drop. - The status code stays visible at the call site through the helper's name, so the per-route choice is still explicit. - If the service wraps bodies in an envelope, the helper is the one place it is applied. Helpers should stay thin. One that takes a status as a parameter, `send(res, status, body)`, brings back every mistake it was meant to remove, including passing a string status to `res.status`. ## Reading the status back The code a route chose is visible on `res.statusCode` until the response finishes, which is how request loggers report it; `res.headersSent` says whether it can still be changed. Neither changes anything on its own: once a terminal method has run, a later `res.status()` only rewrites a number nobody will send. In a route, set the code and headers first, call one terminal method, and `return` from every branch that responded, so two branches never both try to answer. ## Pitfalls - Setting the status after the body: `res.json(order); res.status(201)` — the 200 already went out. - `res.status(err.status)` in an error handler when `err.status` is undefined: Express 5 throws a `TypeError` from inside the handler; write `res.status(err.status ?? 500)`. - Hard-coding `/v1/orders` in `Location` instead of deriving it from `req.baseUrl`. - Trusting a route's status without a test; the removed 4.x forms keep working, just wrongly. - Mixing styles: half the routes on the helpers and half on inline calls is worse than either alone, because readers can no longer assume the helper was used.

  • How would you catch a route that answers 200 where the contract says 201?
    Assert it in an HTTP-level test: call the route through the exported app and check the status and the `Location` header together. A helper narrows the surface, but only a test proves each route calls the right one. A lint rule that flags bare `res.status(201)` outside the helper module keeps new routes on the helper.
  • What does res.status(err.status) do in Express 5 when err.status is undefined?
    It throws a `TypeError`, because Express 5's `res.status` rejects anything that is not an integer. Thrown inside an error handler, that new error is forwarded to the next error handler, or to Express's default one, in place of the original. Default it explicitly, `res.status(err.status ?? 500)`, or check the value first; Express 4 only deprecated non-integer arguments.

  • Calling res.send(201) in Express 5 and expecting a 201 status.
  • Passing the status code as the second argument of res.json.
  • Sending a JSON body with 204 and assuming the client receives it.
  • Passing a status held as a string, such as '201', to res.status.
  • Expecting res.status(201) to set the Location header by itself.

Assumes Express 5: res.status accepts only integers from 100 to 999, and the 4.x forms res.send(status) and res.json(obj, status) are gone.