Express 5 Migration Guide and Security Hardening for an Express API

Move an Express 4 API to Express 5 and lock it down: removed methods, the new path syntax, async error handling, the query parser and req.body changes, then trust proxy, Helmet, rate limiting, body and upload limits and an error handler.

Cover for the article Express 5 Migration Guide and Security Hardening for an Express API

To migrate an Express 4 API to Express 5, run npm install express@5, run the official codemods, then fix five areas by hand: route path syntax, req.query, req.body, removed response signatures and static-file dotfiles. Express 5 needs Node.js 18 or newer, and rejected promises from async handlers now reach your error handler by themselves. After the migration, harden the app: set trust proxy to match your real proxy chain, add Helmet, rate limit the API, set explicit body and upload limits, and write one error handler that never leaks stack traces. On 5 November 2026 the latest tag on npm is Express 5.3.0, and Express 4's latest is 4.22.3. The Express team moved 4.x to maintenance in 2025, so a migration now is the planned path, not a risky experiment.

Where Express 4 and 5 stand

The Express team's 31 March 2025 post says that tagging 5.1.0 as latest moved Express from Current to Active and started the clock on end-of-life for v4. It proposed v4 end-of-life "no sooner than 2026-10-01" and called the dates "goals not commitments". The Express support page on 5 November 2026 still lists v4.x as "ongoing" with no end date, and says that EOL versions "may" receive critical security updates but with no guarantee. Whatever the final date, the practical risk is the same as with any older line: fixes arrive for the newest line first. If you also run Angular or other Node.js tooling, check what your upgrade plan looks like in the Node.js 20 to 26 upgrade path.

Step 1: install and run the codemods

npm install express@5
npx codemod@latest @expressjs/v5-migration-recipe     # runs all official codemods
npx codemod@latest @expressjs/<name-of-the-codemod>   # or run a single one

Both commands are from the official migration guide. Review the diff like any other change, then run your tests, then start the app and click through it to catch calls to removed methods.

Step 2: replace removed methods and signatures

Express 4Express 5
app.del()app.delete()
req.param(name)req.params.name, req.body or req.query, explicitly
res.json(obj, 201), res.send(body, 200)res.status(201).json(obj), res.status(200).send(body)
res.send(200)res.sendStatus(200)
res.redirect('/users', 302)res.redirect(302, '/users')
res.redirect('back')res.redirect(req.get('Referrer') || '/')
res.sendfile()res.sendFile()
req.acceptsCharset(), acceptsEncoding(), acceptsLanguage()The plural forms: acceptsCharsets(), acceptsEncodings(), acceptsLanguages()
app.param(fn) (single argument)app.param(name, fn)
hidden and from options of express.static and res.sendFiledotfiles and root

Three behaviour changes in this area are easy to miss. res.status() throws for anything that is not an integer from 100 to 999, res.vary() throws when called without a field, and res.clearCookie ignores maxAge and expires.

Step 3: fix route paths

Express 5 uses a newer path-to-regexp. Wildcards must be named, the optional ? suffix became braces, and regular expressions inside path strings are no longer supported. The characters ()[]?+! are reserved, so escape them with a backslash, and parameter names must be valid JavaScript identifiers (or quoted, like :"this"):

// Express 4                                // Express 5
app.get('/*', handler);                     app.get('/*splat', handler);
                                            app.get('/{*splat}', handler);  // also matches "/"
app.get('/:file.:ext?', handler);           app.get('/:file{.:ext}', handler);
app.get('/[discussion|page]/:slug', h);     app.get(['/discussion/:slug', '/page/:slug'], h);

