DEV Community

Cover image for Looking for an Express alternative? NestJS can now run without Express
Kamil Mysliwiec for NestJS

Posted on Edited on

Looking for an Express alternative? NestJS can now run without Express

Ask anyone, human or AI, what to use instead of Express, and you'll hear two names: Fastify, because it's faster, and Hono, because it's small and runs everywhere. Nest usually isn't on that list, and there's a fair reason: Nest runs on Express by default, so "use Nest instead of Express" sounds like "use Express, with more on top".

Since Nest 12.3, it doesn't have to. The NodeAdapter runs Nest directly on Node's node:http module, with no Express underneath. It handles about 50% more requests per second than Express, within a few percent of plain Fastify, and most Express middleware still works with it.

It's opt-in for now. A new project still runs on Express until you install the adapter and pass it in main.ts, a small change shown below. In Nest 13, the Node adapter becomes the default.

This post is for anyone who's leaving Express: what the Node adapter is, the numbers, what stays compatible and what doesn't, the same endpoint written both ways, errors, tests and production settings, and how to move an Express app over without stopping feature work.

Why people leave Express

Express is fine. It's also the framework most people are trying to get away from, usually for one of four reasons:

  • Speed. Express is the slowest of the common Node.js options, by a wide margin on routes that do little work.
  • Everything is your decision. Validation, authentication, configuration, folder structure, how services share a database connection, how tests replace them: Express gives you a router and middleware, and the rest is a pile of libraries someone on the team picked.
  • Async errors. Before Express 5, a rejected promise in a handler didn't reach the error handler. Express 5 fixed that, but a lot of code in the wild still has the wrappers.
  • The codebase stops having a shape. A small Express app is pleasant. At thirty routes, five developers and a queue, every app looks different, and every new developer learns that one.

Fastify answers the first point and, with its plugin system, part of the second. Hono answers the first and adds edge runtimes. Nest answers the last three, and now the first one too.

Nest on node:http

nest new still sets up a project on Express, and NestFactory.create() still picks Express when you don't pass an adapter. To switch, install the Node adapter:

npm i @nestjs/platform-node
Enter fullscreen mode Exit fullscreen mode

Then pass it to NestFactory.create() in main.ts:

import { NestFactory } from '@nestjs/core';
import { NestNodeApplication, NodeAdapter } from '@nestjs/platform-node';
import { AppModule } from './app.module.js';

const app = await NestFactory.create<NestNodeApplication>(
  AppModule,
  new NodeAdapter(),
);
await app.listen(process.env.PORT ?? 3000);
Enter fullscreen mode Exit fullscreen mode

That's the whole switch. Controllers, providers, guards, pipes, interceptors and exception filters don't know which adapter they run on, so nothing else in the app changes. NestNodeApplication gives you the adapter's own methods on app: useBodyParser(), useStaticAssets(), setViewEngine() and inject(), which sends a fake request without a listening server, as Fastify's inject() does.

In end-to-end tests, pass the adapter there too, so the tests run on what production runs:

app = moduleRef.createNestApplication<NestNodeApplication>(new NodeAdapter());
Enter fullscreen mode Exit fullscreen mode

Without it, the testing module creates an Express application, so the tests exercise a different server than the one you ship.

The numbers

Requests per second on GET /, each server answering Hello world!, with wrk -t4 -c100 for 8 seconds after a 3-second warm-up, on Node.js 24.20, median of 3 rounds:

Server GET /
Fastify 57.1k
Nest on Node 55.6k
Hono on Node 53.1k
Nest on Fastify 52.6k
Express 37.0k
Nest on Express 37.0k

And a separate round on an M1 Pro, with a route parameter and a JSON body:

Server GET /users/:id POST /echo (JSON)
Express 35.6k 30.1k
Fastify 54.0k 43.5k
Nest on Express 34.5k 28.2k
Nest on Fastify 48.4k 40.2k
Nest on Node 51.0k 42.4k

So Nest on Node is about 3-6% behind plain Fastify, slightly ahead of Hono on Node, and 41-50% ahead of plain Express. It's also faster than Nest on Fastify, which surprises people: the Node adapter has its own body parsers and route matching, so no other framework sits between Nest and node:http.

The benchmark and the servers for every framework, Koa, Elysia and AdonisJS included, are in nestjs/nest#18063. Run it on your own machine: other machines give other gaps.

One caveat I'd put on any framework benchmark: these routes do almost nothing. A route that queries Postgres or calls another service spends most of its time waiting for them, so for most APIs, a few percent either way won't decide anything. What these numbers settle is that, with the Node adapter, you don't pay Express's price for using Nest.

