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

  1. Single‑threaded event loop – No change in how Node processes I/O.
  2. Stateless request handling – Controllers (Express) vs. Controllers (Nest) still receive a fresh request each time.
  3. 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

  1. Forgetting to add @Module metadata – Controllers won’t be discovered unless they’re listed in the controllers array of a module.
  2. Mixing @Res() with automatic response handling – If you inject the raw Response and forget to return or res.send(), Nest thinks the request is still open and will timeout.
  3. Over‑using global pipes – Applying ValidationPipe globally can break legacy routes that expect plain objects; scope it to DTO‑based controllers first.
  4. 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() after NestFactory.create().
  5. Circular dependencies in providers – Because Nest resolves dependencies at startup, two services that inject each other will throw a Circular dependency error. Use forwardRef(() => OtherService) or refactor the design.
  6. Skipping the tsconfig.json tweaks – Nest’s default tsconfig.build.json sets "module": "commonjs" and "target": "es2017"; mismatched settings can cause runtime errors when compiling.

Your 30‑day plan

Week 1 – Foundations

  1. Install the CLI: npm i -g @nestjs/cli and generate a starter project: nest new my-nest-app.
  2. Run the generated app: npm run start:dev and explore the generated AppController and AppService.
  3. Add a simple GET route mirroring your most used Express endpoint, using a controller and a DTO.
  4. 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

  1. Create a UsersModule with UsersController and UsersService. Inject the service into the controller.
  2. Introduce a custom provider (e.g., a logger) and register it with useClass or useFactory.
  3. Port an existing Express middleware (e.g., helmet or a custom logger) to Nest using app.use() in main.ts.
  4. Project: Extend the Todo API to a separate TodosModule, add a TodosService that persists to a JSON file, and protect routes with a simple auth middleware that reads a header.

Week 3 – Validation, Pipes, and Exception Filters

  1. Install class-validator and class-transformer. Create a DTO for the Todo create payload and apply @IsString(), @Length(), etc.
  2. Add a global ValidationPipe in main.ts and observe automatic 400 responses.
  3. Write a custom exception filter (@Catch(HttpException)) that logs errors and formats the JSON response.
  4. Project: Refactor the Todo POST endpoint to use the DTO, add validation, and test error handling with malformed payloads.

Week 4 – Testing, Documentation, and Production Prep

  1. Write unit tests for a service using Jest (npm run test). Mock dependencies with jest.mock() or Nest’s TestingModule.
  2. Write e2e tests with @nestjs/testing and supertest for the Todo GET/POST flow.
  3. Add OpenAPI (Swagger) support: npm i @nestjs/swagger swagger-ui-express and configure DocumentBuilder in main.ts. Verify the generated docs.
  4. 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

Originally published at switchbyskill.com.