skip to content

An Express 5 API mounts auth, then cors, then morgan, then express.json, so preflights get 401, rejected calls go unlogged and auth sees no body; what order fixes it?

level: seniorimportance: must knowfreq 62%

answer

  1. registration order is execution order
  2. who answers before whom
  3. a preflight carries no credentials
  4. logger first, parser before readers

basics

~20 s

Express runs app.use middleware in registration order, so mount morgan first, then helmet and cors, then express.json, then auth, then routes. Preflights are then answered before auth, 401s get logged, and auth reads a parsed req.body.

solid answer

~40 s

Express walks `app.use` layers in registration order, and a layer that responds ends the walk; each symptom is one inversion. Auth before `cors()`: a browser preflight is an `OPTIONS` request without credentials, so auth answers 401 before `cors()` can reply, and real 401s also lack `Access-Control-Allow-Origin`. morgan after auth: requests auth rejects end before morgan runs, so they never get a log line. `express.json()` after auth: in Express 5 `req.body` is `undefined` until a parser has run, so `req.body.apiKey` throws and the request fails with a 500. The fix is morgan, `helmet()`, `cors()`, `express.json()`, auth, routes, then error handlers. morgan still records the final status because it writes its line when the response finishes.

code

javascript · 24 lines
javascript
const express = require('express');
const morgan = require('morgan');
const helmet = require('helmet');
const cors = require('cors');

const app = express();

function requireApiKey(req, res, next) {
  const key = req.body?.apiKey;
  if (!key || key !== process.env.API_KEY) return res.sendStatus(401);
  next();
}

app.use(morgan('combined'));                          // 1. sees every request, writes on finish
app.use(helmet());                                    // 2. security headers on every later response
app.use(cors({ origin: 'https://app.example.com' })); // 3. answers preflights itself
app.use(express.json());                              // 4. req.body exists before anyone reads it
app.use('/api', requireApiKey);                       // 5. auth reads the parsed body
app.post('/api/orders', (req, res) => res.status(201).json({ created: true }));

console.log(app.router.stack.map((layer) => layer.name));
// [ 'logger', 'helmetMiddleware', 'corsMiddleware', 'jsonParser', 'requireApiKey', 'handle' ]

app.listen(3000);

go deeper

for a junior

Recall that Express runs app.use middleware top to bottom and that a layer which responds stops everything after it.

for a middle

Explain why cors must precede auth, why the logger goes first yet still sees the final status, and why parsers precede readers of req.body.

for a senior

Diagnose from symptoms alone: map 401 preflights, missing log lines and an undefined body to the specific inversions, and verify the live order through app.router.stack.

for a principal

Decide where a team defines the stack: one shared bootstrap module that fixes the order for every service, versus per-service wiring that drifts but adapts to each service's needs.