What stays Express-compatible

The Node adapter's request and response objects extend Node's IncomingMessage and ServerResponse with the Express-style helpers that middleware and exception filters usually rely on: req.get(), req.ip, req.hostname, res.status(), res.json(), res.set(), res.cookie(), res.redirect(), res.sendFile(), res.locals and the rest of the common set. Middleware runs in an Express-style stack, with the same (req, res, next) signature.

So the middleware you already use keeps working: helmet, compression, cookie-parser, express-session, express-rate-limit, morgan, and passport with @nestjs/passport. File uploads use the same Multer-based interceptors, imported from @nestjs/platform-node.

It isn't Express, though, and it differs on purpose in a few places:

  • Routes are matched by specificity, as in Fastify, not in the order they were registered, and paths are case-sensitive.
  • A string returned from a handler is sent as text/plain, not text/html.
  • No automatic ETag, so no 304 for a conditional request, except from res.sendFile() and static assets.
  • A JSON body with a __proto__ or constructor.prototype key is rejected with a 400.
  • Route parameters are capped at 100 characters, as in Fastify. maxParamLength raises it.
  • Express settings become adapter options, such as trustProxy for trust proxy.

And some Express APIs aren't there: res.render() (use the @Render() decorator), res.download(), res.format(), req.accepts(), req.subdomains and a few others, plus mounting a whole Express application with app.use(). If your app depends on one of those, or on a package that only supports Express, stay on the Express adapter for now. The HTTP adapters chapter has the complete list.

What Express never gave you

Speed is why you'd look. It's not why I'd want you to stay. Here's an endpoint for placing an order, the way it usually looks in Express:

// orders/orders.router.ts
import { Router } from 'express';
import { z } from 'zod';
import { authenticate } from '../auth/authenticate.js';
import { canCreateOrder } from '../auth/permissions.js';
import { ordersService } from './orders.service.js';

const createOrderSchema = z.object({
  items: z
    .array(z.object({ productId: z.uuid(), quantity: z.int().min(1) }))
    .min(1),
});

export const ordersRouter = Router();
ordersRouter.use(authenticate); // forget this line, and the router is public

ordersRouter.post('/', async (req, res) => {
  const parsed = createOrderSchema.safeParse(req.body);
  if (!parsed.success) {
    return res.status(400).json({ errors: parsed.error.issues });
  }
  if (!canCreateOrder(req.user)) {
    return res.status(403).json({ message: 'Forbidden' });
  }
  res.status(201).json(await ordersService.place(req.user, parsed.data));
});
Enter fullscreen mode Exit fullscreen mode

It works, and every line of it is a decision your team made and has to make again on the next router: where authenticate goes, how a validation error is shaped, which status a denied request gets, and where ordersService comes from (here, a module-level singleton that tests have to mock by patching the import). And TypeScript only knows about req.user once someone adds a declare global block for it, in every project.

The same endpoint in Nest:

import { Body, Controller, Post } from '@nestjs/common';
import { CurrentUser } from '@nestjs/authentication';
import { Can } from '@nestjs/authorization';
import { z } from 'zod';
import type { User } from '../users/user.js';
import { OrderPolicy } from './order.policy.js';
import { OrdersService } from './orders.service.js';

const createOrderSchema = z.object({
  items: z
    .array(z.object({ productId: z.uuid(), quantity: z.int().min(1) }))
    .min(1),
});

@Controller('orders')
export class OrdersController {
  constructor(private readonly ordersService: OrdersService) {}

  @Post()
  @Can(OrderPolicy, 'create')
  create(
    @CurrentUser() user: User,
    @Body({ schema: createOrderSchema }) dto: z.infer<typeof createOrderSchema>,
  ) {
    return this.ordersService.place(user, dto);
  }
}
Enter fullscreen mode Exit fullscreen mode

Four things happen there that you'd wire up by hand in Express:

  • The route is closed by default. With @nestjs/authentication, every route requires a signed-in user unless it's marked @Public(). You can't forget to add the auth middleware to a new router, because there's nothing to add.
  • Permission checks are declared, and also closed by default. @nestjs/authorization denies a route that declares no check, so a new route without one fails closed instead of open.
  • The body is validated before the handler runs. Zod, Valibot, ArkType or any other Standard Schema library, or class-validator if you prefer classes. An invalid body is a 400 that lists what's wrong.
  • OrdersService is injected. Nest creates it once and passes it in, with its own dependencies, so a test replaces the database or the mailer without patching imports.

And the parts around that endpoint come from first-party packages, built and released by the same team, instead of from whoever maintains the library you found:

