Skip to content

Web Development · Backend

Express 4 to 5 Migration: What Breaks and How to Fix It

Express 4's earliest end-of-life date has passed. Moving to Express 5.3 takes a codemod, new route syntax and four request changes. Here is each fix, with code.

Abhishek Gupta

Abhishek Gupta

11 min read

A paper-cut locomotive crossing a switch from a worn, patched railway track onto a clean new track curving across layered paper hills

Sponsored

Share

Between November 17 and 23, 2026, npm served Express 4 about 82.3 million times. That’s 39% of all Express downloads that week, more than a year and a half after Express 5 became the default latest tag, and after the date the Express team gave as the earliest possible end of life for 4.x. If one of those installs is yours, migrate from Express 4 to 5 now, target 5.3.0, and budget most of the effort for route strings and request parsing, not for the renamed methods.

This guide works from the official Express 5 migration guide, the release notes on GitHub, and a test app run against Express 5.3.0 on Node 22 to confirm the error messages quoted below.

Horizontal bar chart of Express downloads by version for November 17 to 23, 2026: 5.2.1 leads with 68.5 million, then 5.3.0 at 46.5 million and 4.22.3 at 29.9 million; all 5.x versions total 127.2 million (61%) and all 4.x versions total 82.3 million (39%)

Should you migrate from Express 4 to 5 now?

Yes. Express 4 has been in maintenance since April 1, 2025, its end of life is set for no sooner than October 1, 2026, and the 5.x line has had two years of releases. The upgrade needs Node.js 18 or newer, one codemod run, and a manual pass over route paths, req.body, req.query and static files.

The honest caveat on dates: the Express team wrote that its schedule was “goals not commitments” and that v4 is “a special case” whose maintenance it might extend. The support page still lists 4.x as ongoing, and 4.22.3 shipped on September 14, 2026. So nothing stops working on a given morning. What you have is a window that has opened and could close with one blog post, while every middleware author ships their next major against 5.x.

LineStatus todayKey dates
4.xMaintenance, latest 4.22.3Maintenance from Apr 1, 2025; EOL no sooner than Oct 1, 2026
5.xActive, latest 5.3.0 (Oct 9, 2026)Default on npm since 5.1.0 (Mar 31, 2025); maintenance starts when v6 ships
6.xNot releasedNo date

Express 5 needs Node 18, but don’t stop there. Node 18 lost security support in April 2025, so if the app is that old, move the runtime too. The Node.js 24 to 26 upgrade checklist covers that side, and doing both in one release cycle is reasonable as long as they ship as separate deploys.

Step 1: check your middleware before you touch Express

In most Express apps, the middleware stack is where an upgrade breaks, not the routes you wrote. Before bumping the version, list what you load:

npm ls --depth=0 | grep -iE "express|passport|multer|helmet|cors|session|validator|sanitize|async"
npm view @types/express dist-tags.latest   # 5.0.6 at the time of writing

Three kinds of package cause trouble. The first is anything that patches Express internals, the clearest case being express-async-errors (more on it below). Second come packages that write to req.query, which many sanitizers and validators did in their Express 4 versions. Third is code that declares express@^4 as a peer dependency: npm 7 and later refuse to install it next to Express 5 with an ERESOLVE error, which at least makes it easy to spot. express-async-errors 3.1.1, last published in 2022, peers on express@^4.16.2, so it fails that way.

If you write TypeScript, bump @types/express to 5.x in the same commit. Mixing express@5 with 4.x types gives you type errors that point at the wrong problem.

Step 2: run the codemod

The Express team publishes a migration recipe through codemod.com:

npx codemod@latest @expressjs/v5-migration-recipe

It rewrites the mechanical changes. Run it on a clean branch and read the diff, because it’s quick to review and you’ll want to know what moved.

Express 4Express 5
app.del('/x', fn)app.delete('/x', fn)
req.param('id')req.params.id, req.body.id or req.query.id, explicitly
res.json(obj, 201) / res.send(obj, 201)res.status(201).json(obj)
res.send(200)res.sendStatus(200)
res.redirect('/users', 302)res.redirect(302, '/users')
res.redirect('back')res.redirect(req.get('Referrer') || '/')
res.sendfile(path)res.sendFile(path)
req.acceptsCharset() and friendsreq.acceptsCharsets() (plural)
express.static.mimethe mime-types package