Two consequences. A wildcard parameter is now an array: GET /foo/bar on /*splat gives { splat: ['foo', 'bar'] }. And req.params omits parameters that did not match, where Express 4 gave an empty string or undefined. A catch-all SPA or SSR fallback route is the most common place this bites, so grep for '*' and '/*' first. The path-to-regexp 8.0.0 release notes list the same removals (regex overrides for parameters and loose mode). The Express 4 line also needed several path-to-regexp dependency updates (GHSA-9wv6-86v2-598j in 4.20.0 and GHSA-rhx6-c78j-4q9w in 4.21.2), which is one more reason to move.

Step 4: async handlers just work, and you must still handle errors

In Express 5, a handler that returns a promise calls next(err) if it rejects, and async functions always return a promise, so the try/catch and .catch(next) boilerplate can go:

app.get('/users/:id', async (req, res) => {
  const user = await getUserById(req.params.id); // a rejection reaches the error handler
  if (!user) return res.status(404).json({ message: 'Not found' });
  res.json(user);
});

The error-handling guide keeps three exceptions. If you build a promise chain without returning it, pass next to the final .catch(), or the rejection is unhandled and can crash the process. Errors from callback APIs (such as fs.readFile) must be passed to next() manually. And errors thrown inside timers need a try/catch that calls next(err). In every case, Express must receive the error for the handler to run.

Step 5: req.query, req.body and urlencoded

  • req.query is a getter and the default parser is "simple" (Node's querystring), where Express 4 defaulted to "extended" (the qs library). Assigning to it (req.query.page = 1) no longer works. If you rely on nested query syntax, set it back deliberately with app.set('query parser', 'extended'), or keep the simple parser and validate the result with a schema.
  • req.body is undefined when nothing was parsed, where Express 4 gave {}. Use req.body?.field or check first.
  • express.urlencoded() defaults extended to false. Pass { extended: true } to keep the old behaviour, if you need it.
  • req.host keeps the port, and req.params has a null prototype for string paths.

Validating req.params, req.query and req.body with one schema per route is the cleanest answer to all of these. I describe a setup in Building a Type-Safe Express 5 API with Zod.

Step 6: static files and dotfiles

express.static now defaults dotfiles to "ignore", and hidden directories in the request path return 404. That breaks /.well-known/ paths used by ACME challenges, Android App Links and Apple Universal Links unless you opt that directory in:

app.use('/.well-known', express.static('public/.well-known', { dotfiles: 'allow' }));
app.use(express.static('public'));

Also note that .js files are now served as text/javascript instead of application/javascript, because Express 5 uses a newer mime-db. The migration guide does not count this as breaking, so pin dependencies deliberately if a client depends on the old type.

Hardening part 1: know what is in front of the app

The trust proxy setting defaults to false, which means the client IP comes from req.socket.remoteAddress. Behind a reverse proxy that is the proxy's address, so IP-based rate limits and logs treat every visitor as one client. Setting it fixes that and creates the opposite risk: the Express docs warn that X-Forwarded-* headers "are easily spoofed". The guide for proxies gives the rules:

  • With true, the client IP is the left-most X-Forwarded-For entry, so the last trusted proxy must remove or overwrite X-Forwarded-For, X-Forwarded-Host and X-Forwarded-Proto, or a client can supply any value.
  • With a number n, Express trusts the address at most n hops away. Make sure there are no other paths to the app with a different number of hops.
  • With subnets ('loopback', 'linklocal', 'uniquelocal', or your own list), the nearest untrusted address is the client.

Prefer an exact hop count or subnet list that mirrors your real topology, and test req.ip through the real proxy. The proxy-addr package behind this setting had a Critical advisory this year (CVE-2026-90711, fixed in 2.0.8), which is listed in Patching a MEAN Stack.

Hardening part 2: one app skeleton

This is the order I would register middleware in. It uses Helmet 8.3.0 (Node 18 or newer) and express-rate-limit 8.7.3, which were the current npm releases on 5 November 2026:

import express from 'express';
import helmet from 'helmet';
import { rateLimit } from 'express-rate-limit';
// import { apiRouter } from './routes.js';  // your routes
// import { errorHandler } from './errors.js'; // defined further down

export const app = express();
app.set('trust proxy', 1); // exactly one proxy in front: match your real setup
app.use(helmet());
app.use(
  rateLimit({ windowMs: 15 * 60 * 1000, limit: 100, standardHeaders: 'draft-8', legacyHeaders: false }),
);
app.use(express.json({ limit: '100kb' }));
app.use(express.urlencoded({ extended: false, limit: '100kb', parameterLimit: 1000 }));

app.use('/api', apiRouter);

app.use((_req, res) => res.status(404).json({ message: 'Not found' })); // after every route
app.use(errorHandler); // last

Helmet

app.use(helmet()) sets a standard set of security headers, including Content-Security-Policy, Strict-Transport-Security (max-age=31536000; includeSubDomains), X-Content-Type-Options: nosniff, Referrer-Policy: no-referrer and Cross-Origin-Resource-Policy: same-origin. It removes X-Powered-By and sets X-XSS-Protection to 0. Cross-Origin-Embedder-Policy is not set by default. For a JSON API most of these are belt and braces. They matter when the same app also serves HTML, and they cost nothing. If a frontend on another origin loads your API assets or uses Cross-Origin-Resource-Policy-sensitive resources, adjust that one header instead of removing Helmet. Helmet does not replace TLS, which the Express guide recommends terminating at a proxy such as Nginx.

Rate limiting

The option names in express-rate-limit 8 are windowMs, limit (not max), standardHeaders ('draft-6', 'draft-7' or 'draft-8'), legacyHeaders and ipv6Subnet. The default key is the client IP address, so it depends on trust proxy being right. The default memory store gives inconsistent results with several servers or processes, because each instance counts separately, so use an external store when you run more than one. Two behaviours deserve a decision: by default, passOnStoreError blocks traffic when the store fails, and the 100-requests-per-15-minutes figure above is only an example, not a recommendation. Pick numbers from your own traffic.

Login endpoints need more than a global limit. The Express security guide recommends blocking on two metrics: consecutive failed attempts for the same username and IP, and total failures from one IP over a longer period. It points to the rate-limiter-flexible package for that. A tighter rateLimit() on the login route is a reasonable first step.

Body and upload limits

Express 5's body parsers come from body-parser 2. The documented defaults are a limit of '100kb' for JSON, text, raw and urlencoded bodies, a parameterLimit of 1000 for urlencoded, and a nesting depth of 32 when extended is true. A body over the limit is rejected with status 413 and the error type entity.too.large. The docs advise against very high limits and note that payloads of 5 MB or more can introduce risks. Set the limit explicitly, as in the skeleton, and raise it only on the one route that needs it. inflate: false rejects compressed request bodies, which can also act as a stopgap for compression bugs.

Uploads are a separate case, because multer's own limits default to Infinity for fileSize, files, fields, parts, fieldNestingDepth and fieldArrayIndexLimit, and 1 MB for fieldSize. Its docs say limits apply to the whole request and recommend setting them to values that match your application:

import multer from 'multer';

const upload = multer({
  limits: { fileSize: 5 * 1024 * 1024, files: 5, fields: 20, parts: 25 }, // example numbers
  fileFilter: (_req, file, cb) => cb(null, file.mimetype.startsWith('image/')), // synchronous
});

The synchronous fileFilter is deliberate: the October 2026 multer advisory (CVE-2026-113872, fixed in 2.5.0) affected applications that used an asynchronous fileFilter, while synchronous ones were not affected.

One error handler

The built-in handler sets the status from err.status, and it includes the stack trace in the body unless NODE_ENV is production. Write your own so the shape is predictable and nothing internal leaks:

import type { ErrorRequestHandler } from 'express';

export const errorHandler: ErrorRequestHandler = (err, _req, res, next) => {
  if (res.headersSent) return next(err); // let Express close the connection
  const status = Number.isInteger(err.status) && err.status >= 400 && err.status < 600 ? err.status : 500;
  if (status === 500) console.error(err); // send it to your logger, not to the client
  res.status(status).json({ message: status === 500 ? 'Internal Server Error' : err.message });
};

Body-parser errors carry a 4xx status, so a bad JSON body becomes a 400 and an oversized one a 413. The HTTP status codes reference helps when you decide which code a failure should return.

Keep it patched

Most Express risk after a migration is in the middleware. Two October 2026 advisories show why: body-parser CVE-2026-111181 (fixed in 2.4.0 and 1.20.9) lets one unauthenticated request crash the process, and the multer one above does the same with an async fileFilter. The Express team also documents a workaround for the Node.js Brotli bug (CVE-2026-111497): reject request encodings you do not need before any body parser runs. Body parsers accept gzip, br, deflate and zstd encodings, so that is worth doing if you do not need them. The full version tables are in Patching a MEAN Stack, and the process for scanning and fixing dependencies is in Node.js vulnerabilities: how to find, triage and fix them.

Migration test checklist

  • Every route with a wildcard, optional segment or regex path still matches the same URLs, and a request that should 404 does.
  • A rejected promise in an async handler returns your JSON error, not a hung request or a crash.
  • Query strings with arrays and nested objects parse as the code expects, or are rejected by validation.
  • A POST with no body or the wrong content type does not throw on req.body.
  • /.well-known/ files, if you serve any, return 200.
  • req.ip through the real proxy shows the client address, and a spoofed X-Forwarded-For does not change it.
  • An over-limit JSON body returns 413, and the 101st request in a window returns 429 with your limiter's headers.

Frequently asked questions

Is Express 5 faster?

This guide has no benchmark numbers, because none come from a primary source. The documented changes are in correctness and security: promise handling, stricter path syntax and a safer default for hidden files.

Will my middleware work with Express 5?

Check each package's documentation and its engines and dependency ranges, then test it. Express's own middleware packages move together. For example Express 5.3.0 depends on body-parser and router 2.x, and the current multer is 2.5.0.

Do I need TypeScript types changes?

The @types/express package is at 5.0.6 on npm, so update it together with Express.

If you want help migrating a production API, see my Node.js and Express API development service.

Sources