Express security: middleware order, the defaults to check, and what each request passes through
Express calls itself a routing and middleware web framework with minimal functionality of its own.
On this guide's reading, an Express application's security therefore lives in the middleware it adds, the order it adds them in and the defaults it changes. This guide works through each position from the settings to the error handler, the Express advisories to check your versions against, and a middleware-order test matrix with a local lab you can run.
In this guide
Express middleware-order test matrix with a local ordering lab
Twelve blocks: a mount list of your own code, one block per position from the settings to the error handler with what the Express and middleware documentation says, what moving the layer changes and what to record, and a block for versions and advisories. A worked example and a local lab with eight fixtures follow, the lab's files and output copied in from a real run.
express.txt
Introduction16 lines
Part A. The matrix161 lines
Part B. Worked example: the lab's own stack16 lines
Part C. The local ordering lab620 lines
Whole template821 lines
EXPRESS MIDDLEWARE-ORDER TEST MATRIX, WITH A LOCAL ORDERING LAB
ILLUSTRATION AND TEMPLATE. Part A is a blank matrix to copy into a ticket or a spreadsheet: a mount list of your own code, then one block per position, from the settings to the error handler. Part B fills in the mount list for the lab's own invented stack, as a worked example. Part C is a local lab: an invented middleware runner written for this page and run on 127.0.0.1, with fixtures for malformed JSON, a cross-origin credentialed request and production error responses. The lab is not Express and holds no code from Express or from any middleware package. Every line in Part A under Documentation or under Earlier or later comes from that project's own documentation, named on the line, as read on 14 November 2026; the lines under This page's reading are this guide's inferences from them.
Every check in Part A is read-only and run by the application's owner or their developer, on code and systems they control. Reading the code, the lockfile, the configuration and your own logs changes nothing. Where a line asks you to send a request, send it to a local copy of your application or to the lab, never to production and never to a system you do not own. On production, a line asks only for what your own browser receives while you use your own site in the ordinary way. Where a source describes a step that changes your application, such as adding a test endpoint, no line here asks for it: leave it for a planned change. Record the names of secrets and environment variables, never their values.
HOW TO FILL IT
- Start with the mount list in A0. Every later block refers to its line numbers.
- Each block gives what the documentation says the layer does, what the documentation says about running it earlier or later, this page's reading (marked as such), what to record from your application, and the lab fixture that shows the move, where there is one.
- Where you cannot answer a line, write "unknown" and add it to the findings log as something to find out.
- "Source" names the document that says it. "This page's reading" is advice from this guide, not a rule from Express or a middleware's authors.
Application:
Commit or build checked:
Express major version (from the lockfile):
Completed by (name and role): Date:
PART A. THE MATRIX
A0. THE MOUNT LIST
Write every app.set, app.enable, app.disable, app.use, app.METHOD, router.use and router.METHOD call in the order it runs at start-up, including the calls inside routers and sub-apps, with the file, the line number and the mount path. Mark each line with the block it belongs to (A1 to A10), or "other".
Source: Express 5.x API reference, app.use() (middleware functions are executed sequentially, therefore the order of middleware inclusion is important; with a string path, app.use() matches that path and its subpaths, so a middleware on /apple runs for /apple/images but not /apples).
Line | File and line | Call | Mount path | Block
A1. SETTINGS, BEFORE THE FIRST MIDDLEWARE
Documentation:
- trust proxy defaults to false, which treats the app as directly facing the client. With true, the client's address is the left-most entry in X-Forwarded-For, and the guide warns that it is then important to ensure the last trusted reverse proxy removes or overwrites X-Forwarded-For, X-Forwarded-Host and X-Forwarded-Proto, otherwise it may be possible for the client to provide any value. Source: Express 5.x guide, Express behind proxies.
- The application settings reference notes that X-Forwarded-* headers are easily spoofed and the detected IP addresses are unreliable, and that sub-apps inherit trust proxy even though it has a default value. Source: Express 5.x API reference, application settings.
- x-powered-by defaults to true, which enables the "X-Powered-By: Express" header. Source: Express 5.x API reference, application settings. The production security guide shows app.disable('x-powered-by'). Source: Express production best practices: security.
- env defaults to NODE_ENV, or "development" if NODE_ENV is not set. Source: Express 5.x API reference, application settings.
- case sensitive routing and strict routing are read when the app first creates its router. Adding a route or middleware, calling app.param(), accessing app.router or handling a request can create the router, so the reference says to set them before any of those operations; changing them afterwards has no effect on routing. Source: Express 5.x API reference, application settings.
Earlier or later, per the documentation: assuming the proxy sets the X-Forwarded-For header, the express-rate-limit proxy guide says to add app.set('trust proxy', ...) right after you create the Express application. Source: express-rate-limit, Troubleshooting Proxy Issues.
This page's reading: put every setting above the first app.use, so no middleware runs under a default you meant to change.
Record:
1.1 trust proxy value, and the proxies in front of the app (load balancer, CDN, platform router), from your hosting setup:
1.2 X-Powered-By: disabled in code, removed by Helmet, or still sent:
1.3 The env value in each environment, production first, read from where that environment sets NODE_ENV or from a start-up log line that already records it:
1.4 case sensitive routing and strict routing, and the line where each is set compared with the first app.use:
Lab fixture: none. The lab has no proxy in front of it.
A2. SECURITY HEADERS (HELMET OR YOUR OWN)
Documentation:
- Helmet sets HTTP response headers. Its quick start mounts it with app.use(helmet()), its HTTP header reference gives each header's default, and each header can be disabled or configured. Source: Helmet README.
- Its default Content-Security-Policy includes default-src 'self', script-src 'self', object-src 'none' and frame-ancestors 'self', among other directives. The README says the header likely requires some configuration for your specific app, and that Helmet performs very little validation on your CSP. Source: Helmet README.
- Helmet removes the X-Powered-By header by default, and notes that Express has a built-in way to disable it. Source: Helmet README.
Earlier or later, per the documentation:
- Middleware functions loaded first are also executed first. In the guide's example, a logger loaded after the route to the root path is never reached by a request to that path, because the route handler ends the request-response cycle. Source: Express 5.x guide, Writing middleware.
- Passing anything except the string 'route' or 'router' to next() makes Express treat the request as an error and skip the remaining non-error routing and middleware functions. Source: Express 5.x guide, Writing middleware.
- Helmet's nonce example mounts a middleware that sets res.locals.cspNonce before helmet(), which reads it. Source: Helmet README.
This page's reading: any layer that answers before the headers layer sends that answer without its headers, such as express.static, a health check, a CORS preflight answered earlier, a rate-limit refusal or an error raised earlier. Mount the headers layer above all of them.
Record:
2.1 Mount-list line of helmet() or your own header code, and every option you changed:
2.2 Every layer above it that can end a response:
2.3 In your browser's developer tools (Network panel), on your own site, the response headers of a page, a static file and a 404. On a local copy, the same for a 400 from the body parser and a 500. Note any response that lacks the headers the page has:
Lab fixtures: 6, 7 and 8.
A3. CORS
Documentation:
- The cors package sets response headers; it does not block requests. Its README says the server receives and processes every request, and that CORS is not access control. Source: cors README.
- Its default configuration is origin "*", methods GET, HEAD, PUT, PATCH, POST and DELETE, preflightContinue false and optionsSuccessStatus 204. Source: cors README.
- CORS-preflight requests must never include credentials. For a preflighted request, the browser first sends an OPTIONS request and sends the actual request upon approval from the server. Source: MDN, Cross-Origin Resource Sharing (CORS).
- A successful response to a CORS-preflight request is restricted to an ok status, such as 200 or 204. Any other response either ends up not being shared or fails the preflight. Source: Fetch Standard.
Earlier or later, per the documentation: used as application-level middleware, app.use(cors()), it already handles preflight requests for all routes. Otherwise, its pre-flight section says to add a new OPTIONS handler for the route you want to support, and also shows enabling pre-flight across the board. Source: cors README.
This page's reading: mount CORS above authentication. A preflight carries no cookie, because cookies are credentials, so an authentication check above CORS refuses it, the refusal is not an ok status, and the real request is never sent. Mount it above any router whose responses a page on another origin needs to read. Its position protects nothing by itself: a request from an origin that is not listed still reaches your routes.
Record:
3.1 Mount-list line, mount path, and whether it is app-level or per route:
3.2 The origin setting: its type (string, list, regular expression, function or true) and its values:
3.3 credentials, methods, allowedHeaders and preflightContinue:
3.4 For per-route use, each route with a matching OPTIONS handler and each without one:
3.5 From your own front end, in your browser's developer tools, the preflight's status and its Access-Control-Allow-Origin and Access-Control-Allow-Credentials values:
Lab fixtures: 3, 4 and 5.
A4. RATE LIMIT KEYED ON THE CLIENT ADDRESS
Documentation (express-rate-limit):
- By default the client's IP address is the key. If a keyGenerator returns the same value for every user, it becomes a global rate limiter. Source: express-rate-limit, Configuration.
- Behind a proxy or load balancer, the request's IP address might be the proxy's, which the guide says makes the limiter effectively a global one, blocking all requests once the limit is reached. Assuming the proxy sets the X-Forwarded-For header, the fix it gives is the trust proxy setting. Source: express-rate-limit, Troubleshooting Proxy Issues.
- The library logs ERR_ERL_PERMISSIVE_TRUST_PROXY when trust proxy is true, because Express then returns the leftmost X-Forwarded-For entry, which a client could set; ERR_ERL_UNEXPECTED_X_FORWARDED_FOR when that header arrives while trust proxy is false; and ERR_ERL_DOUBLE_COUNT when one request increments a hit count more than once. Source: express-rate-limit, Error Codes.
- The default store is the memory store, whose limits are reset when the Node.js process restarts. With passOnStoreError at its default of false, a store error goes to the Express error handler and requests are blocked, which the page calls failing closed. The default status code is 429. Source: express-rate-limit, Configuration.
Earlier or later, per the documentation: ERR_ERL_DOUBLE_COUNT names the same instance called more than once, or several instances using the same store, as causes. Source: express-rate-limit, Error Codes.
This page's reading: mount an address-keyed limiter above sessions and body parsers, so a refused request costs neither a session lookup nor a body read. Mount it below CORS if a page on another origin needs to read the 429. A limiter mounted on the whole app and again on a route can count one request twice.
Record:
4.1 Each limiter: mount-list line, mount path, windowMs, limit, keyGenerator, store and passOnStoreError:
4.2 Search your own application logs for the three ERR_ERL_ codes above. The Error Codes page says validate: false disables every check, a custom keyGenerator prevents the trust proxy and X-Forwarded-For checks, each check can also be disabled by name in the validate option, and otherwise each check runs once and then disables itself, so search the lines that follow each start-up and note how validate and keyGenerator are set. Write the date range searched and any matches:
4.3 Routes covered by more than one limiter, and whether those limiters share a store:
Lab fixture: none.
A5. SESSIONS
Documentation (express-session):
- Session data is stored on the server, and only the session ID is in the cookie. The default store, MemoryStore, is purposely not designed for a production environment. Source: express-session README.
- The cookie option defaults to path '/', httpOnly true, secure false and maxAge null, and the cookie is named connect.sid by default. Source: express-session README.
- secure: true needs HTTPS: over HTTP the cookie is not set, and behind a proxy, trust proxy needs to be set in Express. The proxy option defaults to undefined, which uses the trust proxy setting from Express. Source: express-session README.
- saveUninitialized defaults to true, which forces a new, unmodified session to be saved to the store; the README says using that default is deprecated. Source: express-session README.
- Since version 1.5.0 the module no longer needs cookie-parser, and using cookie-parser may cause issues if the secret is not the same in both. Source: express-session README.
- The production security guide advises against the default session cookie name, because it can be used to fingerprint the server. Source: Express production best practices: security.
Earlier or later, per the documentation: the README says to store or access session data through the request property req.session. Source: express-session README.
This page's reading: mount sessions below the address-keyed limiter and above authentication, which reads req.session. Mounted above express.static or a health check while saveUninitialized is true, the session layer can create and store a session for each of those requests.
Record:
5.1 Mount-list line, and the layers above it that answer without needing a session:
5.2 store, name, cookie (secure, httpOnly, sameSite, maxAge, domain), resave, saveUninitialized and proxy:
5.3 Where the secret comes from (the environment variable name only), and whether cookie-parser is also mounted, reading the same variable:
5.4 The Set-Cookie header your production site sends when you sign in to your own account, attributes only, with the value removed:
Lab: the lab's session layer reads an invented cookie and stores nothing.
A6. AUTHENTICATION AND AUTHORISATION
Documentation:
- Express describes itself as a routing and middleware web framework with minimal functionality of its own. Source: Express 5.x guide, Using middleware.
- If a parent uses path-specific middleware to protect a sub-app, the reference says to apply that middleware to the full mount path of the sub-app rather than to a narrower path inside it. Source: Express 5.x API reference, application settings.
- With case sensitive routing disabled, /Foo and /foo are treated the same; with strict routing disabled, /foo and /foo/ are. Source: Express 5.x API reference, application settings.
- next('route') skips the remaining middleware functions in a router middleware stack and passes control to the next route, and works only in middleware loaded with app.METHOD() or router.METHOD(); next('router') skips the rest of the router's middleware functions and passes control back out of the router. Source: Express 5.x guide, Using middleware.
- CORS is not access control, and the README says to use authentication and authorisation to protect your API. Source: cors README.
Earlier or later, per the documentation: in the guide's example, a logger loaded after the route to the root path is never reached by a request to that path, because the route handler ends the request-response cycle. Source: Express 5.x guide, Writing middleware.
This page's reading: every route, router and static folder mounted above the authentication check is public, whatever its path suggests. A check mounted on a narrower path than the router it guards leaves the rest of that router open. A check that calls next('route') when it should refuse hands the request to the next matching route instead.
Record:
6.1 Mount-list line of each authentication and authorisation check, with its mount path:
6.2 Every route, router and express.static above each check:
6.3 For each sub-app or router: its mount path, and the path its check is mounted on:
6.4 Every check that calls next('route') or next('router'), and where that request goes next:
6.5 case sensitive routing and strict routing (from 1.4):
Lab fixtures: 2 and 3.
A7. RATE LIMIT KEYED ON THE ACCOUNT
Documentation: a keyGenerator can return an identifier such as a username or an API key instead of the IP address. Source: express-rate-limit, Configuration.
This page's reading: an account-keyed limiter can only run below the check that establishes who the caller is. Keep it as well as the address-keyed limiter in A4, not instead of it.
Record:
7.1 Each account-keyed limiter: mount-list line, mount path, and the request property its keyGenerator reads:
Lab fixture: none.
A8. BODY PARSERS
Documentation:
- express.json() is based on body-parser and only parses requests whose Content-Type matches its type option, application/json by default. Its defaults include limit "100kb", strict true (arrays and objects only) and inflate true. req.body is undefined if there was no body to parse, the Content-Type was not matched, or an error occurred. Source: Express 5.x API reference, express().
- The reference warns that req.body's shape is based on user-controlled input, so all its properties and values are untrusted and should be validated before trusting. Source: Express 5.x API reference, express().
- body-parser errors will typically have a status, an expose property that determines whether the message should be displayed to the client, a type, and the body that was read, if available. A body that cannot be parsed gives status 400 and type 'entity.parse.failed', with the failed entity in the body property; a body over the limit gives 413 and type 'entity.too.large'. Source: body-parser README.
- The urlencoded parser's parameterLimit defaults to 1000, and a request with more parameters gets a 413; its depth option, used when extended is true, defaults to 32. The README recommends not configuring a very high limit. As of v2, req.body is left undefined when no body is parsed; in v1 it was always set to an empty object. Source: body-parser README.
Earlier or later, per the documentation: the body-parser README says adding parsers specifically to the routes that need them is, in general, the most recommended way to use it with Express. Source: body-parser README.
This page's reading: on protected routes, parse below authentication, so an anonymous caller is refused before the server reads and parses its body. A sign-in route needs its parser above its own credential check, which mounting per route allows. A route that reads req.body must sit below the parser that fills it.
Record:
8.1 Each parser: mount-list line, mount path (app, router or route), type, limit and strict; for urlencoded, extended, parameterLimit and depth:
8.2 Any verify function, and what it does with the raw body:
8.3 Protected routes whose parser sits above their authentication check:
8.4 On a local copy, the status and body your app returns for the malformed JSON in fixture 1, signed out and signed in:
Lab fixtures: 1 and 2.
A9. ROUTES, STATIC FILES AND THE 404 HANDLER
Documentation:
- In the guide's example of two routes for GET requests to the same path, the second route never gets called because the first ends the request-response cycle. Source: Express 5.x guide, Using middleware.
- express.static is built-in middleware that serves static assets such as HTML files and images. Source: Express 5.x guide, Using middleware.
- Express sends its own formatted 404 Not Found and error messages. The production security guide says these can be changed by adding your own not found handler and error handler, and its example writes both as the last app.use calls right before app.listen(). Source: Express production best practices: security.
- In the reference's example, a middleware that sends a response without calling next() does not allow the request to go beyond it, and requests never reach the route below it. Source: Express 5.x API reference, app.use().
This page's reading: a 404 handler mounted without a path answers everything that reaches it, so one mounted above a router hides that router. A second definition of a route with stricter checks never runs if an earlier one answers.
Record:
9.1 Duplicate method and path pairs, with both mount-list lines:
9.2 express.static: mount-list line, directory, and the layers above it:
9.3 The 404 handler's mount-list line, and anything mounted after it other than error handlers:
Lab fixture: 7.
A10. ERROR HANDLER
Documentation:
- Error-handling middleware takes four arguments, (err, req, res, next), and all four must be declared for Express to treat it as error-handling middleware. Source: Express 5.x guide, Using middleware.
- It is defined last, after the other app.use() and route calls. Express's built-in error handler sits at the end of the middleware stack. An error passed to next() and not handled by a custom handler is written to the client with the stack trace, which is not included in the production environment, where the body is the HTML of the status code message. Source: Express 5.x guide, Error handling.
- When the headers have already been sent, a custom handler must delegate to the default handler, which closes the connection and fails the request. Source: Express 5.x guide, Error handling.
- In Express 5, route handlers and middleware that return a promise call next(value) automatically when they reject or throw. Source: Express 5.x guide, Error handling. In Express 4, rejected promises are not passed to next automatically, including from async functions, and the 4.x guide says the unhandled rejection "crashes the process on current Node.js versions" unless the handler catches the error and passes it to Express. Source: Express 4.x guide, Error handling.
Earlier or later, per the documentation: an error skips the remaining non-error routing and middleware functions (A2), and error handlers are defined after them. Sources: Express 5.x guides, Writing middleware and Error handling.
This page's reading: an error handler mounted above the routes never sees their errors, so the built-in handler answers them. A custom handler that sends the whole error object to the client can send back what a body parser stored in the body property. Read expose before showing a message, and send nothing else from the error.
Record:
10.1 Mount-list line of each error handler, and whether each declares four arguments:
10.2 NODE_ENV in each environment (from 1.3):
10.3 On a local copy run with NODE_ENV=production, the status and body for the malformed JSON in fixture 1 (400), a body over your parser's limit (413) and a route that throws (500):
10.4 Whether the handler checks res.headersSent, and whether it reads err.expose:
10.5 Express 4 only: async route handlers with no try and catch that passes the error to next:
Lab fixtures: 1 and 8.
A11. VERSIONS AND ADVISORIES
11.1 The resolved versions of express, body-parser, helmet, cors, express-session and express-rate-limit, from the lockfile of the commit checked:
11.2 For express: each entry on the Express security updates page, and each advisory for the express package in the GitHub Advisory Database, whose range includes 11.1, with the date you read them. Where the two disagree on a version, write both down and act on the advisory's version fields, as this page does in its advisories section:
11.3 The same for body-parser and each middleware package in 11.1:
Source: Express security updates page; GitHub Advisory Database. The Node.js guide covers the runtime and npm.
FINDINGS LOG
One line per finding:
ID | Block | Finding | Evidence (mount-list line, response seen, log line, or page read and date) | Owner | Decision | Review by | Closed (date and evidence)
PART B. WORKED EXAMPLE: THE LAB'S OWN STACK
The suggested stack in Part C (ORDERS in file 1), written out as a mount list:
Line | Call | Mount path | Block
1 | securityHeaders | / | A2
2 | cors, one allowed origin, credentials | / | A3
3 | session loader | / | A5
4 | requireSignIn | /api | A6
5 | jsonBody, limit 1024 bytes | /api | A8
6 | GET /health, POST /api/notes, GET /api/report | exact paths | A9
7 | notFound | / | A9
8 | errorHandler, production or development | / | A10
A1, A4, A7 and A11 are empty: the lab has no settings, no proxy, no rate limiter and no packages.
2.2 Layers above the headers layer that end a response: none. In the headers-after-routes stack, every layer down to the routes on line 6 sits above it, including those routes (fixtures 6 and 8).
3.4 App-level, so the cors layer answers every preflight. In the auth-before-cors stack, the sign-in check sits above it (fixture 3).
6.2 Above requireSignIn on /api: nothing. /health is outside /api and public on purpose.
8.3 None in the suggested stack. In the parser-before-auth stack, the parser on /api sits above the sign-in check (fixture 2).
10.3 Production mode: 400 for malformed JSON (fixture 1) and 500 for a route that throws (fixture 8), each with a fixed message and a reference. The 413 case has no fixture.
PART C. THE LOCAL ORDERING LAB
WHAT IT IS
An illustration of ordering, written for this page. ordered-stack.mjs is a small invented middleware runner. Each layer is a plain function called in the order it was added; a layer calls next() to pass the request on or next(error) to skip ahead to the error handler, and a layer mounted on a path runs for that path and the paths below it. It is not Express, and it holds no code from Express, Helmet, cors, express-session, body-parser or express-rate-limit. Its layers stand in for Express's routing and for Helmet, cors, express-session and body-parser: a headers layer that sets three response headers, a CORS layer with one allowed origin and credentials, a session layer that reads an invented cookie, a sign-in check on /api, a JSON parser that rejects malformed bodies with error fields modelled on the ones the body-parser README documents, three routes, a 404 handler, and an error handler with a development and a production mode. The development mode writes the error's stack trace, which is what the Express guide says its built-in handler does outside production. The production mode sends a fixed message and a reference, and logs the detail.
run-fixtures.mjs starts the stack five times: the suggested order in production and development modes, and three orders that each move one layer (auth-before-cors, parser-before-auth and headers-after-routes) in production mode. It sends the request in each of eight fixtures to one or more of those stacks and prints what came back. The lab shows how this runner behaves. How Express and each middleware behave is in Part A, from their documentation.
WHAT IT NEEDS
Node.js and nothing else. The two files import only node:http and each other, and nothing is installed. The output below was recorded on Node.js v26.0.0 on macOS, the version on the machine that ran it. It is a fact about this run, not a recommendation.
WHAT IT TOUCHES
Five servers listen on 127.0.0.1 on ports the system picks, and the script closes every one before it exits. Every request goes to those servers. Nothing is written to disk. The origins, cookie, user and notes are invented, and the cookie value is not a secret.
HOW THE OUTPUT WAS CAPTURED
A small shell script ran the two steps below in the lab folder, saved each command's output and exit code to a file, and started step 2 in the background so it could be stopped by its own process id if it did not exit. It exited by itself. The text below was copied from those files by a second script. Lines in the development-mode stack traces that showed a local folder path were cut, and each cut is marked where it was made. The two scripts are not part of the lab.
SET-UP
Make an empty folder, save the two files below into it under the names shown, and run the steps under RUN IT in that folder.
==== File 1 of 2: ordered-stack.mjs ====
// ordered-stack.mjs: an invented middleware runner written for this page's
// ordering lab. It is not Express and holds no code from Express or from any
// middleware package. Each layer is a plain function, called in the order it
// was added, so moving one layer shows what that move changes.
import http from 'node:http'
// ---------- the runner ----------
// A layer mounted on a path runs for that path and anything below it, so
// '/api' covers '/api/notes' but not '/apis'.
function isPathCovered(layer, urlPath) {
if (layer.exact) return urlPath === layer.path
if (layer.path === '/') return true
return urlPath === layer.path || urlPath.startsWith(layer.path + '/')
}
// Calls each matching layer in order. A layer calls next() to pass the
// request on, or next(error) to skip ahead to the next error layer. A layer
// that throws, or returns a promise that rejects, counts as next(error).
function runLayers(layers, req, res) {
let position = 0
function next(error) {
while (position < layers.length) {
const layer = layers[position]
position += 1
if (!isPathCovered(layer, req.path)) continue
if (layer.method && layer.method !== req.method) continue
if (Boolean(layer.handlesErrors) !== Boolean(error)) continue
try {
const result = error ? layer.fn(error, req, res, next) : layer.fn(req, res, next)
if (result && typeof result.catch === 'function') result.catch(next)
} catch (thrown) {
next(thrown)
}
return
}
if (!res.writableEnded) sendJson(res, error ? 500 : 404, { error: 'No layer answered.' })
}
next()
}
function sendJson(res, status, value) {
res.statusCode = status
res.setHeader('Content-Type', 'application/json; charset=utf-8')
res.end(JSON.stringify(value))
}
// ---------- the invented middleware ----------
function securityHeaders(req, res, next) {
res.setHeader('X-Content-Type-Options', 'nosniff')
res.setHeader('Content-Security-Policy', "default-src 'self'")
res.setHeader('Referrer-Policy', 'no-referrer')
next()
}
function corsForOrigins(allowedOrigins) {
return function cors(req, res, next) {
const origin = req.headers.origin
const isAllowed = Boolean(origin) && allowedOrigins.includes(origin)
res.setHeader('Vary', 'Origin')
if (isAllowed) {
res.setHeader('Access-Control-Allow-Origin', origin)
res.setHeader('Access-Control-Allow-Credentials', 'true')
}
const isPreflight = req.method === 'OPTIONS' && Boolean(req.headers['access-control-request-method'])
if (!isPreflight) return next()
if (isAllowed) {
res.setHeader('Access-Control-Allow-Methods', 'GET, POST')
res.setHeader('Access-Control-Allow-Headers', 'Content-Type')
}
res.statusCode = 204
res.end()
}
}
function readCookie(req, name) {
const header = req.headers.cookie || ''
for (const part of header.split(';')) {
const pair = part.trim().split('=')
if (pair[0] === name) return pair[1]
}
return undefined
}
function sessionLoader(sessions) {
return function session(req, res, next) {
req.session = sessions.get(readCookie(req, 'lab_sid')) || null
next()
}
}
function requireSignIn(req, res, next) {
if (!req.session) return sendJson(res, 401, { error: 'Sign in first.' })
next()
}
// Error fields modelled on the ones the body-parser README documents for its
// errors: status, type, expose, and the body that failed.
function makeHttpError(status, type, message, rawBody) {
const error = new Error(message)
error.status = status
error.type = type
error.expose = status < 500
error.body = rawBody
return error
}
function readBody(req, limitBytes) {
return new Promise(function (resolve, reject) {
const chunks = []
let size = 0
req.on('data', function (chunk) {
size += chunk.length
if (size > limitBytes) reject(makeHttpError(413, 'entity.too.large', 'request entity too large'))
else chunks.push(chunk)
})
req.on('end', function () { resolve(Buffer.concat(chunks).toString('utf8')) })
req.on('error', reject)
})
}
function jsonBody(limitBytes) {
return async function json(req, res, next) {
const contentType = req.headers['content-type'] || ''
if (!contentType.startsWith('application/json')) return next()
const raw = await readBody(req, limitBytes)
try {
req.body = JSON.parse(raw)
} catch (parseError) {
throw makeHttpError(400, 'entity.parse.failed', parseError.message, raw)
}
next()
}
}
// ---------- the invented routes ----------
function addNote(notes) {
return function createNote(req, res) {
const title = req.body && typeof req.body.title === 'string' ? req.body.title : ''
if (!title) return sendJson(res, 400, { error: 'A note needs a title.' })
notes.push({ owner: req.session.userId, title: title })
sendJson(res, 201, { created: notes.length, owner: req.session.userId })
}
}
function health(req, res) {
sendJson(res, 200, { status: 'ok' })
}
function failingReport() {
throw new Error('Invented fault: the report store is unreachable')
}
function notFound(req, res) {
sendJson(res, 404, { error: 'Not found.' })
}
// ---------- the error handler, in two modes ----------
const PUBLIC_MESSAGES = {
'entity.parse.failed': 'The request body is not valid JSON.',
'entity.too.large': 'The request body is too large.',
}
function errorHandler(mode, serverLog) {
return function handleError(error, req, res, next) {
if (res.headersSent) return res.destroy()
const status = error.status >= 400 && error.status < 600 ? error.status : 500
const reference = 'ref-' + String(serverLog.length + 1).padStart(4, '0')
serverLog.push(reference + ' ' + status + ' ' + error.message)
if (mode === 'development') {
res.statusCode = status
res.setHeader('Content-Type', 'text/plain; charset=utf-8')
return res.end(error.stack)
}
const message = PUBLIC_MESSAGES[error.type] || (status < 500 ? 'The request was refused.' : 'Something went wrong.')
sendJson(res, status, { error: message, reference: reference })
}
}
// ---------- the orders the lab compares ----------
export const ALLOWED_ORIGIN = 'https://app.lab-invented.example'
export const SESSION_COOKIE = 'lab_sid=lab-invented-sid-1'
// Each order differs from 'suggested' by one move.
export const ORDERS = {
'suggested': ['headers', 'cors', 'session', 'sign-in', 'json', 'routes', 'not-found', 'errors'],
'auth-before-cors': ['headers', 'session', 'sign-in', 'cors', 'json', 'routes', 'not-found', 'errors'],
'parser-before-auth': ['headers', 'cors', 'json', 'session', 'sign-in', 'routes', 'not-found', 'errors'],
'headers-after-routes': ['cors', 'session', 'sign-in', 'json', 'routes', 'headers', 'not-found', 'errors'],
}
function buildLayerGroups(mode, serverLog, notes) {
const sessions = new Map([['lab-invented-sid-1', { userId: 'lab-invented-user-1' }]])
return {
'headers': [{ path: '/', fn: securityHeaders }],
'cors': [{ path: '/', fn: corsForOrigins([ALLOWED_ORIGIN]) }],
'session': [{ path: '/', fn: sessionLoader(sessions) }],
'sign-in': [{ path: '/api', fn: requireSignIn }],
'json': [{ path: '/api', fn: jsonBody(1024) }],
'routes': [
{ path: '/health', exact: true, method: 'GET', fn: health },
{ path: '/api/notes', exact: true, method: 'POST', fn: addNote(notes) },
{ path: '/api/report', exact: true, method: 'GET', fn: failingReport },
],
'not-found': [{ path: '/', fn: notFound }],
'errors': [{ path: '/', handlesErrors: true, fn: errorHandler(mode, serverLog) }],
}
}
export function createLabServer(orderName, mode) {
const serverLog = []
const notes = []
const groups = buildLayerGroups(mode, serverLog, notes)
const layers = []
for (const groupName of ORDERS[orderName]) {
for (const layer of groups[groupName]) layers.push(layer)
}
const server = http.createServer(function (req, res) {
req.path = new URL(req.url, 'http://127.0.0.1').pathname
runLayers(layers, req, res)
})
return { server: server, serverLog: serverLog, notes: notes }
}
==== File 2 of 2: run-fixtures.mjs ====
// run-fixtures.mjs: starts the invented stack in each order on 127.0.0.1, on
// ports the system picks, sends each fixture request, prints what came back,
// and closes every server before it exits. Run: node run-fixtures.mjs
import http from 'node:http'
import { ALLOWED_ORIGIN, SESSION_COOKIE, createLabServer } from './ordered-stack.mjs'
const OTHER_ORIGIN = 'https://elsewhere.lab-invented.example'
const MALFORMED_JSON = '{"title": "Quarterly plan'
// A selection: x-content-type-options marks the headers layer, and the
// access-control headers and vary mark the CORS layer.
const SHOWN_HEADERS = [
'content-type', 'x-content-type-options',
'access-control-allow-origin', 'access-control-allow-credentials',
'access-control-allow-methods', 'vary',
]
function listen(server) {
return new Promise(function (resolve) {
server.listen(0, '127.0.0.1', function () { resolve(server.address().port) })
})
}
function send(port, request) {
return new Promise(function (resolve, reject) {
const options = { host: '127.0.0.1', port: port, method: request.method, path: request.path, headers: request.headers || {}, agent: false }
const outgoing = http.request(options, function (response) {
const chunks = []
response.on('data', function (chunk) { chunks.push(chunk) })
response.on('end', function () {
resolve({ status: response.statusCode, headers: response.headers, body: Buffer.concat(chunks).toString('utf8') })
})
})
outgoing.on('error', reject)
if (request.body) outgoing.write(request.body)
outgoing.end()
})
}
function describeRequest(request) {
const lines = [' request: ' + request.method + ' ' + request.path]
for (const name of Object.keys(request.headers || {})) lines.push(' ' + name + ': ' + request.headers[name])
if (request.body) lines.push(' body: ' + request.body)
return lines
}
function describeResponse(response) {
const lines = [' response: ' + response.status]
for (const name of SHOWN_HEADERS) {
const value = response.headers[name]
lines.push(' ' + name + ': ' + (value === undefined ? '(absent)' : value))
}
lines.push(' body:')
for (const bodyLine of (response.body || '(empty)').split('\n')) lines.push(' ' + bodyLine)
return lines
}
async function runFixture(stacks, fixture) {
console.log('')
console.log('FIXTURE ' + fixture.id + ': ' + fixture.title)
for (const stackName of fixture.stacks) {
const stack = stacks[stackName]
const response = await send(stack.port, fixture.request)
console.log('- stack ' + stackName)
for (const line of describeRequest(fixture.request)) console.log(line)
for (const line of describeResponse(response)) console.log(line)
if (fixture.showNotes) console.log(' notes stored on this stack so far: ' + stack.notes.length)
if (fixture.showLog) console.log(' server log so far: ' + (stack.serverLog.join(' | ') || '(empty)'))
}
}
const STACKS = {
'suggested, production': ['suggested', 'production'],
'suggested, development': ['suggested', 'development'],
'auth-before-cors, production': ['auth-before-cors', 'production'],
'parser-before-auth, production': ['parser-before-auth', 'production'],
'headers-after-routes, production': ['headers-after-routes', 'production'],
}
const FIXTURES = [
{
id: 1, title: 'malformed JSON from a signed-in client',
stacks: ['suggested, production', 'suggested, development'], showLog: true,
request: { method: 'POST', path: '/api/notes', headers: { 'content-type': 'application/json', 'cookie': SESSION_COOKIE }, body: MALFORMED_JSON },
},
{
id: 2, title: 'malformed JSON with no session cookie',
stacks: ['suggested, production', 'parser-before-auth, production'], showLog: true,
request: { method: 'POST', path: '/api/notes', headers: { 'content-type': 'application/json' }, body: MALFORMED_JSON },
},
{
id: 3, title: 'cross-origin preflight for a credentialed POST (a preflight carries no cookie)',
stacks: ['suggested, production', 'auth-before-cors, production'],
request: { method: 'OPTIONS', path: '/api/notes', headers: { 'origin': ALLOWED_ORIGIN, 'access-control-request-method': 'POST', 'access-control-request-headers': 'content-type' } },
},
{
id: 4, title: 'credentialed cross-origin POST from the allowed origin',
stacks: ['suggested, production'], showNotes: true,
request: { method: 'POST', path: '/api/notes', headers: { 'origin': ALLOWED_ORIGIN, 'content-type': 'application/json', 'cookie': SESSION_COOKIE }, body: '{"title": "Quarterly plan"}' },
},
{
id: 5, title: 'credentialed cross-origin POST from an origin not on the list',
stacks: ['suggested, production'], showNotes: true,
request: { method: 'POST', path: '/api/notes', headers: { 'origin': OTHER_ORIGIN, 'content-type': 'application/json', 'cookie': SESSION_COOKIE }, body: '{"title": "Written from elsewhere"}' },
},
{
id: 6, title: 'security headers on a route answered before the headers layer',
stacks: ['suggested, production', 'headers-after-routes, production'],
request: { method: 'GET', path: '/health' },
},
{
id: 7, title: 'security headers on a 404 when the headers layer sits between the routes and the 404 handler',
stacks: ['headers-after-routes, production'],
request: { method: 'GET', path: '/nothing-here' },
},
{
id: 8, title: 'an unexpected error in a route, in production and development modes',
stacks: ['suggested, production', 'suggested, development', 'headers-after-routes, production'], showLog: true,
request: { method: 'GET', path: '/api/report', headers: { 'cookie': SESSION_COOKIE } },
},
]
async function main() {
console.log('node ' + process.version + ', ordering lab, invented data only')
const stacks = {}
for (const stackName of Object.keys(STACKS)) {
const settings = STACKS[stackName]
const lab = createLabServer(settings[0], settings[1])
const port = await listen(lab.server)
stacks[stackName] = { server: lab.server, port: port, notes: lab.notes, serverLog: lab.serverLog }
}
try {
for (const fixture of FIXTURES) await runFixture(stacks, fixture)
} finally {
for (const stackName of Object.keys(stacks)) stacks[stackName].server.close()
}
console.log('')
console.log('all ' + Object.keys(stacks).length + ' servers closed')
}
main()
RUN IT, WITH WHAT EACH STEP PRINTED
STEP 1: node --version
v26.0.0
(exit code 0)
STEP 2: node run-fixtures.mjs
node v26.0.0, ordering lab, invented data only
FIXTURE 1: malformed JSON from a signed-in client
- stack suggested, production
request: POST /api/notes
content-type: application/json
cookie: lab_sid=lab-invented-sid-1
body: {"title": "Quarterly plan
response: 400
content-type: application/json; charset=utf-8
x-content-type-options: nosniff
access-control-allow-origin: (absent)
access-control-allow-credentials: (absent)
access-control-allow-methods: (absent)
vary: Origin
body:
{"error":"The request body is not valid JSON.","reference":"ref-0001"}
server log so far: ref-0001 400 Unterminated string in JSON at position 25 (line 1 column 26)
- stack suggested, development
request: POST /api/notes
content-type: application/json
cookie: lab_sid=lab-invented-sid-1
body: {"title": "Quarterly plan
response: 400
content-type: text/plain; charset=utf-8
x-content-type-options: nosniff
access-control-allow-origin: (absent)
access-control-allow-credentials: (absent)
access-control-allow-methods: (absent)
vary: Origin
body:
Error: Unterminated string in JSON at position 25 (line 1 column 26)
(2 lines showing a local path cut here)
at process.processTicksAndRejections (node:internal/process/task_queues:104:5)
server log so far: ref-0001 400 Unterminated string in JSON at position 25 (line 1 column 26)
FIXTURE 2: malformed JSON with no session cookie
- stack suggested, production
request: POST /api/notes
content-type: application/json
body: {"title": "Quarterly plan
response: 401
content-type: application/json; charset=utf-8
x-content-type-options: nosniff
access-control-allow-origin: (absent)
access-control-allow-credentials: (absent)
access-control-allow-methods: (absent)
vary: Origin
body:
{"error":"Sign in first."}
server log so far: ref-0001 400 Unterminated string in JSON at position 25 (line 1 column 26)
- stack parser-before-auth, production
request: POST /api/notes
content-type: application/json
body: {"title": "Quarterly plan
response: 400
content-type: application/json; charset=utf-8
x-content-type-options: nosniff
access-control-allow-origin: (absent)
access-control-allow-credentials: (absent)
access-control-allow-methods: (absent)
vary: Origin
body:
{"error":"The request body is not valid JSON.","reference":"ref-0001"}
server log so far: ref-0001 400 Unterminated string in JSON at position 25 (line 1 column 26)
FIXTURE 3: cross-origin preflight for a credentialed POST (a preflight carries no cookie)
- stack suggested, production
request: OPTIONS /api/notes
origin: https://app.lab-invented.example
access-control-request-method: POST
access-control-request-headers: content-type
response: 204
content-type: (absent)
x-content-type-options: nosniff
access-control-allow-origin: https://app.lab-invented.example
access-control-allow-credentials: true
access-control-allow-methods: GET, POST
vary: Origin
body:
(empty)
- stack auth-before-cors, production
request: OPTIONS /api/notes
origin: https://app.lab-invented.example
access-control-request-method: POST
access-control-request-headers: content-type
response: 401
content-type: application/json; charset=utf-8
x-content-type-options: nosniff
access-control-allow-origin: (absent)
access-control-allow-credentials: (absent)
access-control-allow-methods: (absent)
vary: (absent)
body:
{"error":"Sign in first."}
FIXTURE 4: credentialed cross-origin POST from the allowed origin
- stack suggested, production
request: POST /api/notes
origin: https://app.lab-invented.example
content-type: application/json
cookie: lab_sid=lab-invented-sid-1
body: {"title": "Quarterly plan"}
response: 201
content-type: application/json; charset=utf-8
x-content-type-options: nosniff
access-control-allow-origin: https://app.lab-invented.example
access-control-allow-credentials: true
access-control-allow-methods: (absent)
vary: Origin
body:
{"created":1,"owner":"lab-invented-user-1"}
notes stored on this stack so far: 1
FIXTURE 5: credentialed cross-origin POST from an origin not on the list
- stack suggested, production
request: POST /api/notes
origin: https://elsewhere.lab-invented.example
content-type: application/json
cookie: lab_sid=lab-invented-sid-1
body: {"title": "Written from elsewhere"}
response: 201
content-type: application/json; charset=utf-8
x-content-type-options: nosniff
access-control-allow-origin: (absent)
access-control-allow-credentials: (absent)
access-control-allow-methods: (absent)
vary: Origin
body:
{"created":2,"owner":"lab-invented-user-1"}
notes stored on this stack so far: 2
FIXTURE 6: security headers on a route answered before the headers layer
- stack suggested, production
request: GET /health
response: 200
content-type: application/json; charset=utf-8
x-content-type-options: nosniff
access-control-allow-origin: (absent)
access-control-allow-credentials: (absent)
access-control-allow-methods: (absent)
vary: Origin
body:
{"status":"ok"}
- stack headers-after-routes, production
request: GET /health
response: 200
content-type: application/json; charset=utf-8
x-content-type-options: (absent)
access-control-allow-origin: (absent)
access-control-allow-credentials: (absent)
access-control-allow-methods: (absent)
vary: Origin
body:
{"status":"ok"}
FIXTURE 7: security headers on a 404 when the headers layer sits between the routes and the 404 handler
- stack headers-after-routes, production
request: GET /nothing-here
response: 404
content-type: application/json; charset=utf-8
x-content-type-options: nosniff
access-control-allow-origin: (absent)
access-control-allow-credentials: (absent)
access-control-allow-methods: (absent)
vary: Origin
body:
{"error":"Not found."}
FIXTURE 8: an unexpected error in a route, in production and development modes
- stack suggested, production
request: GET /api/report
cookie: lab_sid=lab-invented-sid-1
response: 500
content-type: application/json; charset=utf-8
x-content-type-options: nosniff
access-control-allow-origin: (absent)
access-control-allow-credentials: (absent)
access-control-allow-methods: (absent)
vary: Origin
body:
{"error":"Something went wrong.","reference":"ref-0002"}
server log so far: ref-0001 400 Unterminated string in JSON at position 25 (line 1 column 26) | ref-0002 500 Invented fault: the report store is unreachable
- stack suggested, development
request: GET /api/report
cookie: lab_sid=lab-invented-sid-1
response: 500
content-type: text/plain; charset=utf-8
x-content-type-options: nosniff
access-control-allow-origin: (absent)
access-control-allow-credentials: (absent)
access-control-allow-methods: (absent)
vary: Origin
body:
Error: Invented fault: the report store is unreachable
(10 lines showing a local path cut here)
server log so far: ref-0001 400 Unterminated string in JSON at position 25 (line 1 column 26) | ref-0002 500 Invented fault: the report store is unreachable
- stack headers-after-routes, production
request: GET /api/report
cookie: lab_sid=lab-invented-sid-1
response: 500
content-type: application/json; charset=utf-8
x-content-type-options: (absent)
access-control-allow-origin: (absent)
access-control-allow-credentials: (absent)
access-control-allow-methods: (absent)
vary: Origin
body:
{"error":"Something went wrong.","reference":"ref-0001"}
server log so far: ref-0001 500 Invented fault: the report store is unreachable
all 5 servers closed
(exit code 0)
WHAT THE LAB SHOWED
- Fixture 1: signed in, the malformed JSON got a 400 in both modes. In production mode the body was a fixed message and a reference, and the parser's message went to the server log under that reference. In development mode the body was the stack trace.
- Fixture 2: with no session cookie, the suggested stack refused with 401 before reading the body, and its log gained no entry (the entry shown is fixture 1's). With the parser moved above the sign-in check, the same anonymous request was read, parsed and refused with 400, and that stack's log recorded the parse failure.
- Fixture 3: the preflight, which carried no cookie, got 204 with the allowed origin and the credentials header when CORS ran above the sign-in check. With the sign-in check above CORS, it got 401 and no CORS headers.
- Fixtures 4 and 5: both credentialed POSTs were stored, and the note count went from 1 to 2. The response to the origin that is not on the list carried no Access-Control-Allow-Origin header, and the note was stored anyway. The lab sends the cookie itself and is not a browser, so it cannot show what a browser would send or let a script read.
- Fixtures 6, 7 and 8: with the headers layer below the routes, the /health response and the 500 from the failing route went out without X-Content-Type-Options, while the 404 for an unknown path carried it, because the headers layer sits between the routes and the 404 handler.
- Fixture 8: the route that throws got 500 with a fixed message and a reference in production mode, and the stack trace in development mode.
WHAT THE LAB DOES NOT SHOW
- Express itself, or any middleware package. A real stack can behave differently: read the documentation lines in Part A and check your own application.
- A browser. Whether a browser sends a cookie cross-site, and whether it lets a script read a response, are not exercised.
- A proxy, a rate limiter, a session store or a real sign-in, so A1, A4 and A7 have no fixture, and A5 has only the cookie read.
- Express 4's handling of rejected promises. The runner turns a rejected promise into next(error), which is what the Express 5 guide describes.
- A body over the parser's limit. The lab's JSON layer rejects one with 413, but no fixture sends one.Express security: what the framework does, and what it leaves to your middleware
Express's own guide describes it as a routing and middleware web framework with minimal functionality of its own, and says an Express application is essentially a series of middleware function calls executed during the request-response cycle.
On this page's reading, that sentence says where Express security sits: in the middleware functions an application adds, the order it adds them in, and the settings it changes from their defaults.
On the Express side, the project's security updates page lists Express vulnerabilities under the version update that fixed each one, and its production security guide sets out practices for applications built on Express. Several defaults are worth reading before an application goes live. The application settings table in the Express 5.x API reference has x-powered-by on by default and env falling back to "development" when NODE_ENV is not set, and the 5.x error handling guide says that outside the production environment the built-in error handler writes the stack trace to the client.
Other defaults limit what a request can do.
The same API reference says express.json()'s limit option, which controls the maximum request body size, defaults to 100kb, and in its default strict mode it accepts only arrays and objects.
The rest stays with the application. The production security guide puts it plainly: the responsibility for validating and correctly handling the types of user input your application accepts is yours. The cors README says the same about access: CORS is not access control, and it tells you to use authentication and authorisation to protect your API.
On this page's reading, that leaves security headers, CORS, rate limits, sessions and authentication to middleware your team chooses, configures and places, which is why a review of an Express application starts with the order of its middleware.
Express runs on Node.js, and its security updates page opens with a caution that Node.js vulnerabilities directly affect Express. The Node.js guide covers the runtime and npm; this page covers Express's middleware order and configuration.
Why Express middleware order is a security setting
Express documents the rules that make order matter.
Its API reference says middleware functions are executed sequentially, so the order of middleware inclusion is important. Its guide to writing middleware says that middleware functions loaded first are also executed first, and shows that when a logger is loaded after the route to the root path, a request to that path never reaches it, because the route handler ends the request-response cycle.
Passing anything except the string 'route' or 'router' to next() makes Express treat the request as an error and skip the remaining non-error routing and middleware functions. And error-handling middleware, which takes four arguments, is defined last, after the other app.use() and route calls.
On this page's reading, those rules give every layer two kinds of neighbour. The layers above it decide whether a request reaches it at all, and in what state: whether a body has been parsed, a session loaded or a client address worked out. The layers below it never see a request it answers.
A header set after a route has replied, a sign-in check mounted below a router, and an error handler placed above the routes it should catch all look correct in the code and do nothing for the requests that matter.
Mount paths add a second dimension. With a string path, app.use() matches that path and its subpaths, so middleware on /apple runs for /apple/images but not for /apples. Where a parent app uses path-specific middleware to protect a sub-app, the reference says to apply that middleware to the full mount path of the sub-app rather than to a narrower path inside it.
The case sensitive routing and strict routing settings change what a path matches. With case sensitive routing disabled, /Foo and /foo are treated the same, and with strict routing disabled, /foo and /foo/ are.
Both are read when the app first creates its router, which adding a route or middleware, calling app.param(), accessing app.router or handling a request can do, so the reference says to set them before any of those operations.
Express 5 changed a rule the error handler depends on. The Express 5.x error handling guide says route handlers and middleware that return a promise call next(value) automatically when they reject or throw an error, and that because async functions always return a promise, their errors reach Express with no extra work.
The Express 4.x guide says rejected promises are not passed to next automatically, including from async functions, and that the unhandled rejection "crashes the process on current Node.js versions" unless the handler catches the error and passes it on. Check which major version your lockfile resolves before relying on either.
An Express middleware order to start from
The Express pages cited here give the rules above rather than one order for security middleware.
The express-rate-limit and body-parser documentation each give a placement: assuming the proxy sets the X-Forwarded-For header, the express-rate-limit proxy guide says to set trust proxy right after you create the Express application, and the body-parser README says adding parsers to the routes that need them is, in general, the most recommended way to use it with Express.
The order below is this page's suggestion, built from those rules and from what each layer needs from the layers above it. The matrix on this page checks each position against your own code.
- Settings: trust proxy, x-powered-by and the routing settings, above the first app.use.
- Security headers, such as Helmet, so the responses that follow carry them.
- CORS, so a preflight is answered before anything asks it for a session.
- A rate limit keyed on the client address, before any work is spent on the request.
- Sessions, so authentication can read req.session.
- Authentication and authorisation, mounted on the full path of everything they protect.
- A rate limit keyed on the account, once the caller is known.
- Body parsers, on the routes that take a body.
- Routes and static files.
- The 404 handler, then the error handler, last.
What each layer needs from the layers above it
Each position below gives what the Express or middleware documentation says, then this page's reading of what moving the layer changes.
The matrix repeats each one as a block to fill in, with what to record.
The trust proxy setting decides which address Express treats as the client's. Its default is false, under which the app is understood as directly facing the client. Set to true, the client's address is the left-most entry in the X-Forwarded-For header, and Express's guide to running behind proxies warns that it is then important to ensure the last trusted reverse proxy removes or overwrites X-Forwarded-For, X-Forwarded-Host and X-Forwarded-Proto, otherwise it may be possible for the client to provide any value.
The application settings reference adds that X-Forwarded-* headers are easily spoofed and the detected IP addresses are unreliable.
The express-rate-limit and express-session documentation both tie behaviour to that setting. The express-rate-limit guide says that behind a proxy or load balancer the request's address might be the proxy's, which makes the limiter effectively a global one, blocking all requests once the limit is reached.
The express-session README says that behind a proxy, a session cookie marked secure needs trust proxy set in Express. How trust proxy changes req.hostname is covered in the host header injection guide.
The Express production security guide says Helmet can help protect an app from some well-known web vulnerabilities by setting HTTP headers appropriately. The Helmet README's quick start mounts it with app.use(helmet()), its HTTP header reference gives each header's default, and it says each header can be disabled or configured.
Its Content-Security-Policy default includes default-src 'self', script-src 'self' and object-src 'none', and the README says the header likely requires some configuration for your specific app.
On this page's reading, Helmet can only set headers on responses that pass through it, so anything that answers above it goes out without them: express.static, a health check, a preflight answered by CORS, a rate-limit refusal or an error raised earlier. The lab shows the shape of it: with its headers layer moved below the routes, the health check and the 500 from a failing route went out without X-Content-Type-Options, while the 404 for an unknown path still carried it, because the headers layer sat between the routes and the 404 handler.
Settings aside, what belongs above Helmet is a middleware that prepares a value Helmet reads, such as the nonce in the README's Content Security Policy example, which a middleware sets in res.locals before helmet() runs.
Express also sends an X-Powered-By header by default. The production security guide shows app.disable('x-powered-by'), and Helmet removes the header by default. The guide notes that disabling it does not prevent a sophisticated attacker from determining that an app is running Express.
MDN's guide to cross-origin resource sharing says CORS-preflight requests must never include credentials, and that for a preflighted request the browser first sends an OPTIONS request and sends the actual request upon approval from the server. The Fetch Standard restricts a successful preflight response to an ok status, such as 200 or 204.
Put an authentication check above the cors middleware and, on this page's reading, the preflight arrives without a session cookie, the check refuses it with a status that is not ok, and the real request is never sent.
In the lab, the same preflight got 204 with CORS above the sign-in check and 401 with the sign-in check above CORS.
The cors README says that used as application-level middleware, app.use(cors()), it already handles preflight requests for all routes. Otherwise, its pre-flight section says to add a new OPTIONS handler for the route you want to support, and shows enabling pre-flight across the board as well.
On this page's reading, its position protects nothing by itself. The README says the server receives and processes every request, and in the lab a credentialed request from an origin that was not on the list was stored, with no Access-Control-Allow-Origin header on the response.
Which origins to list, and the settings that let the wrong ones in, are the subject of the CORS misconfiguration guide.
By default, express-rate-limit uses the client's IP address as its key, keeps its counts in a memory store whose limits are reset when the Node.js process restarts, and answers with status 429. With passOnStoreError at its default of false, a store error goes to the Express error handler and requests are blocked, which its documentation calls failing closed.
The library logs ERR_ERL_PERMISSIVE_TRUST_PROXY when trust proxy is true, because Express then takes the leftmost X-Forwarded-For entry, which a client could set, and ERR_ERL_DOUBLE_COUNT when one request increments a count more than once, which it says could happen when the same instance is called more than once or several instances use the same store.
This page suggests two positions. A limiter keyed on the client address goes above sessions and body parsers, so a refused request costs neither a session lookup nor a body read, and below CORS if a page on another origin needs to read the 429.
A limiter keyed on the account can only go below the check that says who the caller is. The Express production guide describes blocking authorisation attempts using the number of consecutive failed attempts by the same user name and IP address, and the number of failed attempts from an IP address over some long period of time. The rate limiting guide covers what to count, against which key, and what a refusal should say.
express-session keeps session data on the server and only the session ID in the cookie. Its README says the default MemoryStore is purposely not designed for a production environment, and the Express production guide says production needs a scalable session store and advises against the default session cookie name, which can be used to fingerprint the server.
Since version 1.5.0 the module no longer needs cookie-parser, and the README warns that using cookie-parser may cause issues if the secret is not the same in both.
On this page's reading, authentication reads req.session, so sessions go above it, and the other direction matters too. saveUninitialized defaults to true, which forces a new, unmodified session to be saved to the store, and the README says using that default is deprecated.
A session layer mounted above express.static or a health check can then create and store a session for each of those requests. The cookie security guide covers each cookie attribute, and the session management guide covers when a session ID should change.
express.json() is based on body-parser. It parses only requests whose Content-Type matches its type option, application/json by default, with a default limit of 100kb, and the Express 5.x reference says req.body is undefined if there was no body to parse, the Content-Type did not match, or an error occurred.
Its warning is worth keeping beside every route: req.body's shape is based on user-controlled input, so all its properties and values are untrusted and should be validated before trusting.
The body-parser README documents what a parser hands the error handler. Its errors will typically have a status, an expose property that determines whether its message should be displayed to the client, a type, and the body it read, if available. A body that cannot be parsed gives status 400 and type 'entity.parse.failed', with the failed entity in the body property.
On this page's reading, a parser mounted above authentication makes the server read and parse bodies from anyone, signed in or not. In the lab, a malformed body with no session cookie got 401 with the parser below the sign-in check, and was parsed and refused with 400 with the parser above it. How the extended form parser builds nested objects from brackets is covered in the NoSQL injection guide.
Express's error handling guide says its built-in error handler sits at the end of the middleware stack. An error passed to next() and not handled by a custom handler is written to the client with the stack trace, which is not included in the production environment, and the guide says to set NODE_ENV to production to run in production mode.
A custom handler is defined last, after the other app.use() and route calls, takes four arguments, and must delegate to the default handler when the headers have already been sent.
On this page's reading, two mistakes undo it. An error handler mounted above the routes never sees their errors, so the built-in handler answers them. And a custom handler that sends the whole error object to the client can return the request body a parser stored in its body property.
Read expose before showing a message, and send nothing else from the error. In the lab, the same malformed body gave a fixed message and a reference in production mode and the full stack trace in development mode. The security misconfiguration guide covers verbose error output across frameworks.
Express security best practices from the project's own guide
The Express production security guide is short and worth reading in full.
Its main points, in its own order:
- Do not use deprecated or vulnerable versions. Express 2.x and 3.x are no longer maintained, and security and performance issues in them will not be fixed. The guide also says not to use any version listed as vulnerable on the security updates page.
- Use TLS if the app deals with or transmits sensitive data.
- Do not trust user input. The guide's example is an open redirect, with code that checks a URL's host before calling res.redirect. The open redirects guide covers the wider problem.
- Use Helmet to set security-related response headers.
- Reduce fingerprinting: disable X-Powered-By, and replace Express's own 404 and error messages with your own handlers, which its example writes as the last app.use calls before app.listen().
- Use cookies securely: change the default session cookie name, set the cookie options, and use a scalable session store in production.
- Prevent brute-force attacks against authorisation by blocking authorisation attempts based on the number of consecutive failed attempts by the same user name and IP address, and on the number of failed attempts from an IP address over some long period of time.
- Check dependencies with npm audit, and watch advisory sources such as the GitHub Advisory Database for advisories that may affect Express or other modules your app uses.
What the list does not say
Several of those points are a choice of middleware or a setting. Apart from its example that writes the 404 and error handlers last, the guide does not say where each piece goes in the stack, and that is the question the rest of this page and the matrix answer.
Express vulnerabilities: the security updates page and the advisories behind it
The Express security updates page lists Express vulnerabilities under the version update that fixed them.
Read on 14 November 2026, its entries sat under 4.x and 3.x headings. Several are dependency updates, some noting that they may affect your application if it uses a named API, and its 3.x section says Express 3.x is end-of-life and no longer maintained, with known and unknown security and performance issues not addressed since the last update on 1 August 2015.
The advisories below are the records behind that page's entries for CVE-2024-29041 and CVE-2024-43796, and a body-parser advisory, each as its repository advisory and its GitHub Advisory Database entry read on 14 November 2026. This is a dated selection, not a complete list: check the Express security updates page and the GitHub Advisory Database, under the express and body-parser packages, for newer entries, and record your versions against both in block A11 of the matrix.
- CVE-2024-29041 (GHSA-rv95-896h-c2vc), an open redirect in malformed URLs. The Express repository advisory and the GitHub Advisory Database entry both list express versions below 4.19.2, and from 5.0.0-alpha.1 to below 5.0.0-beta.3, as affected, with 4.19.2 and 5.0.0-beta.3 as patched. Both say that when Express redirects to a user-provided URL it encodes the URL with encodeurl before setting the location header, which can cause malformed URLs to be evaluated in unexpected ways by common redirect allow list implementations. The main method impacted is res.location(), which res.redirect() also calls. Its workaround is to pre-parse the URL string with require('node:url').parse or new URL before passing user input to either.
- The same advisory, GHSA-rv95-896h-c2vc, says an initial fix went out with express 4.19.0, a feature regression was patched in 4.19.1, and improved handling for the bypass was added in 4.19.2, while the security updates page lists the fix under 4.19.0 and 4.19.1. This page acts on the advisory's version fields, which give 4.19.2.
- CVE-2024-43796 (GHSA-qw6h-vgh9-j6wx), cross-site scripting through response.redirect(). The Express repository advisory and the GitHub Advisory Database entry both list express versions below 4.20.0, and from 5.0.0-alpha.1 to below 5.0.0, as affected, with 4.20.0 and 5.0.0 as patched. Both descriptions say that in express below 4.20.0, passing untrusted user input to response.redirect(), even after sanitising it, may execute untrusted code, and their details list the conditions exploitation requires, including that the attacker controls the input to response.redirect() and that the user clicks on the link in the template. Their workarounds section encourages upgrading to the patched version, and otherwise making sure any untrusted inputs are safe, ideally by validating them against an explicit allowlist. The security updates page lists the fix under 4.20.0.
- CVE-2024-45590 (GHSA-qwcr-r2fm-qrc7), denial of service in body-parser when url encoding is enabled. The body-parser repository advisory and the GitHub Advisory Database entry both list body-parser below 1.20.3 as affected and 1.20.3 as patched, and say a malicious actor using a specially crafted payload could flood the server with a large number of requests, resulting in denial of service. The Express security updates page does not print this advisory's id, but its 4.20.0 body-parser entry links to it. Under Express 4.20.0 it lists a body-parser dependency update to address a vulnerability, noting it may affect your application if you had url encoding activated.
How to use the middleware-order test matrix
The matrix works outward from your code.
It traces a request through each position, from the settings to the error handler, and for each one sets what the documentation says beside what your application actually does.
- Write the mount list first, from the code rather than from memory: every app.set, app.use, route and router call in the order it runs, including the calls inside routers and sub-apps mounted from other files.
- Fill blocks A1 to A10 from the mount list, the lockfile and the configuration. Each block quotes the documentation it relies on, so a reviewer can check a line without this page.
- Watch requests only on a local copy of the application or in the lab. For production, read the headers your own browser receives on your own site in its developer tools, and nothing more.
- Search your own logs for the express-rate-limit error codes in block A4. Its documentation says each validation check runs once and then disables itself, unless the validate option disables it or, for some checks, a custom keyGenerator prevents it, so look in the log lines that follow each start-up and note which options are set.
- Log every difference between the order you meant and the order you found, with an owner. Moving a layer is a code change that goes through your usual change process. Once it is made, repeat the matching block's checks on a local copy and record the result.
- Revisit the matrix when a router is added, when a middleware package moves to a new major version, and when the proxies in front of the application change.
The local ordering lab: eight fixtures and four orders
The asset ends with a lab to run on your own computer.
It is an illustration written for this page: a small invented middleware runner whose layers are plain functions called in the order they are added. It is not Express and holds no code from Express or from any middleware package, so it shows what moving a layer does in that runner, and every statement on this page about Express itself rests on Express's documentation.
It ran on Node.js v26.0.0 on macOS. Its two files import only node:http and each other, and it listens on 127.0.0.1.
- Malformed JSON from a signed-in client got a 400 in both modes: a fixed message and a reference in production mode, the stack trace in development mode.
- Malformed JSON with no session cookie got 401 with the parser below the sign-in check, and was parsed and refused with 400 with the parser above it.
- A preflight for a credentialed request got 204 with the CORS headers when CORS sat above the sign-in check, and 401 with no CORS headers when it sat below.
- A credentialed request from an origin not on the list was stored, and its response carried no Access-Control-Allow-Origin header.
- With the headers layer below the routes, a route's response and a 500 went out without the security header, while a 404 still carried it.
- Left out: a browser, a proxy, a rate limiter, a session store and Express 4's handling of rejected promises.
What a review of your own middleware cannot show
A completed matrix records the order in the code you read, on the day you read it.
It cannot show what a middleware package does beyond its documentation, what a proxy in front of the application does to headers before Express sees them, or how a browser treats a response. The lab narrows none of those gaps, because it is not Express.
Nor does it show whether each route checks that the caller may see the record it asks for. The matrix places the authentication check; on this page's reading, the ownership check lives inside each route, where reading the code and exercising the running application as each role can show a missing one. The broken access control guide covers that work.
Where a Clever Ops review fits
This guide is an informational configuration and code guide.
Nothing on it describes a test of Express or of its middleware projects, and the matrix and the lab are for your own team to keep.
Active testing of your own Express application sits within a scoped web application penetration test, which signs in to your custom web application and calls its API using test accounts for every role. Its report sets out the scope as tested, naming the build, the test dates, the routes and roles covered, the accounts used and every exclusion.
Clever Ops also reviews code for custom web applications and their APIs, including Node applications, using read-only access to your repository.
Where Clever Ops built or hosts your Express application, the same work is reported as a security review, not as an independent penetration test, and the report identifies who built the application and who provides its hosting.
Frequently asked questions
The Express documentation cited here gives no yes or no. It records defaults, and on this page's reading some are worth changing before production: x-powered-by is on, env falls back to "development" when NODE_ENV is not set, the built-in error handler writes the stack trace to the client outside production, and express-session's default MemoryStore is purposely not designed for production. Others limit what a request can do, such as express.json()'s 100kb default limit. The production security guide says the responsibility for validating and correctly handling the types of user input your application accepts is yours.
The Express documentation cited here gives rules rather than one order: middleware runs in the order it is loaded, its examples show that a request a route has already answered never reaches a layer loaded below that route, and error handlers go last. From those rules this page suggests settings first, then security headers, CORS, a rate limit keyed on the client address, sessions, authentication, a rate limit keyed on the account, body parsers on the routes that need them, routes, the 404 handler and the error handler. The matrix checks each position in your own code.
MDN says CORS-preflight requests must never include credentials, so on this page's reading a preflight arrives without your session cookie, and the Fetch Standard restricts a successful preflight response to an ok status such as 200 or 204. If an authentication check runs above the cors middleware, it refuses the preflight and the browser does not send the real request. Mount cors above the check: its README says that used as application-level middleware it already handles preflight requests for all routes. In the lab, the same preflight got 204 one way round and 401 the other.
Helmet's quick start mounts it with app.use(helmet()). Express runs middleware in the order it is loaded, and its guide shows that a request a route has already answered never reaches a middleware loaded after that route. On this page's reading, anything that answers above Helmet, such as express.static, a health check or a CORS preflight, goes out without its headers. Settings can sit above it, and so can a middleware that prepares a value Helmet reads, such as the Content Security Policy nonce in Helmet's own example.
The Express repository advisory GHSA-rv95-896h-c2vc and its GitHub Advisory Database entry both list express versions below 4.19.2, and pre-release versions from 5.0.0-alpha.1 to below 5.0.0-beta.3, as affected, with 4.19.2 and 5.0.0-beta.3 as patched. Both say an initial fix went out with 4.19.0 and improved handling for the bypass was added in 4.19.2, while the Express security updates page lists the fix under 4.19.0 and 4.19.1. This page acts on the advisory's version fields, as read on 14 November 2026.
The Express error handling guide says the built-in error handler writes the stack trace to the client except in the production environment, and to set NODE_ENV to production to run in production mode. The application settings reference says the env setting falls back to "development" when NODE_ENV is not set. Add your own error handler as the last middleware, with four arguments, and have it send a fixed message while the detail goes to your logs. In the lab, the same fault gave the stack trace in development mode and a fixed message with a reference in production mode.
Scope the right test for your application
Tell us what you have built, who uses it and when it needs to launch. You will get a plain-English recommendation: a website audit, a web application test or a referral to a specialist.