How does the NestJS platform adapter layer work?
NestJS does not talk to an HTTP server directly. The framework core handles routing metadata, dependency injection and the request pipeline, then delegates the actual server work to an HTTP adapter: registering routes, reading request data, writing responses and starting the listener. ExpressAdapter from @nestjs/platform-express is used by default. To run on Fastify, you install @nestjs/platform-fastify and pass a FastifyAdapter instance as the second argument to NestFactory.create.
The generic type on NestFactory.create, either NestExpressApplication or NestFastifyApplication, does not change runtime behavior. It exposes the platform-specific methods on the app object so the compiler knows which API surface you are using.
What is portable and what is coupled
Most code that stays inside Nest's abstractions moves between adapters unchanged:
- Controllers using
@Body,@Param,@Queryand@Headers - Guards, pipes and interceptors that read from
ExecutionContextwithout pulling out the underlying request - Exception filters that rethrow or map errors without writing the response themselves
Code that touches the platform directly is coupled to one adapter:
- Handlers using
@Req()or@Res() - Filters that call Express-style
response.status().json(), which has no equivalent on a Fastify reply. Fastify usesreply.status().send(). - Anything registered with
app.use - Imports of Express or Fastify types
Changing adapters takes a few lines of code. The larger change is in behavior. Body parsing, middleware semantics, plugin scoping and error formatting all come from the underlying server, and the abstraction does not hide those differences.
+------------------------------------------------------------+
| PORTABLE: your code inside Nest abstractions |
| Controllers: @Body @Param @Query @Headers |
| Guards, pipes, interceptors via ExecutionContext |
| Exception filters that rethrow or map errors |
+------------------------------------------------------------+
|
v
+------------------------------------------------------------+
| NESTJS CORE |
| routing metadata | dependency injection | request pipeline |
+------------------------------------------------------------+
| delegates: routes, request,
| response, listener
+----------------+----------------+
v v
+---------------------------+ +---------------------------+
| ExpressAdapter (default) | | FastifyAdapter |
| @nestjs/platform-express | | @nestjs/platform-fastify |
| NestExpressApplication | | NestFastifyApplication |
+---------------------------+ +---------------------------+
v v
+---------------------------+ +---------------------------+
| Express | | Fastify |
| res.status().json() | | reply.status().send() |
| body parsing, middleware, | | body parsing, middleware, |
| plugins, error format | | plugins, error format |
+---------------------------+ +---------------------------+
COUPLED: @Req()/@Res(), app.use, Express/Fastify types,
and filters that write the response directly.
Code inside Nest's abstractions runs on either adapter. Code that touches raw req/res, app.use or platform types is tied to one server, and body parsing, middleware, plugin and error behavior come from that server.
NestJS Fastify vs Express: which adapter fits your service?
| Dimension | Express | Fastify |
|---|---|---|
| Ecosystem | Very large; most Node middleware targets it | Smaller; @fastify/* plugins replace common middleware |
| Middleware | Native (req, res, next) |
Runs through a compatibility hook; not every package works |
@Res() object |
res.status().json() |
reply.code().send() |
| Default bind host | All interfaces | Localhost only |
| JSON body limit | 100 KB | 1 MiB |
| Trailing slash, case | /a = /a/, case-insensitive |
Distinct routes, case-sensitive |
| File uploads | FileInterceptor (multer) |
Needs a multipart plugin |
Several of these defaults change behavior without any error. A containerized service that calls listen(port) on Fastify binds to localhost and never receives traffic from outside the container. Clients that sent /Users/ start receiving 404s. Errors raised by the server itself, such as oversized or unparseable bodies, return Fastify's error format before your exception filters run.
Fastify fits high-RPS, low-latency services with small payloads, where framework overhead is a meaningful share of each request. It also fits greenfield code and codebases that already avoid @Res() and raw middleware. Express is still the better choice if you depend on Express-specific middleware or write handlers against res. It is also the better choice if most of your latency comes from database or downstream calls. In that case, a faster router saves little.
You also have alternatives to a direct switch:
- Stay on Express. This is a reasonable choice if you have no throughput problem to solve.
- Refactor to be adapter-agnostic first. Replace
@Res()with return values and interceptors. Replace raw middleware with guards and pipes. This makes any later switch mechanical. - Use a compatibility layer. Run legacy Express middleware through Fastify's middleware support while you migrate. Treat it as temporary, because it can cost some of the performance you switched for.
How do you switch a NestJS app from Express to Fastify?
The minimal switch touches three places. Install @nestjs/platform-fastify (and fastify if your package manager doesn't pull it in), then pass new FastifyAdapter() as the second argument to NestFactory.create<NestFastifyApplication>(). The generic types the returned app, so adapter-specific methods such as register are visible to the compiler. Finally, call listen with an explicit host: app.listen(3000, '0.0.0.0').
The host argument is the step people skip. Fastify binds to localhost by default, so the server accepts connections only from inside its own network namespace. On a laptop this changes nothing. In a container, kubelet probes and sibling services connect through the pod's network interface, not loopback. Probes fail, the pod restarts, and the logs show a healthy "listening" line. Pass '0.0.0.0', or read the host from config.
Next, audit every @Req() and @Res(). They now return FastifyRequest and FastifyReply, so Express-typed handlers won't compile:
res.status(201).json(body)fails becauseFastifyReplyhas nojson(). Usereply.code(201).send(body).sendserializes objects and sets the content type.res.localsdoesn't exist. Attach per-request state to the request object instead.req.ipstill exists. Behind a load balancer, set Fastify'strustProxyoption on the adapter instead of Express'sapp.set('trust proxy').
The more durable fix is to stop injecting the response at all. Return a value and declare @HttpCode() and @Header() on the handler. Nest then writes the response through whichever adapter is active, and interceptors and exception filters still see the result. That keeps controllers free of adapter-specific code.
// main.ts
import { NestFactory } from '@nestjs/core';
import { FastifyAdapter, NestFastifyApplication } from '@nestjs/platform-fastify';
import { AppModule } from './app.module';
async function bootstrap() {
// The generic exposes Fastify-specific methods such as register().
// trustProxy replaces Express's app.set('trust proxy') so req.ip is the client IP behind a load balancer.
const app = await NestFactory.create<NestFastifyApplication>(
AppModule,
new FastifyAdapter({ trustProxy: true }),
);
// Fastify binds to localhost by default. Bind to all interfaces so kubelet probes
// and other pods can reach the server through the pod's network interface.
await app.listen(Number(process.env.PORT ?? 3000), process.env.HOST ?? '0.0.0.0');
}
bootstrap();
// orders.controller.ts
import { Body, Controller, Header, HttpCode, Post, Res } from '@nestjs/common';
import type { FastifyReply } from 'fastify';
@Controller('orders')
export class OrdersController {
// Preferred: return a value. Nest writes it through whichever adapter is active,
// and interceptors and exception filters still see the result.
@Post()
@HttpCode(201)
@Header('Cache-Control', 'no-store')
create(@Body() dto: { sku: string }) {
return { id: 'ord_123', sku: dto.sku };
}
// If you must use the raw reply: Express's res.status(201).json(body) becomes this.
@Post('legacy')
createLegacy(@Body() dto: { sku: string }, @Res() reply: FastifyReply) {
reply.code(201).send({ id: 'ord_124', sku: dto.sku }); // send() serializes and sets content-type
}
}
A minimal Fastify bootstrap with an explicit 0.0.0.0 host and trustProxy, plus a controller that compares the preferred return-value style using @HttpCode/@Header with the raw FastifyReply equivalent of res.status().json().
Why does Express middleware break or misbehave on Fastify?
Middleware is where adapter differences surface first. A class registered through configure(consumer) still runs on Fastify, but Nest mounts it through Fastify's middleware layer, which passes the raw Node IncomingMessage and ServerResponse rather than Express's decorated objects. That layer runs early in the request lifecycle, before Fastify parses the body. As a result, req.body is undefined, res.locals does not exist, and helpers such as res.status().json() or req.get() are missing. TypeScript often won't flag any of this, because many middleware signatures are typed loosely.
You have three ways to handle it:
- Use a Fastify-native plugin. Find or write one that hooks into Fastify's lifecycle.
- Rewrite as a guard or interceptor. Logic that only needs request context, such as auth checks, tenant resolution or timing, fits Nest's own primitives. These primitives work the same on both adapters.
- Register
@fastify/express. This compatibility plugin restores much of Express's middleware behaviour, but it adds per-request overhead and doesn't cover the whole Express API. It also turns what would be visible porting work into runtime bugs that show up only on specific code paths.
Most common Express packages have Fastify counterparts that you register with app.register():
| Concern | Express package | Fastify equivalent |
|---|---|---|
| CORS | cors |
@fastify/cors, or app.enableCors() |
| Security headers | helmet |
@fastify/helmet |
| Cookies | cookie-parser |
@fastify/cookie |
| Compression | compression |
@fastify/compress |
| Multipart uploads | multer |
@fastify/multipart |
| Static files | serve-static |
@fastify/static |
Uploads need extra attention. FileInterceptor and the related decorators from @nestjs/platform-express are built on Multer and depend on Express, so they won't work on Fastify. Any upload endpoint has to be rewritten against the multipart plugin's API.
// main.ts: bootstrap on Fastify and register native plugins in place of Express middleware
import { NestFactory } from '@nestjs/core';
import {
FastifyAdapter,
NestFastifyApplication,
} from '@nestjs/platform-fastify';
import helmet from '@fastify/helmet';
import fastifyCookie from '@fastify/cookie';
import compression from '@fastify/compress';
import multipart from '@fastify/multipart';
import fastifyStatic from '@fastify/static';
import { join } from 'path';
import { AppModule } from './app.module';
async function bootstrap() {
const app = await NestFactory.create<NestFastifyApplication>(
AppModule,
new FastifyAdapter(),
);
// CORS: Nest's built-in helper uses @fastify/cors under the hood on this adapter
app.enableCors({ origin: [''], credentials: true });
// Replaces helmet, cookie-parser and compression from the Express setup
await app.register(helmet);
await app.register(fastifyCookie, { secret: process.env.COOKIE_SECRET ?? 'dev-only-placeholder' });
await app.register(compression, { encodings: ['gzip', 'deflate'] });
// Replaces multer. FileInterceptor/@UploadedFile() are Express-only;
// read uploads from the Fastify request instead (e.g. await req.file()).
await app.register(multipart, { limits: { fileSize: 10 * 1024 * 1024 } });
// Replaces serve-static
await app.register(fastifyStatic, { root: join(__dirname, '..', 'public'), prefix: '/public/' });
// Fastify listens on 127.0.0.1 by default; bind all interfaces for containers
await app.listen(3000, '0.0.0.0');
}
bootstrap();
A NestJS Fastify bootstrap that swaps each common Express middleware package for its Fastify plugin via app.register(), with CORS handled by enableCors().
Body parsing, raw bodies and plugin encapsulation gotchas
Fastify does not use body-parser. It ships with parsers for JSON and plain text, and anything else (form-encoded bodies, XML, custom media types) needs a content-type parser registered on the underlying instance through addContentTypeParser, or a plugin such as @fastify/formbody. Size limits move as well. Instead of a limit option on body-parser, you set bodyLimit in the options passed to FastifyAdapter.
For webhook signature verification, pass rawBody: true to NestFactory.create. Nest then attaches the unparsed buffer to req.rawBody, and you can type the request with RawBodyRequest. You need this because signatures are computed over the exact bytes received, and re-serializing the parsed JSON rarely reproduces them.
Encapsulation causes more confusion than parsing does. Every register call creates a child context. Decorators, hooks and parsers added inside that context stay invisible to the parent and its siblings unless the plugin is wrapped with fastify-plugin. A hook can therefore register without errors and never run on the routes Nest mounted elsewhere.
Timing has the same effect. Nest builds its routes during app.init() or listen(). Once Fastify is ready, it refuses further plugin registration. Plugins added later either throw or attach too late to matter, so register them before initialization.
Integrations have their own adapter-specific setup:
- Swagger: depends on
@fastify/staticto serve the UI. - GraphQL: needs a driver with Fastify support. Mercurius is the Fastify-native option.
- View engines: configured through
@fastify/view. - Global prefix and versioning: worth retesting against any middleware path matching.
Before you switch, confirm that each library you depend on supports Fastify.
import { NestFactory } from '@nestjs/core';
import { FastifyAdapter, NestFastifyApplication } from '@nestjs/platform-fastify';
import { Controller, Headers, Post, Req, RawBodyRequest, UnauthorizedException } from '@nestjs/common';
import { FastifyRequest } from 'fastify';
import fastifyFormbody from '@fastify/formbody';
import { createHmac, timingSafeEqual } from 'node:crypto';
import { AppModule } from './app.module';
async function bootstrap() {
const app = await NestFactory.create<NestFastifyApplication>(
AppModule,
new FastifyAdapter({ bodyLimit: 1_048_576 }), // replaces body-parser's `limit` (1 MiB)
{ rawBody: true }, // keep the unparsed buffer on req.rawBody
);
// Register plugins and parsers BEFORE listen(); Fastify rejects them once ready.
await app.register(fastifyFormbody); // application/x-www-form-urlencoded
app.getHttpAdapter().getInstance().addContentTypeParser(
'application/xml', { parseAs: 'string' }, (_req, body, done) => done(null, body), // pass XML through as a string
);
await app.listen(3000, '0.0.0.0');
}
bootstrap();
@Controller('webhooks')
export class WebhookController {
@Post()
handle(@Req() req: RawBodyRequest<FastifyRequest>, @Headers('x-signature') signature = '') {
// Sign the exact received bytes, not re-serialized JSON.
const expected = createHmac('sha256', process.env.WEBHOOK_SECRET ?? 'placeholder-secret')
.update(req.rawBody ?? Buffer.alloc(0))
.digest('hex');
const a = Buffer.from(expected);
const b = Buffer.from(signature);
if (a.length !== b.length || !timingSafeEqual(a, b)) throw new UnauthorizedException();
return { received: true };
}
}
A Fastify-based Nest bootstrap that sets the body size limit on the adapter, enables rawBody for HMAC webhook verification, and registers a form-body plugin and an XML content-type parser before listen().
Does Fastify make NestJS faster in practice?
Fastify's lower per-request overhead comes from two places. Its router uses a radix tree, so route matching stays cheap as you register more routes, while Express walks its middleware and route stack in order. When a route declares a response schema, Fastify also compiles a serializer for that shape ahead of time instead of calling generic JSON.stringify. Both savings are small fixed costs per request. They matter most on high-RPS, low-latency endpoints with small payloads, such as health checks, token introspection and cache-backed lookups.
Nest does not turn your DTOs into Fastify response schemas automatically. Unless you attach schemas yourself through route options, responses use standard serialization, and you get only the router and core overhead savings.
Illustrative estimate (assumed inputs, not measured): a handler spends 15 ms on a database query, 3 ms on business logic and 0.4 ms in framework overhead on Express. If Fastify cuts the overhead to 0.2 ms, latency drops from 18.4 ms to 18.2 ms, about 1%. The same 0.2 ms saving on a 1 ms in-memory endpoint is closer to 20%.
Published microbenchmarks usually measure hello-world routes, which is the case least like your real traffic. To measure your own app:
- Run identical endpoints on both adapters with the same configuration, hardware and backing services.
- Drive them with an HTTP load generator at a fixed request rate.
- Compare p50 and p99 latency and CPU per request, not only peak throughput.
What does a migration cost, and how can you reduce the engineering time?
Most of the cost is finding Express assumptions, not changing the bootstrap file. Start with an inventory:
- Grep for
@Req()and@Res(). Handlers that callres.status().json()or readreq.iporreq.cookiesdepend on Express object shapes. - Grep for Express type imports and
app.usecalls. Each one is a place where Express middleware semantics are assumed. - List every third-party middleware. For each, record whether a Fastify plugin replaces it, it runs under the middleware compatibility layer, or it needs rewriting.
Before you change anything, write contract tests for client-visible behavior: status codes, headers, error body shapes, cookie attributes and content types. These tests show what changed when you switch adapters. Run e2e tests with supertest against the server behind app.getHttpAdapter().getInstance(). Await app.init() and the Fastify instance's ready() first, or routes and plugins may not be registered when the first request arrives. Finally, roll out behind a canary and compare error rates and latency against the Express fleet.
The ongoing cost is easy to underestimate. Supporting both adapters means two CI matrices and two sets of edge cases in every shared module. Your team also has to learn Fastify's hook lifecycle and plugin encapsulation, which do not map one-to-one onto Express middleware. Pick one adapter per service.
The work that pays off regardless of which adapter you choose is staying adapter-agnostic. Use DTOs, interceptors, guards and exception filters instead of raw request and response objects. A codebase written this way can switch adapters in days instead of weeks.
If profiling shows the framework is a small share of request time compared with database calls or downstream services, migrating for speed alone is rarely worth the risk.
When to avoid it
Keep Express when the switch would cost more than it returns. These warning signs usually show up before any code is changed:
- Controllers depend on the Express request and response objects. Search for
@Req()and@Res(). If handlers callres.locals,res.redirect,req.sessionor set headers through Express helpers in many places, each call site needs rewriting and retesting. Dozens of hits across modules means you are doing a rewrite, not swapping an adapter. - Key dependencies are Express-only. File uploads built on the Express-specific interceptors are one example. Session stores, SSO or SAML integrations, and internal shared libraries written against Express types are others. Each one needs a Fastify-native replacement, and someone has to maintain it.
- The deployment wrapper assumes Express. Some serverless and edge setups wrap an Express app instance directly. Changing the adapter there also changes how cold starts, request translation and error handling work in production, which adds risk to a change that otherwise looks like a small code change.
- You have no baseline. Without load tests and latency percentiles from the current service, you cannot show the migration improved anything. You also cannot tell a regression from noise.
- Nobody on the team knows Fastify's lifecycle. Fastify's hooks, encapsulation rules and serialization behave differently from Express. Teams without that knowledge tend to debug plugin scoping during an incident instead of in review.
- The service is low-traffic, internal or near end-of-life. The gain is small, and every engineer who touches the service later has to learn a second adapter.
How OneEnv can help
Disclosure: OneEnv is the product behind this blog.
OneEnv (oneenv.io) is a workspace-based governance platform for the things services share — environment variables, database structure, API routes and validation rules. A change to a shared value is staged on a branch, reviewed once, and then every affected service explicitly approves or rejects it before it goes live, so you can see who a change touches before it ships instead of finding out in production.
Applied to nestjs fastify vs express, this is where it helps:
Saves time
- Every service that inherits a shared value is listed in one place, so nobody searches repos and chats to find out who is affected.
- One review per branch replaces coordinating each team separately; each service still keeps its own approve/reject.
- Changing a shared variable is one edit and one review instead of editing every service's
.envby hand.
Saves cost
- Fewer production incidents and rollbacks caused by a shared value, route or column changing under a consumer unannounced.
- Less duplicated configuration to maintain: one shared definition inherited by many services.
- A wrong or stale value is caught at review time by the services it affects, not by a failed deploy.
- OneEnv has a free plan (1 workspace, unlimited services and members, full governance), so trying it costs nothing.
These are qualitative benefits, not measured results — how much you save depends on how many services share the value.
Want to try it? Start at oneenv.io.