# NestJS over plain Express

> Express leaves the structural decisions to you, and every repository answers them differently. Two years in, the container is the part of NestJS I would keep - and Node 22 just went LTS.

- Author: Deyan Peev (https://deyanpeev.com)
- Published: 2024-11-19
- Tags: NestJS, Express, TypeScript, Node.js, Architecture, Testing
- URL: https://deyanpeev.com/posts/nestjs-over-plain-express

I've shipped both. The internal migration tool I worked on at VMware was
Express and Sequelize, and it was fine. The accounts and billing service I
have spent the last year and a half on is NestJS, and that is also fine, but
for a different reason. On a team, with several people adding endpoints to the
same repository over months, the framework has already settled the boring
arguments, and to me that's worth more than the lines of code it costs.

I am not saying Express is bad. It's a small, stable router with a
middleware signature that has outlived almost everything built on top of it.
But it declines to answer a set of questions that every real service has to
answer, and I would rather have them answered once, in a framework, than
again in every repository.

# The same endpoint, twice

Take a POST that creates an invoice. Validate the body, write it, return the
row. In Express, with a schema library:

```javascript
const express = require('express')
const { z } = require('zod')

const app = express()
app.use(express.json())

const createInvoice = z.object({
  accountId: z.string().min(1),
  amountCents: z.number().int().positive(),
  currency: z.string().length(3),
})

app.post('/invoices', async (req, res, next) => {
  try {
    const body = createInvoice.parse(req.body)
    const invoice = await invoices.create(body)
    res.status(201).json(invoice)
  } catch (error) {
    next(error)
  }
})
```

Nothing is wrong with that. But look at what it doesn't say. Where does
`invoices` come from? A module-level singleton imported at the top, so that
requiring this file connects to a database? How does the error handler know
that a Zod failure is a 400 and a duplicate key is a 409? Is `express.json()`
applied here or in another file, and is the body size limited? If I want to
test the route's behaviour without a live Mongo, what do I replace, and how?

Every one of those has about four good answers, and a repository with six
contributors will contain three of them. In Express codebases I've spent
more time reconciling the four conventions that grew in parallel than writing
routes.

The Nest version splits into more files, and that is intended. Each file is
one of those questions, answered in the same place in every module.

```typescript
// invoices/dto/create-invoice.dto.ts
import { IsInt, IsPositive, IsString, Length } from 'class-validator'

export class CreateInvoiceDto {
  @IsString()
  readonly accountId: string

  @IsInt()
  @IsPositive()
  readonly amountCents: number

  @IsString()
  @Length(3, 3)
  readonly currency: string
}
```

```typescript
// invoices/invoices.controller.ts
import { Body, Controller, Post } from '@nestjs/common'
import { CreateInvoiceDto } from './dto/create-invoice.dto'
import { InvoicesService } from './invoices.service'

@Controller('invoices')
export class InvoicesController {
  constructor(private readonly invoices: InvoicesService) {}

  @Post()
  create(@Body() dto: CreateInvoiceDto) {
    return this.invoices.create(dto)
  }
}
```

```typescript
// invoices/invoices.module.ts
import { Module } from '@nestjs/common'
import { InvoicesController } from './invoices.controller'
import { InvoicesService } from './invoices.service'

@Module({
  imports: [BillingModule],
  controllers: [InvoicesController],
  providers: [InvoicesService],
  exports: [InvoicesService],
})
export class InvoicesModule {}
```

The controller returns a value instead of writing to `res`. A `POST` handler
that returns normally becomes a 201, anything else becomes a 200, and a handler
that throws becomes whatever its exception maps to. There's no `try`/`catch`
and no `next(error)` in the route, because the framework awaits the handler
and owns that conversion.

# The container is the product

If I had to keep one thing from NestJS and throw the rest away, it would be
the dependency injection container, because
`constructor(private readonly invoices: InvoicesService)` is a declaration the
framework can read.

Nest builds a graph from those constructor types at startup. If
`InvoicesService` needs a `BillingClient` that no imported module exports,
the application fails to boot and tells you the path it could not resolve.
That happens before any traffic, and not on the first request that happens to
hit that branch. The `imports` and `exports` arrays in a module are a real
boundary too. A provider isn't reachable from another module unless that
module exports it and the consumer imports it. In Express,
`require('../billing/client')` reaches anything from anywhere, forever.

The other half is that there are no module-level singletons any more. The
service gets constructed with its dependencies handed in, and the next section
only works because of that.

# Testing is where I stopped arguing

This is what changed my mind, and assertion syntax has nothing to do with it.

```typescript
const moduleRef = await Test.createTestingModule({
  controllers: [InvoicesController],
  providers: [InvoicesService],
})
  .overrideProvider(InvoicesService)
  .useValue({ create: jest.fn().mockResolvedValue(invoice) })
  .compile()

const controller = moduleRef.get(InvoicesController)
```

That is the real controller, wired by the real container, with one node of the
graph swapped. I didn't have to start an HTTP server, and I didn't have to
reach into a module registry to monkey-patch an import.

The Express equivalent, in the codebases I have worked in, is usually one of
these. You export a factory from every file and thread dependencies through by
hand, which works and is rarely done consistently. Or you mock the module
loader, and that's fine until two tests in the same process disagree about
what is mocked. Or you give up and drive the whole application through
Supertest against a real database. That last one is a useful test, but as a
substitute for a fast one it's slow and flaky.

The good Express answer (factories, explicit dependencies, no import-time side
effects) is what the Nest container does. You can have this in Express, but
you have to want it, and then enforce it in review, and explain it again to
every new joiner.

# Validation and errors belong to the framework, once

Two global registrations replace a per-route habit:

```typescript
const app = await NestFactory.create(AppModule)

app.useGlobalPipes(
  new ValidationPipe({
    whitelist: true,
    forbidNonWhitelisted: true,
    transform: true,
  }),
)

await app.listen(process.env.PORT ?? 3000)
```

`whitelist` strips properties with no decorator on the DTO;
`forbidNonWhitelisted` rejects the request instead. That pair is why I like
this more than a validation middleware I have to remember to apply. The default
for an undeclared field is "refuse", not "pass it to the database".

Errors get the same treatment. `throw new ConflictException('invoice exists')`
in a service becomes a 409 with a JSON body, from anywhere in the call stack,
without the route knowing. Domain errors that aren't HTTP errors get one
exception filter that maps them, in one file, for every controller.

One thing here is often stated as an Express deficiency, and in late 2024 it
still is one. Express 4 does not catch a rejected promise from an `async`
handler. Forget the `try`/`catch` and the request hangs until the client gives
up, with an unhandled rejection in the logs and no response.
`express-async-errors` and every `asyncHandler(fn)` wrapper in the wild exist
to paper over that. Nest awaits the handler, so there is nothing left for a
wrapper to do.

# What it costs

The decorators are the visible tax, and they're less magic than they look.
`@Body()` and friends are metadata that a `tsc` build with
`emitDecoratorMetadata` writes out and `reflect-metadata` reads back. That is
also the constraint. The container resolves `InvoicesService` from emitted
type metadata, so the compile step isn't optional, TypeScript is effectively
mandatory, and an interface can't be an injection token because interfaces do
not survive to runtime. You use a class or a string/symbol token instead.

The dependency tree is bigger and the framework has more concepts to learn
than Express has. Startup does real work too, building the module graph costs
milliseconds you can measure. That matters if your process starts cold a lot,
and much less for a service that boots once and serves for a fortnight.

So for two routes and a webhook I'd still write Express, or nothing at
all. It's the same instinct as with [.NET 6's minimal
APIs](https://deyanpeev.com/posts/dotnet-six-small-services). When a service is small enough to
read in one file, the structure that helps a large team is just ceremony. The
crossover for me is roughly when the service gets a second contributor and
a third resource.

# Node 22 went LTS three weeks ago

Node 22 moved to Active LTS on 29 October under the codename
[Jod](https://nodejs.org/en/blog/release/v22.11.0), and that pushed it
from "interesting" to "the version we target". It also brought several things
we have taken up in the last few weeks. They aren't NestJS features, but each
one replaced a dependency.

`--env-file` reads a `.env` without `dotenv`, and the flag can be repeated,
with the later file winning:

```bash
node --env-file=.env --env-file=.env.local scripts/reconcile.mjs
```

For the service itself I still use Nest's `ConfigModule`, because I want
config validated and injected, not read off `process.env` in whichever file
needs it. For the one-off scripts around the service (backfills,
reconciliation, whatever you run once against staging) the flag is enough and
the dependency is gone.

`node --run` runs a `package.json` script without going through npm. That
takes a noticeable slice off short CI steps, because it doesn't start a
package manager to start a process:

```bash
node --run build
node --run test
```

It is still experimental in 22, and by design it doesn't do everything npm
does (it ignores pre and post scripts, for instance), so read the
[release notes](https://nodejs.org/en/blog/announcements/v22-release-announce)
before swapping it into a pipeline you care about.

`node --watch` is stable now, which retired nodemon from the plain-Node
workers. Nest's own `nest start --watch` still drives the API, since that
needs a compile step in front of the restart.

Two changes we didn't opt into but did have to notice. Maglev, V8's
mid-tier compiler, is on by default on supported architectures, and the
benefit lands on short-lived processes, so on our CLI scripts and CI steps and
not on the long-running API. And the default stream `highWaterMark` went from
16 KiB to 64 KiB, which is a throughput win and a memory cost. If you have a
lot of concurrent streams, that shows up on a memory graph and not in a
changelog. It's the same thing I kept running into with [.NET in
containers](https://deyanpeev.com/posts/dotnet-five-linux-containers-memory), a default that is
better on average but not automatically better for your load.
`stream.setDefaultHighWaterMark` puts it back.

The one I'm still waiting for is `require()` of an ES module, which is behind
`--experimental-require-module` in 22. A Nest build is CommonJS, an increasing
number of small libraries ship ESM only, and the gap between those two facts
is a `ERR_REQUIRE_ESM` and an afternoon.

# Express 5 exists, and it is not what `npm install` gives you

Express 5.0 was published in September and
[announced on 15 October](https://expressjs.com/en/blog/2024-10-15-v5-release),
on the `next` dist-tag. `npm install express` today still installs 4.x. So the
Express in production, including the Express under NestJS 10, is Express 4.

Express 5 does fix real things. It catches rejected promises from middleware
and routes them to `next(err)`, which removes the wrapper I complained about
above. It drops the deprecated `res.send(status, body)` signatures, changes
route matching to `path-to-regexp` 9 (no more inline regex in a path, and
wildcards have to be named), and stops initialising `req.body` to `{}`
unconditionally.

So the headline fix is something NestJS already gave me two years ago, and the
rest is a migration with a real edge-case list attached. I'll take it when
Nest takes it, and I expect to spend the time on wildcard routes and not on
anything conceptual.

# What I would choose today

For a service a team owns, with more than a handful of resources and a
lifetime measured in years, I'd pick NestJS on Node 22, with the compile step
and the container and the global validation pipe. It is Express underneath, so
on throughput it's Express minus a small constant. The reason to choose it is
that the arguments get settled in the framework and not in review.

For a script, a webhook, or something whose job fits on one screen it's
Express, or `node:http`, and no build step.

What I would avoid is the middle. That's Nest's structure adopted as
folder-naming: you get the concepts and the build step, and the services still
reach into module-level singletons and the routes still catch their own
errors.
