In an Express 5 JSON API, why does an unmatched route return an HTML 'Cannot GET' page, and how do you send a JSON 404?
answer
- no middleware answered
- the final handler's default page
- app.use with no path, after routers
- forwarded 404s need a later error handler
basics
~10 sWhen no middleware or route responds, Express's final handler sends a 404 HTML page reading Cannot GET /path. Register app.use((req, res) => res.status(404).json(...)) after every router so unmatched requests get JSON.
solid answer
~40 sAn unmatched request is not an error: Express ran every layer, none responded, and its built-in final handler answered with status 404 and a small HTML page, `Cannot GET /v1/nope`. A four-argument error handler never sees it, because nothing called `next(err)`. The fix is a plain middleware registered after all routers, `app.use((req, res) => res.status(404).json({ error: 'not_found' }))`, or `v1.use(...)` at the end of the version router to scope it to the API. If it forwards instead — `next(err)` with `err.status = 404`, so the central error handler shapes the body — it must be registered before that error handler, or the error reaches Express's default HTML handler. In Express 5 use `app.use` with no path: the Express 4 idiom `app.all('*', ...)` throws at startup.
code
javascript · 24 linesconst express = require('express');
const app = express();
const v1 = express.Router();
v1.get('/orders', (req, res) => res.json([]));
v1.use((req, res) => {
res.status(404).json({ error: 'not_found', path: req.originalUrl });
});
app.use('/v1', v1);
app.use((req, res, next) => {
const err = new Error('Not Found');
err.status = 404;
next(err);
});
app.use((err, req, res, next) => {
if (res.headersSent) return next(err);
res.status(err.status ?? 500).json({ error: err.message });
});
module.exports = app;
// GET /v1/nope -> 404 {"error":"not_found","path":"/v1/nope"}
// GET /nope -> 404 {"error":"Not Found"}go deeper
Know that Express sends its own HTML 404 when no route responds, and that a path-less app.use middleware placed after all routes replaces it with your JSON.
Explain why error middleware never sees an unmatched request, how the final handler produces the page, and why a forwarded 404 must sit before the error handler.
Spot the upgrade and ordering traps: app.all('*') throwing under Express 5's route syntax, a 404 middleware mounted too early, wrong methods surfacing as 404, and HTML leaking from a misplaced fallback.
Decide where not-found handling lives in a house layout: per version router, app-wide, or both, and whether 404s always flow through the shared error handler so one body format covers every failure.
## Why Express answers with HTML Express handles a request by walking its stack of middleware and routes in registration order. Each layer either responds or calls `next()`. When the walk reaches the end and **no layer has responded**, Express hands the request to its **final handler** (the `finalhandler` package, created inside `app.handle`). With no error pending, that handler answers **404** with a minimal HTML document whose body reads `Cannot GET /v1/nope` — method and path filled in. The Express FAQ puts it directly: a 404 is not the result of an error, so error-handling middleware does not capture it. The four-argument `(err, req, res, next)` handlers only run when something calls `next(err)`, throws, or (in Express 5) returns a rejected promise. An unmatched URL does none of those. For a JSON API the HTML page is wrong in two ways: clients that parse every response as JSON choke on it, and the body shape differs from every other error the API returns. ## Adding a JSON 404 The fix is an ordinary middleware with no path, registered **after every router and route**: ```js app.use((req, res) => { res.status(404).json({ error: 'not_found', path: req.originalUrl }); }); ``` Because it is last among the non-error layers, it only runs when nothing before it responded. `req.originalUrl` gives the full path, even when the middleware sits inside a mounted router. ## Where it goes relative to the error handler There are two ways to write the 404 middleware, and they place it differently: | Style | What it does | Position that works | |---|---|---| | Respond directly | `res.status(404).json(...)` | anywhere after the routers | | Forward | `next(err)` with `err.status = 404` | after the routers **and before** the error handler | Errors only travel forward through the stack. A forwarded 404 created after the error handler finds no error handler ahead of it, so Express's final handler answers — with its **default HTML error page** and status 404, which is exactly what the change was meant to remove. Forwarding is still the better style when the error handler owns the one JSON error format; it just has to come first. ## What the default page does and does not reveal For an unmatched request the final handler's page carries only the method and path, so it leaks little; the problem is format, not secrets. A forwarded error is different: when the final handler answers an error and the `env` setting is not `production`, the page shows the error's stack trace. That is one more reason a forwarded 404 must reach your own error handler rather than fall through to the default one. ## Scoping the 404 to the API A not-found middleware is scoped by **where it is mounted**: - `v1.use((req, res) => ...)` at the end of the version router catches only unmatched paths under `/v1`, so API clients always get JSON. - An app-level fallback after everything else covers the rest — static files, pages, other mounts — with whatever they need. - Both are plain middleware; nothing marks either as "the 404 handler" except its position. ## Express 5 pitfalls - **`app.all('*', ...)` throws at startup.** Express 5 uses path-to-regexp v8, where a wildcard must be named: `/*splat`, or `/{*splat}` to include the root. The bare `*` fails with `Missing parameter name`. A path-less `app.use(...)` needs no pattern at all. - **Registered too early**, before the routers, it answers every request with 404. - **A wrong method is a 404 too.** Express matches method and path together and does not send 405 on its own; `POST` to a GET-only path falls through like any unmatched URL. Add 405 explicitly where the contract needs it, for example with `router.route('/orders').get(list).all((req, res) => res.sendStatus(405))`. - **Forgetting the status**: `res.json({ error: 'not_found' })` alone sends 200. - **Swallowing real 404s**: a route that finds no record should still answer 404 itself, or call `next()` only if falling through to the not-found middleware is really what it means. Whether to say 404 or 405, and what the error body contains, are HTTP and REST design questions; the Express part is putting a middleware at the right position in the stack.
- Why does POST /v1/orders return 404 when only GET /v1/orders exists?Express matches method and path together. When no route accepts POST for that path, the request falls through every layer like any unmatched one, so the 404 middleware or the final handler answers. Express does not send 405 by itself; where the contract needs it, add it, for example `router.route('/orders').get(list).all((req, res) => res.sendStatus(405))`.
- Why put the JSON 404 at the end of the v1 router rather than only at the end of the app?A `v1.use(...)` at the end of the version router only catches unmatched paths under `/v1`, so API clients always get the API's JSON while the rest of the app — pages, static files, other mounts — keeps its own not-found behaviour from an app-level fallback. Both are ordinary middleware; their position in the stack is what scopes them.
Like a switchboard where no extension picked up: the phone company plays its generic recording. A 404 middleware is your own recording, placed after every extension so it only plays when nobody answered.
- Expecting the four-argument error handler to catch unmatched routes.
- Registering the 404 middleware before the routers, so every request 404s.
- Using app.all('*') as the catch-all route in Express 5.
- Forwarding the 404 with next(err) to an error handler registered earlier.
- Expecting Express to send 405 by itself for a wrong method.
Assumes Express 5: the Express 4 catch-all app.all('*') now throws at startup under path-to-regexp v8; the final handler's 404 behaviour is unchanged.