跳到正文
DEV Community· Kamil Mysliwiec·· 30 分鐘前AI 評分60

NestJS 12.3 可透過 NodeAdapter 不依賴 Express 運行

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

AI 導讀

NestJS 自 12.3 起可透過 NodeAdapter 直接運行於 Node.js 的 node:http 模組,無須使用 Express;Nest 13 會將 Node adapter 設為預設。

正文

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, when I'd still pick Fastify or Hono, 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

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);

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());

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 that Express leaves you to assemble, 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);
  }
}

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.

When I'd still pick Fastify or Hono

To be fair to both:

  • A service that stays a few routes, like a proxy or a webhook receiver: Fastify or Hono. There's nothing to organize, and either starts with less code.
  • The highest possible request rate on routes that do very little: Fastify, which is still a few percent ahead.
  • Cloudflare Workers or another edge runtime: Hono, which is built on Web Standards and runs there natively.
  • A Next.js frontend that should share route types with its API, with no code generation: Hono's RPC client infers them from the routes. With Nest, a shared package holds the schemas and types instead.
  • Fastify plugins you depend on: run Nest on Fastify with the FastifyAdapter, and keep them.

Nest is the better fit when the backend will grow: more modules, more people, a database, background jobs, and a codebase that has to look the same in two years. That's most backends I've seen, which is why I'd start there.

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);

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.

If the app is small enough to review in one change, moving it all at once also works, and it's a good job for a coding agent, as long as tests pin what the app does first. The Migrating from Express page has both approaches step by step, the list of things that change without an error, and a prompt to give an agent.

Getting started

npx @nestjs/cli new orders-api
cd orders-api
npm i @nestjs/platform-node

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 resource orders gives you a module, controller, service, DTOs and tests to compare with how you'd lay it out in Express.

The comparison with Fastify, Express and Hono, with the same benchmark, is in the docs: Nest vs Fastify, Express and Hono. 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.

來源:DEV Community · dev.to