You need Nest package
Sign-in, sessions, tokens, two-factor, API keys @nestjs/authentication
Permissions @nestjs/authorization
Configuration, validated at startup @nestjs/config
A database @nestjs/drizzle, @nestjs/typeorm, @nestjs/mongoose
Queues and scheduled jobs @nestjs/bullmq, @nestjs/schedule
Email, file storage, translations @nestjs/mail, @nestjs/storage, @nestjs/i18n
Rate limiting, caching @nestjs/throttler, @nestjs/cache-manager
Retries, timeouts, circuit breakers @nestjs/resilience
Webhooks, idempotency keys, the outbox pattern @nestjs/webhooks, @nestjs/idempotency, @nestjs/outbox
OpenAPI @nestjs/swagger
WebSockets, microservices, GraphQL @nestjs/websockets, @nestjs/microservices, @nestjs/graphql
MCP servers, language models @nestjs/mcp, @nestjs/ai

None of them is required. A Nest app starts with the core and adds what it uses.

Express, translated

If you know Express, most of Nest is a different place for code you already write:

Express Nest
express.Router() for a resource a controller in a module (nest g module orders, nest g controller orders)
router.get('/:id', handler) @Get(':id') on a method
req.params, req.query, req.body @Param(), @Query(), @Body()
validation middleware, safeParse() by hand a schema on the parameter, checked before the handler runs
auth middleware that sets req.user @nestjs/authentication, and @CurrentUser() in the handler
requireRole('admin') a policy, with @Can() on the route
router.param('id', load) a pipe: @Param('id', OrderByIdPipe)
res.status(201).json(x) return x (a POST answers 201 by default; @HttpCode() changes it)
res.redirect(301, url) @Redirect(url, 301)
next(err) and the error middleware throw, and an exception filter
app.use(helmet()) app.use(helmet()), unchanged
app.use(cors(options)) app.enableCors(options)
express.static(dir) app.useStaticAssets(dir)
multer().single('file') FileInterceptor('file') and @UploadedFile()
a module that exports a database pool or a mailer a provider, injected where it's used

Errors: throw, and handle them in one place

In Express, a route sends its own error responses, and everything else goes to next(err) and an error-handling middleware at the end of the stack. Every route decides the shape of its errors, and they drift.

In Nest, you throw. HttpException and its subclasses (NotFoundException, ConflictException, ForbiddenException and the rest) become a JSON response with their status, from anywhere: a controller, a service three calls deep, a guard. Any other error becomes a 500, and its stack goes to the log, not to the client.

When your API has its own error shape, one exception filter owns it, for every error, including the ones Nest raises itself, such as a malformed JSON body or a route that doesn't exist:

// common/api-exception.filter.ts
import {
  Catch,
  HttpException,
  type ArgumentsHost,
  type ExceptionFilter,
} from '@nestjs/common';

@Catch()
export class ApiExceptionFilter implements ExceptionFilter {
  catch(exception: unknown, host: ArgumentsHost) {
    const response = host.switchToHttp().getResponse();
    const status =
      exception instanceof HttpException ? exception.getStatus() : 500;
    const message =
      exception instanceof HttpException
        ? exception.message
        : 'Something went wrong';
    response.status(status).json({ error: { status, message } });
  }
}
Enter fullscreen mode Exit fullscreen mode

Register it once in main.ts, with app.useGlobalFilters(new ApiExceptionFilter()), and no route can send an error in another shape.

Testing without a server

An Express test usually starts the app with Supertest and mocks modules by path. In Nest, a testing module builds the app from its modules, overrideProvider() swaps any provider for a fake, and on the Node adapter app.inject() sends a request without opening a port:

// test/orders.e2e-spec.ts
import { Test } from '@nestjs/testing';
import { NestNodeApplication, NodeAdapter } from '@nestjs/platform-node';
import { AppModule } from '../src/app.module.js';
import { OrdersService } from '../src/orders/orders.service.js';

const moduleRef = await Test.createTestingModule({ imports: [AppModule] })
  .overrideProvider(OrdersService)
  .useValue({ place: async () => ({ id: 'order-1' }) })
  .compile();
const app = moduleRef.createNestApplication<NestNodeApplication>(
  new NodeAdapter(),
);
await app.init();

const response = await app.inject({
  method: 'POST',
  url: '/orders',
  payload: { items: [] },
});
// No session here, so the authentication guard answers 401 before the
// schema or the fake service runs. With one, the empty order is a 400.
Enter fullscreen mode Exit fullscreen mode

Unit tests are simpler still. A provider is a plain class, so new OrdersService(fakeRepository, fakeMailer) is the whole setup.

