What carries over
| Express habit | NestJS equivalent | Why it still matters |
|---|---|---|
Middleware stack – app.use(fn) | Middleware – app.use(fn) in the NestJS NestFactory or class‑based middleware (implements NestMiddleware) | Nest sits on top of the same underlying Express (or Fastify) server, so the request‑response pipeline is identical. |
Routing basics – app.get('/path', handler) | Controllers & decorators – @Controller('path') + @Get() | The HTTP verb mapping is the same; Nest just adds metadata via decorators. |
Request/Response objects – req.body, res.json() | Same objects – injected @Req() / @Res() give you the raw Express Request/Response | You can still use req.params, res.status(), etc., when you need low‑level control. |
Error handling – next(err) or error‑handling middleware | Exception filters – @Catch() classes or built‑in HttpException | The underlying mechanism still bubbles through Express, but Nest provides a structured way to centralise it. |
Environment configuration – process.env, dotenv | ConfigModule – ConfigModule.forRoot({ isGlobal: true }) | Both read from process.env; Nest just wraps it for DI. |
| Testing with supertest | Testing with @nestjs/testing – still uses supertest under the hood | The test runner stays the same; Nest adds a testing module to bootstrap the app. |
| Async/await and Promises | Unchanged | All route handlers can be async in both frameworks. |
Core concepts that survive unchanged
- Single‑threaded event loop – No change in how Node processes I/O.
- Stateless request handling – Controllers (Express) vs. Controllers (Nest) still receive a fresh request each time.
- Dependency on npm scripts –
npm run start,npm run build, etc., are identical.
What's new
NestJS introduces a declarative, class‑based architecture powered by TypeScript decorators, a built‑in IoC container, and optional integration with Fastify. Below is a side‑by‑side implementation of a tiny “hello world” endpoint that reads a query param and returns JSON.
Express (JavaScript)
const express = require('express'); const app = express(); app.get('/greet', (req, res) => { const name = req.query.name || 'World'; res.json({ message: `Hello, ${name}!` }); }); app.listen(3000, () => console.log('Server listening on 3000')); NestJS (TypeScript)
import { Module } from '@nestjs/common'; import { NestFactory } from '@nestjs/core'; import { Controller, Get, Query } from '@nestjs/common'; @Controller('greet') class GreetController { @Get() greet(@Query('name') name: string = 'World') { return { message: `Hello, ${name}!` }; } } @Module({ controllers: [GreetController], }) class AppModule {} async function bootstrap() { const app = await NestFactory.create(AppModule); await app.listen(3000); } bootstrap(); What changed and why
| Aspect | Express | NestJS | Reason |
|---|---|---|---|
| File structure | Usually a single app.js or a few route files | src/app.module.ts, src/greet.controller.ts (or inline) | Nest enforces a modular layout that scales. |
| Handler definition | Plain function (req, res) => {} | Method inside a class, decorated with @Get() | Decorators let Nest collect metadata for routing, validation, and more. |
| Dependency injection | Manual require() or import | Constructor injection via @Injectable() services | Centralised DI eliminates boilerplate and improves testability. |
| Type safety | Optional (JS) | Default (TS) | Nest encourages TypeScript, catching errors at compile time. |
| Lifecycle hooks | None built‑in | OnModuleInit, OnApplicationBootstrap, etc. | Hooks give you deterministic startup/shutdown points. |
| Built‑in validation | You add express-validator or similar | class-validator + @Body() pipes | Validation becomes declarative and reusable. |
Common pitfalls
- Forgetting to add
@Modulemetadata – Controllers won’t be discovered unless they’re listed in thecontrollersarray of a module. - Mixing
@Res()with automatic response handling – If you inject the rawResponseand forget toreturnorres.send(), Nest thinks the request is still open and will timeout. - Over‑using global pipes – Applying
ValidationPipeglobally can break legacy routes that expect plain objects; scope it to DTO‑based controllers first. - Assuming Nest replaces Express completely – By default Nest creates an Express instance; any Express middleware you used before still works, but you must register it via
app.use()afterNestFactory.create(). - Circular dependencies in providers – Because Nest resolves dependencies at startup, two services that inject each other will throw a
Circular dependencyerror. UseforwardRef(() => OtherService)or refactor the design. - Skipping the
tsconfig.jsontweaks – Nest’s defaulttsconfig.build.jsonsets"module": "commonjs"and"target": "es2017"; mismatched settings can cause runtime errors when compiling.
Your 30‑day plan
Week 1 – Foundations
- Install the CLI:
npm i -g @nestjs/cliand generate a starter project:nest new my-nest-app. - Run the generated app:
npm run start:devand explore the generatedAppControllerandAppService. - Add a simple GET route mirroring your most used Express endpoint, using a controller and a DTO.
- Project: Build a “Todo” API with in‑memory storage (
GET /todos,POST /todos). Keep it in a single module to get comfortable with decorators.
Week 2 – Modules, DI, and Middleware
- Create a
UsersModulewithUsersControllerandUsersService. Inject the service into the controller. - Introduce a custom provider (e.g., a logger) and register it with
useClassoruseFactory. - Port an existing Express middleware (e.g.,
helmetor a custom logger) to Nest usingapp.use()inmain.ts. - Project: Extend the Todo API to a separate
TodosModule, add aTodosServicethat persists to a JSON file, and protect routes with a simple auth middleware that reads a header.
Week 3 – Validation, Pipes, and Exception Filters
- Install
class-validatorandclass-transformer. Create a DTO for the Todocreatepayload and apply@IsString(),@Length(), etc. - Add a global
ValidationPipeinmain.tsand observe automatic 400 responses. - Write a custom exception filter (
@Catch(HttpException)) that logs errors and formats the JSON response. - Project: Refactor the Todo
POSTendpoint to use the DTO, add validation, and test error handling with malformed payloads.
Week 4 – Testing, Documentation, and Production Prep
- Write unit tests for a service using Jest (
npm run test). Mock dependencies withjest.mock()or Nest’sTestingModule. - Write e2e tests with
@nestjs/testingandsupertestfor the TodoGET/POSTflow. - Add OpenAPI (Swagger) support:
npm i @nestjs/swagger swagger-ui-expressand configureDocumentBuilderinmain.ts. Verify the generated docs. - Project: Containerise the Todo API with a Dockerfile, run it locally, and ensure the Swagger UI is reachable at
/api.
At the end of the month you should have a fully functional, tested, and documented NestJS service that mirrors a real Express codebase, plus a mental model of the framework’s architecture.
FAQ
How much of my existing Express middleware can I reuse?
Almost all of it. Since Nest creates an Express (or Fastify) instance under the hood, you can call app.use(yourMiddleware) in main.ts after the Nest app is created.
Do I have to rewrite every route as a class?
No. You can keep a plain Express router and mount it with app.use('/legacy', legacyRouter). However, for full DI and testing benefits, gradually migrate to controllers.
Is TypeScript mandatory for NestJS?
Nest works with plain JavaScript, but the framework’s decorators and metadata rely on TypeScript’s emit‑decorator feature. The official starter and most examples assume TypeScript, and you’ll get the most out of the IoC container with it.
Can I still use Fastify instead of Express?
Yes. Install @nestjs/platform-fastify and replace NestFactory.create(AppModule) with NestFactory.create(AppModule, new FastifyAdapter()). The rest of your code stays the same.
Keep going
- See what already transfers: take the free Express → NestJS readiness check
- The full Express → NestJS roadmap, topic by topic
- Related: Cloud developer learning Terraform: what carries over, what's new, 30-day plan
- Related: Node.js developer learning Python: what carries over, what's new, 30-day plan
Originally published at switchbyskill.com.