nestjs
Express 5, Fastify 5, and the adapter I did not swap

Last November I wrote that NestJS earns its keep over plain
Express mostly by settling arguments, and I
ended that post waiting on two things, Express 5 arriving properly and
require() of an ES module coming off its flag. Both happened this year, so
this is the follow-up. It also covers the question I got asked most in the
meantime, whether we should be on Fastify instead.
I'll say one thing up front, because it should colour how you read the middle of this. I have not run Fastify in production. I can tell you what it claims, what the swap would cost inside NestJS and why I decided against finding out on a billing service. I can't tell you what its p99 looks like under our load, because I haven't measured it.
The Nest 11 upgrade was an Express 5 upgrade
NestJS 11 shipped on 22 January.
It requires Node 20 or newer, and the change that reaches furthest is that
@nestjs/platform-express now sits on Express 5, where it used to be Express 4.
Express 5 itself became the npm latest tag
on 31 March
with 5.1.0, about six months after it was published, so by spring this was
simply where the ecosystem was.
Most of the application didn't notice, because we had let the framework own the router. What broke was the code where we had gone past Nest and touched Express directly.
Wildcards had to be named. Express 5 moved to path-to-regexp 9, and a bare
* is no longer a valid path:
// Nest 10 / Express 4
@All('*')
notFound() {}
// Nest 11 / Express 5
@All('*splat')
notFound() {}
That caught our catch-all route, a proxy path and a useGlobalPrefix
exclusion pattern (that last one took longest to find). They were all easy to
fix. But path matching changes at runtime and the compiler has nothing to say
about it, so the way you find each one is by requesting the URL.
The deprecated response signatures are gone. res.send(status, body),
res.json(status, obj) and res.sendfile() no longer exist, and
res.redirect(url, status) has its arguments the other way round. In a Nest
codebase these only show up where someone used @Res() to take the raw
response object. For us that was two file-download endpoints and a legacy
redirect.
The body parser changed its defaults. urlencoded now defaults extended to
false, and req.body is no longer initialised to {} for every request. If
you have a guard or interceptor that reads req.body.something on a GET,
that used to be undefined and is now a TypeError. We had one, in an
audit-logging interceptor. It's the least-exercised code path we have and it
has the widest reach. Grep for req.body before you upgrade rather than
after.
The logger change is the one operations noticed
The change I'd have paid for by itself has nothing to do with routing. Nest
11's ConsoleLogger takes a json option.
const app = await NestFactory.create(AppModule, {
logger: new ConsoleLogger({
json: true,
colors: false,
}),
})
We ship container logs to OpenSearch. Before this, Nest's pretty human-readable line had to be reconstructed on the way in by a grok pattern that got the message right and the context wrong roughly whenever anyone logged an object. Now the framework emits structured records and the ingest pipeline doesn't have to guess. Multi-line stack traces stop being several documents, too.
It's a small feature, and it got rid of a category of "the logs are lying to me" incidents. I keep the pretty logger locally and JSON everywhere else, picked by the same environment flag that picks the rest of the config.
Fastify, from the outside
Fastify 5 was released on 17 September
2024 and requires Node 20 or
newer. NestJS 11 supports it through @nestjs/platform-fastify, and switching
adapters is, on paper, one line:
const app = await NestFactory.create<NestFastifyApplication>(
AppModule,
new FastifyAdapter(),
)
What follows is what Fastify does differently as I understand it from its docs and its maintainers. I haven't operated it.
It is schema-first in both directions. You give a route a JSON Schema, and
Fastify uses it to validate the request and to compile a serialiser for the
response with fast-json-stringify. The second half matters more, I think.
Serialising a known shape through generated code, instead of JSON.stringify
walking an unknown object, accounts for a meaningful part of the claimed
throughput advantage. That's an architectural difference and I wouldn't file
it under micro-optimisation.
Its plugin system is encapsulated. Register a plugin inside a scope and its hooks and decorators apply to that scope only. Express middleware is a flat list applied in registration order to whatever comes after it. That's simple to explain, and in a large app it's easy to get subtly wrong.
In practice the swap is more then one line. "Just change the adapter" is the version of this advice that gets repeated though, so concretely:
- Express middleware doesn't apply.
@fastify/helmet,@fastify/cors,@fastify/multipartreplace their Express equivalents, with different options and different defaults. @Res()hands you a Fastifyreply, not an Expressres. Every place that takes the raw object needs rewriting, so for us the two download endpoints above.- Anything in your dependency tree that assumes Express assumes wrong. Passport
strategies, some APM and instrumentation middlewares, and a fair number of
small libraries take
(req, res, next)and are done. - Static assets, view engines and file upload handling are configured through different packages.
- Nest's own validation pipe and DTOs still work. So you keep
class-validator, and you get none of thefast-json-stringifyserialisation benefit unless you also move to schemas. The headline number and the drop-in change are two different projects.
This doesn't make Fastify worse. It makes the adapter swap cheap to start and expensive to half-finish, and a billing service is a bad place to discover which bits you missed.
The benchmark that would change my mind is not the one on the website
Framework benchmarks measure a framework returning a small fixed payload with no work behind it. That's a legitimate measurement of the framework. As a prediction about a service it is nearly useless.
On the endpoints I care about, a request spends its time in Mongo, in Stripe, in Redis, and in our own aggregation. The router is single-digit percentages of that budget. Halving the router's share would be a real gain, but what stands between us and a better p99 is the query that does a collection scan when a tenant crosses some row count.
If I were starting a latency-critical service with few routes and a schema I was willing to write down twice, Fastify would be on the list. I'd benchmark it against my own payloads, my own middleware and my own database, and I'd look at p99 and not the mean. For an existing service where the router isn't the bottleneck, changing it is a migration paid for by a number I have not measured. I would rather spend that week on the index.
Node 24 went LTS three weeks ago
Node 24 became Active LTS on 28 October as Krypton, with support running to April 2028. It ships V8 13.6, npm 11 and Undici 7. Four things in it have changed how we write code, and one has been a useful trap to understand.
require() of an ES module is now unflagged. This is the one I was waiting
for last year. A Nest build is CommonJS and a growing number of small
libraries ship ESM only. Where the two met you used to get ERR_REQUIRE_ESM
and a choice between pinning an old major, await import() in an async
factory, or converting the build. Now it just works:
const { greet } = require('./esm/index.js') // package.json has "type": "module"
There's one hard limit to know about before you rely on it. The module graph has to be synchronous:
Error [ERR_REQUIRE_ASYNC_MODULE]: require() cannot be used on an ESM graph
with top-level await. Use import() instead.
So a library that awaits at the top level of its entry point is still off
limits from require, and --experimental-print-required-tla will tell you
which file in the graph did it.
AsyncLocalStorage now defaults to AsyncContextFrame. Request-scoped
context (tenant, correlation id, the authenticated principal) is what people
use Scope.REQUEST providers for, and request-scoped providers make Nest
rebuild part of the injection graph per request. Put the context in an
AsyncLocalStorage instead and every provider stays a singleton, and any
layer can read the current request's values without threading a parameter
through five call sites. Node 24 rebuilt the propagation on
AsyncContextFrame by default, which makes the approach cheaper across
await boundaries. I'd now default to it for anything ambient.
URLPattern is global now, no import. Handy for the webhook router, which
used to own a small pile of regexes.
The permission model lost its --experimental- prefix. It's --permission
now, with --allow-fs-read, --allow-fs-write and friends. We run it on the
short-lived jobs - a reconciliation script has no business opening a socket -
and not yet on the API, where the allow-list would be large enough to be
theatre.
From V8 13.6 the ones we have used so far are Error.isError(), which
answers the cross-realm question instanceof Error gets wrong, and
RegExp.escape(). That one deletes a hand-rolled escaping helper that every
codebase has and that is wrong in at least one repository per company.
node src/main.ts will never run a Nest app
Node has run TypeScript files directly since type stripping went on by default in 23.6 (and it was backported to 22.18), so the obvious question is whether that removes the Nest build step. It does not, and I don't see it as a feature that's merely missing so far. The reason is structural.
Type stripping erases types and doesn't transform syntax. NestJS is built on two pieces of syntax that can't be erased. Decorators do not parse at all:
@Controller()
^
SyntaxError: Invalid or unexpected token
And parameter properties (the private readonly in every Nest constructor)
are rejected explicitly:
constructor(private readonly service: Service) {}
^^^^^^^^^^^^^^^^
SyntaxError [ERR_UNSUPPORTED_TYPESCRIPT_SYNTAX]: TypeScript parameter
property is not supported in strip-only mode
Neither is an oversight. Decorators are still a TC39 stage 3 proposal and Node won't ship a transform for a proposal that isn't in the language. And the design goal of strip-only mode is that it removes characters without moving the ones that remain, so line numbers in a stack trace still point at your source. Parameter properties would require generating assignments.
Even if both were transformed, it wouldn't be enough. Nest's container
resolves constructor dependencies from the type metadata that
emitDecoratorMetadata writes and reflect-metadata reads back. A stripper
throws that away by definition. Native TypeScript execution in Node is a
convenience for scripts and small ESM services. For a Nest application the
answer is still tsc or SWC, with experimentalDecorators and
emitDecoratorMetadata on. I'd rather the compile step were plainly required
than have it half-work.
Where this leaves the stack
NestJS 11 on Express 5, on Node 24, with a compile step, structured logs and
context in AsyncLocalStorage. The Express 5 migration took a couple of days
and all of it was in the places where we had gone around the framework. I
take that as a reasonable argument for not doing that in the first place.
Fastify stays something I have read about. If I start something small and latency-sensitive I'll try it properly and measure it, and if that happens I'll write down my own numbers instead of somebody else's.