The Node adapter in production

The defaults match Express, so most apps need nothing. The settings worth knowing before you deploy:

  • Behind a load balancer, pass trustProxy to the adapter, such as new NodeAdapter({ trustProxy: 'loopback' }) or your proxies' subnet, so req.ip, req.protocol and req.hostname come from the X-Forwarded-* headers. Trust only the proxies in front of you.
  • Keep-alive: Node closes an idle connection after 5 seconds. Keep server.keepAliveTimeout longer than your load balancer's idle timeout (for example, 72 seconds), or the balancer can reuse a connection the server is closing and answer 502.
  • Body size: the JSON limit is 100kb, as in Express. app.useBodyParser('json', { limit: '10mb' }) raises it, and a bigger body gets a 413.
  • File uploads use the same Multer-based interceptors as on Express, imported from @nestjs/platform-node.
  • Static files and a single-page app: app.useStaticAssets() serves a folder, and @nestjs/serve-static (12.1.1 or later) serves an SPA with its fallback route, without the express package.
  • GraphQL works with the Apollo driver, @nestjs/apollo 14.1.1 or later.
  • Shutdown: call app.enableShutdownHooks(), so your shutdown hooks run on SIGTERM and connections drain on every deploy.

Moving an Express app over, one route at a time

You don't have to rewrite anything to start. Nest can run on your existing Express app, with both answering on the same port:

import { NestFactory } from '@nestjs/core';
import { ExpressAdapter } from '@nestjs/platform-express';
import { AppModule } from './app.module.js';
import { createLegacyApp } from './legacy/app.js';

const app = await NestFactory.create(
  AppModule,
  new ExpressAdapter(createLegacyApp()),
);
await app.listen(process.env.PORT ?? 3000);
Enter fullscreen mode Exit fullscreen mode

createLegacyApp() is your Express app, with its app.listen() call removed. Express's routes and middleware come first, and Nest's routes answer whatever Express doesn't. They see what the Express middleware put on the request, so a guard can check the req.user your existing auth middleware sets. New endpoints go into Nest, and an existing one moves when you next touch it: write it as a Nest route, delete it from the Express router, deploy. Nothing waits for a big switch.

Two requirements: the Express app has to be on Express 5 (npx @expressjs/codemod upgrade does most of it), and a catch-all 404 handler in the Express app has to go, or it answers Nest's routes too.

The Node adapter comes at the end. While the Express app is mounted, Nest has to run on the Express adapter, because the Node adapter can't mount an Express application. Once the last Express route has moved, switch main.ts to the NodeAdapter, and the app gets the speed-up with no other change.

What changes without an error

A wrong translation usually fails loudly. These don't, so check them, or pin them with tests before you move:

  • A POST handler answers 201, where res.json() answered 200. @HttpCode(200) keeps the old status for clients that check it.
  • Errors come out as { statusCode, message, error } until a global exception filter gives them your shape, the one above.
  • An Express 4 app gets a request with no body as req.body set to {}. In Nest, @Body() is undefined, so destructuring it throws.
  • A returned string is sent as text/plain on the Node adapter, where res.send() sent text/html.
  • Optional route parameters and wildcards have Express 5's syntax: search{/:term} and assets/*path. The old syntax stops the app at startup, so you'll notice.

Or all at once, with a coding agent

If the app is small enough to review in one change, moving it all at once works too, and it's a good job for a coding agent, as long as tests pin what the app does first. Give it the docs page and hold it to the tests:

Migrate this Express application to NestJS all at once, following
https://docs.nestjs.com/migrating/express.md.

1. Before changing anything, write black-box HTTP tests that cover every
   route: status codes, bodies and important headers, failures included.
   Run them against the Express app until they all pass.
2. Build the Nest application next to it, using the page's translation table.
3. Check every row of "Keep what would change without an error".
4. Run the same tests against the Nest application. Don't edit a test to
   make it pass. If behavior has to change, stop and tell me.
Enter fullscreen mode Exit fullscreen mode

The Migrating from Express page has both approaches step by step, including the full list of things that change without an error.

Getting started

npx @nestjs/cli new orders-api
cd orders-api
npm i @nestjs/platform-node
Enter fullscreen mode Exit fullscreen mode

nest new sets the project up on Express, so switch main.ts to the NodeAdapter as above. Then run npm run start:dev, and nest g module orders and nest g controller orders give you the first module and controller, with a test, to move your first router into.

The Node adapter's full reference, with the same benchmark, is in the docs: HTTP adapters. If your Express app relies on something the Node adapter doesn't do, tell me: that list is shorter every release, and it's useful to know what's on it.

Top comments (0)