skip to content

In Express 5, how do res.format, res.redirect and res.render let one route answer browsers with HTML and API clients with JSON?

level: middleimportance: should knowfreq 30%

answer

  1. negotiate on Accept
  2. first key when no header
  3. 406 through next(err)
  4. 302 unless you pass a status
  5. view engine plus views folder

basics

~20 s

res.format picks a callback by the Accept header, so an html branch can redirect or render while a json branch calls res.json. res.redirect defaults to 302 and takes a status first; res.render needs a view engine and sends 200 HTML.

solid answer

~40 s

`res.format({ html() {...}, json() {...} })` uses `req.accepts` on the object's keys, sets the chosen `Content-Type` and adds `Vary: Accept`. With no `Accept` header the first callback runs; when nothing matches it calls the `default` callback, or forwards a 406 error through `next(err)`. In the html branch, `res.redirect(303, '/orders/42')` sends the browser on, since `res.redirect` defaults to 302 and takes the status before the URL; or `res.render('order', locals)` renders a view. `res.render` needs the `'view engine'` setting (or a file extension) and templates under the `'views'` directory, merges `app.locals`, `res.locals` and the passed locals, and sends 200 HTML. With a callback it sends nothing; without one, a render error reaches error-handling middleware.

code

javascript · 18 lines
javascript
const express = require('express');
const app = express();

app.use(express.json());
app.use(express.urlencoded({ extended: false }));

app.post('/orders/:id/notes', (req, res) => {
  res.format({
    html() {
      res.redirect(303, `/orders/${req.params.id}`); // browser follows with GET
    },
    json() {
      res.status(201).json({ orderId: req.params.id, note: req.body?.text });
    },
  }); // any other Accept -> next() with a 406 error
});

app.listen(3000);

go deeper

for a junior

Recall that res.redirect defaults to 302 and that res.render needs a view engine and a views directory.

for a middle

Explain how res.format selects by Accept, what happens with no header or no match, and how render locals merge.

for a senior

Use 303 after form posts, keep key order deliberate, handle the 406 path in error middleware, and keep user input out of view names and redirect targets.

for a principal

Decide whether one route should serve both browsers and API clients or whether HTML and JSON surfaces stay separate, and what each choice costs to test.

## The scenario A form-and-JSON endpoint, `POST /orders/:id/notes`, is used by two clients. A browser submits an HTML form and expects to land on the order page. A script sends JSON and expects `201` with a JSON body. Express gives one route the tools to serve both: `res.format` to choose, `res.redirect` and `res.render` for the browser, and `res.json` for the script. ## `res.format`: choosing a branch `res.format(obj)` performs content negotiation on the request's `Accept` header: - **Keys** are MIME types (`'application/json'`) or extension names (`json`, `html`, `text`). A key named `default` is special. - **Selection** uses `req.accepts()` over the keys, honouring quality values, so `Accept: text/html,application/json;q=0.9` picks `html`. - **No `Accept` header** runs the first callback, and `Accept: */*` matches the first key as well, so key order is a decision. - **The chosen type** is set as `Content-Type`, and `Vary: Accept` is added so caches keep the variants apart. A callback can still override the type. - **No match** calls `default` if you supplied one; otherwise Express calls `next()` with a 406 error whose `types` property lists what was offered. Your error middleware, or the default handler, answers it. Each callback receives `(req, res, next)`, so it is an ordinary place to respond. ## `res.redirect`: sending the browser on `res.redirect([status,] path)` sets `Location` and ends the response: | Call | Status | Use | |---|---|---| | `res.redirect('/orders/42')` | 302 Found (the default) | a generic temporary redirect | | `res.redirect(303, '/orders/42')` | 303 See Other | after a form POST, so the browser follows with GET | | `res.redirect(301, '/new-path')` | 301 Moved Permanently | a permanent move | Details worth knowing: - The **status comes first**; there is no `(url, status)` form in Express 5. - The path can be absolute, root-relative or relative to the current URL, and Express encodes it into `Location`. - The body is negotiated too: a short text or HTML note for clients that accept them, empty otherwise, and none for `HEAD`. - Redirecting to a URL taken from user input is an open-redirect risk; the Express security guide shows checking the target host before calling it. ## `res.render`: an HTML view `res.render(view, locals, callback)` hands a template to a view engine and, by default, sends the result: 1. **Configure** the directory with `app.set('views', ...)` (it defaults to a `views` folder in the application root) and the engine with `app.set('view engine', ...)`. Without a view engine, the view name must carry its file extension, or the render fails with `No default engine was specified and no extension was provided.` 2. **Engines** are Express-compatible packages that export `__express(filePath, options, callback)`, or functions you register with `app.engine(ext, fn)`. 3. **Locals** are merged in order: `app.locals`, then `res.locals`, then the object you pass, with later ones winning. 4. **Sending**: without a callback, a successful render goes out through `res.send` as `text/html` with status 200 unless you set another, and an error such as `Failed to lookup view "order"` is passed to `next(err)`. With a callback, Express sends nothing; you call `res.send(html)` yourself. Express 5 also invokes the render callback asynchronously for every engine, removing bugs from engines that called back synchronously. Never build the view name from user input: it is a file path the engine will read and evaluate. ## Gotchas when one route serves both - **Key order is behaviour.** Clients that send `*/*`, such as many command-line tools, get the first key. Put the representation you want as the fallback first. - **Extension keys are shorthand.** `json` maps to `application/json` and `html` to `text/html`, so `{ json() {}, html() {} }` and the full MIME keys behave the same. - **Errors need both shapes too.** A validation failure in the json branch should answer JSON, while the html branch typically re-renders the form; a single error handler can call `res.format` again to choose. - **Locals are not a dumping ground.** The Express documentation warns that `locals` keys should not contain user-controlled input, because they can change how a view engine behaves or open a cross-site scripting path. ## Putting it together - The **html** branch redirects with 303 after a successful POST, or renders the form again with errors. - The **json** branch answers `res.status(201).json(...)`. - A client asking for neither gets a 406 through the error handler, unless a `default` branch decides otherwise. Escaping, layouts and template caching are the template engine's concerns and are covered with server-side template rendering in general.

  • In Express 5, what happens when res.format is called and the request's Accept header is image/png?
    None of the keys match, so Express calls the `default` callback if the object has one. Otherwise it calls `next()` with a 406 Not Acceptable error whose `types` property lists the offered media types, and error-handling middleware or the default handler sends the response. `Vary: Accept` is set either way.
  • Why would res.render('order', locals, cb) leave the request hanging?
    Passing a callback tells Express not to send the rendered HTML itself. The callback receives `(err, html)`, and unless it calls `res.send(html)`, or `next(err)` on failure, no response is ever written and the client waits until a timeout.

  • res.format answers 406 itself before calling any callback
  • res.redirect defaults to 301 Moved Permanently
  • res.render works without a view engine or file extension
  • Passing a callback to res.render still sends the HTML automatically
  • res.format picks the last key when no Accept header is sent