## Registration order is execution order The Express guide puts it bluntly: "middleware functions that are loaded first are also executed first." Every `app.use()` call appends a layer to the app's router, and for each request the router tries those layers top to bottom. A layer that sends a response and does not call `next()` **ends the walk**, so nothing registered after it runs for that request. Most ordering bugs are therefore about *who gets to answer before whom*, and each symptom in this scenario maps to one inversion. ## Symptom by symptom | Symptom | Cause in the broken order | Mechanism | |---|---|---| | Browser preflights fail with 401 | Auth is mounted before `cors()` | A preflight is an `OPTIONS` request the browser sends without the app's credentials; auth rejects it before `cors()` runs | | Even genuine 401s are unreadable in the browser | Same inversion | Responses sent by auth never pass through `cors()`, so they lack `Access-Control-Allow-Origin` | | Rejected calls missing from the access log | morgan is mounted after auth | Requests auth ends never reach the layer that would have logged them | | Auth sees no body | `express.json()` is mounted after auth | In Express 5 `req.body` is `undefined` until a body parser has run, so `req.body.apiKey` throws a `TypeError` | The last one fails loudly rather than quietly. The router catches the synchronous `TypeError` and forwards it as `next(err)`, so the client gets a 500 from the error handler instead of a clean 401. ## The corrected stack 1. **Request logger** (`morgan(...)`) first, so every request, including the ones later layers reject, gets a line. 2. **Security headers** (`helmet()`) next, so its headers are set before any later layer can answer. 3. **CORS** (`cors(...)`) before anything that can reject, so preflights are answered and every later response carries the CORS headers. 4. **Body parsers** (`express.json()`, `express.urlencoded()`) before any middleware that reads `req.body`. 5. **Authentication**, which can now read the parsed body and whose 401s are logged and CORS-readable. 6. **Routers and routes.** 7. **A 404 handler, then the four-argument error handlers**, registered last; their details belong to the error-handling material. ## Why each position works - **morgan first still sees the final status.** Position decides *which* requests morgan sees, not *when* it writes. With the default `immediate: false`, it notes the start time and writes the line when the response finishes, so the 401 auth sends later is logged with its status and timing. Its `:url` token reads `req.originalUrl`, so the full path is logged even for requests that end up inside mounted routers. - **helmet near the top** sets its headers with `res.setHeader` when it runs. A response sent by a layer registered above it goes out without them. - **cors before auth.** With its default `preflightContinue: false`, the cors middleware answers a preflight itself, with status 204 by default, and never calls `next()`, so auth never sees it. For ordinary requests it sets `Access-Control-Allow-Origin` and calls `next()`, so a 401 sent later still carries the header. - **express.json before readers.** The parser reads the stream and sets `req.body`. It also rejects bodies over its default `limit` of `'100kb'` with a 413 and malformed JSON with a 400, both forwarded as errors. Mounted first, those failures are also logged by morgan. - **auth after parsing, before routes.** It is the first layer that needs a parsed request and the last one before business logic. ## Checking the order you actually have - Express 5 exposes the base router again as `app.router`, so `app.router.stack.map((layer) => layer.name)` prints the stack in order: names such as `logger`, `helmetMiddleware`, `corsMiddleware`, `jsonParser` and your own named functions. Anonymous arrow functions print as `<anonymous>`, which is a reason to name middleware. - Remember that `app.use()` calls spread across modules still land in one stack, in the order the modules ran. - A test that sends a preflight without credentials and a rejected request, and then asserts the CORS header and the log line, catches a regression in either inversion. ## Scoping without breaking order Not every layer has to be global. Mount `express.json()` on the routers that accept bodies and auth on the `/api` subtree with `app.use('/api', auth)`. Scoping changes *which paths* a layer covers, not the rule that a layer registered earlier runs earlier for the paths it does cover.

  • Why does morgan mounted first still log the status of a request that auth rejects later?
    morgan's default is `immediate: false`: when the request passes through it, morgan records the start time and arranges to write the line once the response has finished. By then auth has sent its 401, so the line carries the real status, size and response time. Mounting position only decides which requests morgan sees.
  • How can you print the effective middleware order of an Express 5 app?
    Express 5 exposes the base router as `app.router` again, so `app.router.stack.map((layer) => layer.name)` lists every layer in order. Each name comes from the function's name, so named middleware is readable and anonymous arrow functions show up as `<anonymous>`.
  • What changes if `express.json()` is mounted only on the router that accepts bodies?
    Other paths skip the parser entirely, so their `req.body` stays `undefined` in Express 5. Any app-wide middleware that reads `req.body` must then either run inside that router after the parser or tolerate a missing body, for example with optional chaining.

  • Middleware order in Express does not matter as long as it is all registered before app.listen().
  • morgan must be mounted last so it can see the final status code.
  • cors can go after auth because the browser sends the Authorization header on the preflight.
  • Express parses the body lazily the first time req.body is read.
  • In Express 5, req.body defaults to an empty object, so reading a field before parsing is safe.

Assumes Express 5: req.body is undefined until a body parser has run (the migration guide records Express 4 returning {}), and app.router is back as the base router.