The codemod can only rewrite what it can see. A res.send(statusCode) where statusCode is a variable, or a helper that wraps res.json with two arguments, won’t be caught. Grep for res.send( and .json( with a comma inside the parentheses after the run.

Step 3: fix route paths, the part that breaks at startup

Express 5 moved routing into the router package, which uses path-to-regexp 8. The path grammar changed, and invalid paths now throw when the route is registered, so the app dies before it serves a request. That is the good news: you find all of them on the first boot.

Here is what Express 5.3.0 prints for the two most common Express 4 patterns:

app.get('*', ...)
PathError: Missing parameter name at index 1: *; visit https://git.new/pathToRegexpError for info

app.get('/:file.:ext?', ...)
PathError: Unexpected ? at index 11: /:file.:ext?; visit https://git.new/pathToRegexpError for info

The fixes:

// Catch-all: wildcards need a name now
app.get('/*splat', handler);     // matches /a and /a/b, but NOT /
app.get('/{*splat}', handler);   // also matches /

// Optional segments use braces instead of ?
app.get('/:file{.:ext}', handler);

// Regex-ish alternatives become an array of paths
app.get(['/discussion/:slug', '/page/:slug'], handler);

The /*splat versus /{*splat} difference is the one that bites SPAs. An Express 4 fallback like app.get('*', serveIndexHtml) covered the root URL. Its literal translation, /*splat, does not, so the home page 404s while every deep link works. Use /{*splat}.

Two more changes to the matched values. A wildcard param is now an array of segments, so GET /foo/bar against /*splat gives req.params.splat as ['foo', 'bar'], not 'foo/bar'. Call .join('/') where you need the string. And unmatched optional params are omitted instead of set to undefined, which only matters if you checked with 'ext' in req.params.

The characters ()[]?+! are reserved in paths now. If a route literally contains one, escape it with a backslash.

Step 4: the request changes your type checker won’t catch

These four compile fine and fail at runtime, which is why they deserve the most test time.

req.body is undefined when no parser ran. Express 4 defaulted it to {}. Code like const { email } = req.body on a route with no express.json() in front of it, or on a request with no body, now throws a TypeError. Search for destructuring of req.body and either mount the parser on that route or default it: const { email } = req.body ?? {}.

req.query is a getter, and the default parser changed. The default moved from “extended” (the qs library) to “simple” (Node’s querystring). A request to /search?filter[status]=open used to give you { filter: { status: 'open' } }. On Express 5 it gives { 'filter[status]': 'open' }. Repeated keys still become arrays (?tags=a&tags=b gives ['a', 'b']), so plain filter UIs keep working while anything that sends bracket syntax quietly breaks. If your API or a client library depends on nested objects, opt back in explicitly:

app.set('query parser', 'extended');

The getter is the subtler half. Assigning to req.query behaves differently depending on strict mode, which is easy to miss in a test. In a sloppy-mode CommonJS file, req.query = sanitized is silently ignored and your handler reads the unsanitized original. In strict mode (ES modules, TypeScript output, or 'use strict') it throws:

TypeError: Cannot set property query of #<IncomingMessage> which has only a getter

The silent version is the dangerous one, because validation middleware that “cleans” the query string stops cleaning it and nothing errors. Write the cleaned value to a new property and read that in handlers:

app.use((req, res, next) => {
  req.validatedQuery = schema.parse(req.query);
  next();
});

req.host keeps the port. Behind a proxy on a non-standard port, req.host now returns example.com:8443 where Express 4 returned example.com. Tenant lookups and allow-lists keyed on hostname are where this shows up. Use req.hostname if you want the name alone.

req.params has a null prototype for string paths, so req.params.hasOwnProperty('id') throws. Use Object.hasOwn(req.params, 'id').

Step 5: delete your async error wrappers

This is the change worth looking forward to. In Express 5, a handler that throws inside an async function or returns a rejected promise forwards the error to next(err) on its own:

app.get('/users/:id', async (req, res) => {
  const user = await db.users.findById(req.params.id); // a rejection here...
  res.json(user);
});

app.use((err, req, res, next) => {                      // ...lands here
  res.status(500).json({ error: 'internal' });
});

So remove the workarounds: express-async-errors, express-async-handler, and the homegrown asyncHandler(fn) wrappers. The first one isn’t optional to remove. It does require('express/lib/router/layer') to monkey-patch Express 4’s router, that file doesn’t exist in Express 5, and the app crashes on load with Cannot find module 'express/lib/router/layer'. Wrapper functions like asyncHandler keep working, so they can go in a later cleanup.

One related change: app.listen now passes errors such as EADDRINUSE to its callback instead of throwing, so a callback that ignores its first argument will log “listening” on a port it never got. Check the argument.

Step 6: static files and .well-known

express.static() now defaults to dotfiles: 'ignore', and the check covers dot-directories anywhere in the path. That means /.well-known/ returns 404. Apple universal links, Android app links and ACME HTTP challenges all live there, and none of them fail loudly. Your app works, your deep links on phones stop working, and you find out from a support ticket.

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

The same rule applies to res.sendFile(). A path such as /var/www/app/.cache/index.html now returns 404 unless you pass dotfiles: 'allow' or set root to the dot-directory.

While you’re in this layer, two smaller changes. express.urlencoded() now defaults to extended: false, so form posts with nested field names (user[name]) arrive flat unless you pass { extended: true }. And .js files are now served as text/javascript rather than application/javascript, which only matters if a test asserts the exact header.

Smaller changes, one line each

  • res.status() only accepts integers from 100 to 999 and throws otherwise. Watch for res.status(err.code) where code is a string like 'ENOENT'.
  • res.vary() with no argument throws.
  • res.clearCookie() ignores maxAge and expires.
  • router.param() no longer takes an array of names.
  • Debug output moved: use DEBUG=express:*,router,router:*.
  • 5.3.0 stopped quoting Content-Disposition filenames that are valid HTTP tokens, so a test that asserts filename="report.csv" byte for byte fails.

How to roll it out

Keep the upgrade to one pull request with three commits: the codemod output, the manual fixes, and the dependency removals. Then test in this order, because it matches where failures hide.

  1. Boot the app. Every bad route path throws here, so a clean start means Step 3 is done.
  2. Hit the edges, not the happy paths. Root URL on any catch-all, a request with no body to each POST route, a query string with brackets, /.well-known/ files, an async route that rejects.
  3. Run the suite in strict mode. If your tests are sloppy-mode CommonJS and your production build isn’t (or the other way round), the req.query assignment behaves differently in each.
  4. Ship behind your normal canary, and watch 404 rates on static paths and 400s on endpoints that take filters.

If the codebase is large and nobody wants a single cutover, the strangler fig pattern works for this too: put an Express 5 service behind the same proxy and move route groups over one at a time. That’s usually overkill for a framework upgrade of this size, but it’s the right call for a monolith where nobody knows what every route does.

And if this migration is the moment you’re asking whether to stay on Express at all, that’s a separate decision. NestJS runs on Express 5 by default from v11, so you’d do this work anyway, while Fastify means rewriting handlers and middleware, a much bigger job than anything in this guide. Express 5 is a contained upgrade, and most of the time goes into Steps 3 and 4. Start with npm ls, then the codemod, then boot the app and let the route errors tell you what’s left.

Frequently asked questions

Is Express 4 end of life?
Not formally. The Express team set a target of no sooner than October 1, 2026 and said it might extend support for 4.x. As of late November 2026 the official support page still lists 4.x as ongoing, and 4.22.3 shipped on September 14, 2026. Plan as if the date can be announced at any time.
Can I run Express 5 on Node.js 18?
Express 5 declares Node.js 18 as its minimum, so it installs and runs there. Node 18 itself stopped getting security fixes in April 2025, though, so pair this upgrade with a move to a supported Node release rather than treating 18 as a target.
Does the Express 5 codemod fix everything?
No. It rewrites method calls such as res.json(obj, status), res.sendfile, req.param and app.del. Route path strings, req.body and req.query handling, dotfile serving and third-party middleware compatibility all need a manual pass and a test run.

Sources

Sponsored

Sponsored

Discussion

Join the conversation.

Comments are powered by GitHub Discussions. Sign in with your GitHub account to leave a comment.

Sponsored