Skip to main content
Platform security guideReviewed

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.

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

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:

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.

Settings and the client address

The trust proxy setting decides which address Express treats as the client's. 1 min read

Helmet and the responses that leave early

The Express production security guide says Helmet can help protect an app from some well-known web vulnerabilities by setting HTTP headers appropriately. 1 min read

CORS, preflights and the sign-in check

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. 1 min read

Rate limits: two positions and two keys

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. 1 min read

Sessions sit above the sign-in check

express-session keeps session data on the server and only the session ID in the cookie. 1 min read

Body parsers belong below authentication

express.json() is based on body-parser. 1 min read

The error handler goes last

Express's error handling guide says its built-in error handler sits at the end of the middleware stack. 1 min read

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.