DEV Community

Switch by Skill
Switch by Skill

Posted on Originally published at switchbyskill.com

Node.js developer learning NestJS: what carries over, what's new, 30-day plan

What carries over

Node.js / Express concept NestJS equivalent Why it still matters
JavaScript (or TypeScript) runtime Same V8 engine, same event loop All async patterns (async/await, streams, buffers) work unchanged.
Middleware pattern @NestMiddleware or APP_INTERCEPTOR The idea of a function that receives req, res, next stays, but Nest wraps it in a class and injects dependencies.
Routing basics Controllers with @Get(), @Post(), etc. HTTP verbs and path matching are still the core of request handling.
Dependency injection (manual) Built‑in DI container You already know you need to pass services around; Nest formalises it with decorators and a module graph.
Environment configuration process.env + @nestjs/config Accessing env vars is identical; the config module just adds validation and type safety.
Testing with Jest Same test runner, same assertions Nest ships with Jest out of the box, so your existing test setup can be reused.
Error handling via next(err) Throwing exceptions or using @Catch() filters The mechanism of bubbling an error up the stack is unchanged; Nest just provides typed exception classes.
Logging to stdout Logger service or console You can still console.log, but Nest’s Logger gives levels and context.
Package management npm / yarn / pnpm All same package.json scripts; Nest adds a CLI but does not replace your package manager.

Concrete habits that survive

  1. Keep functions pure when possible – Service methods in Nest should still avoid side effects unless they interact with I/O.
  2. Structure code by feature – In Express you might have a routes/ folder; in Nest you’ll create a module per feature, which mirrors that organization.
  3. Use async/await for DB calls – Whether you use mongoose, typeorm, or raw pg, the async patterns stay identical.
  4. Write unit tests that mock external calls – Nest’s testing utilities (Test.createTestingModule) let you inject mocks the same way you would with sinon or jest.mock.

What's new

NestJS introduces a declarative, class‑based architecture built on top of decorators. The same “hello world” endpoint looks different.

Plain Node.js (Express)

// app.js
const express = require('express');
const app = express();

app.get('/hello', (req, res) => {
  res.json({ message: 'Hello from Express' });
});

app.listen(3000, () => console.log('Server running on 3000'));
Enter fullscreen mode Exit fullscreen mode

NestJS

// src/app.controller.ts
import { Controller, Get } from '@nestjs/common';

@Controller()
export class AppController {
  @Get('hello')
  getHello() {
    return { message: 'Hello from NestJS' };
  }
}
Enter fullscreen mode Exit fullscreen mode
// src/main.ts
import { NestFactory } from '@nestjs/core';
import { AppModule } from './app.module';

async function bootstrap() {
  const app = await NestFactory.create(AppModule);
  await app.listen(3000);
}
bootstrap();
Enter fullscreen mode Exit fullscreen mode

What changed and why

Aspect Express NestJS Reason
File structure Single app.js main.ts, app.module.ts, app.controller.ts Modules enforce separation of concerns and make scaling easier.
Routing Function passed to app.get Decorator @Get() on a method inside a controller class Decorators let Nest collect metadata at compile time, enabling automatic validation, guards, and interceptors.
Dependency injection Manual require/new Constructor injection via @Injectable() services Centralized container removes boilerplate and improves testability.
Type safety Optional (plain JS) Default with TypeScript Enables compile‑time checks, better IDE support.
Lifecycle hooks You manage them yourself OnModuleInit, OnApplicationBootstrap, etc. Provides hooks for initialization, graceful shutdown, and more.
Middleware vs Interceptor Single middleware chain Global/inter‑module middleware and interceptors Interceptors can transform responses, handle caching, or implement AOP patterns.

Common pitfalls

  1. Forgetting to add providers to a module – Declaring a service class is not enough; you must list it in the providers array of the module that uses it, otherwise DI will throw “Nest can’t resolve dependencies”.
  2. Mixing plain functions with class methods – Nest expects controllers and services to be classes. Exporting a plain function and trying to inject it will fail.
  3. Over‑using the global scope – Declaring everything as @Global() makes the module graph opaque and defeats the purpose of explicit imports. Keep modules granular.
  4. Ignoring async initialization – If a service needs to connect to a DB in its constructor, the app may start before the connection is ready. Use OnModuleInit or async providers (useFactory returning a promise).
  5. Assuming Express middleware works unchanged – While you can still use Express middleware, you must wrap it with NestMiddleware or register it via app.use() in main.ts. Directly passing req, res, next to a Nest controller method will not work.
  6. Misunderstanding the request‑response lifecycle – Throwing an error inside a controller method automatically maps to an HTTP exception; you don’t need to call next(err). Using both patterns can cause duplicate responses.
  7. Neglecting validation pipes – Nest’s ValidationPipe works with class‑validator decorators. Skipping it means you lose automatic payload validation that Express developers often implement manually.

Your 30‑day plan

Week 1 – Foundations

  1. Install the Nest CLI: npm i -g @nestjs/cli and generate a starter project with nest new demo.
  2. Explore the generated module tree (AppModule, AppController, AppService). Identify where providers, controllers, and imports live.
  3. Rewrite a simple Express route (e.g., /ping) as a Nest controller method. Verify it works with npm run start:dev.
  4. Mini‑project: Build a “Todo API” with in‑memory storage. Create a TodoModule, TodoController, and TodoService. Use DTOs (CreateTodoDto) but skip validation for now.

Week 2 – Dependency injection & configuration

  1. Create a reusable service (e.g., UuidService that wraps uuid/v4). Register it in a dedicated module and inject it into the Todo controller.
  2. Add environment configuration: install @nestjs/config, create a .env file, and load a PORT variable in main.ts.
  3. Introduce a database: add @nestjs/typeorm and a SQLite (or Postgres) connection. Define a TodoEntity and switch the in‑memory store to a real repository.
  4. Mini‑project: Extend the Todo API to persist items. Implement GET /todos, POST /todos, and DELETE /todos/:id.

Week 3 – Validation, pipes, guards, and testing

  1. Add class‑validator: decorate CreateTodoDto with @IsString(), @Length(). Apply ValidationPipe globally in main.ts.
  2. Write a guard that checks for a custom header x-api-key. Return 403 if missing. Apply it to the POST /todos route.
  3. Create an interceptor that logs execution time of each request. Use Logger service inside.
  4. Testing: generate a unit test for TodoService using Test.createTestingModule. Mock the repository with jest.fn(). Run npm run test.

Week 4 – Advanced patterns and deployment

  1. Implement a custom decorator (e.g., @CurrentUser()) that extracts a user object from the request (simulated). Use it in a new UserController.
  2. Set up Swagger: install @nestjs/swagger, add DocumentBuilder in main.ts, and verify API docs at /api.
  3. Dockerize the app: write a Dockerfile that uses a multi‑stage build (node:18-alpine → npm run build). Test container locally.
  4. Mini‑project: Add a simple authentication flow (JWT). Create AuthModule, AuthService, and a POST /auth/login endpoint that returns a signed token. Protect the Todo routes with a JWT guard.

At the end of the month you should have a fully functional, tested, and containerized NestJS service that mirrors a typical Express project but leverages Nest’s architectural advantages.


FAQ

How much TypeScript do I need to know?

NestJS is built around TypeScript; you should be comfortable with interfaces, classes, and decorators. Basic type annotations are enough to get started, and you can deepen your knowledge as you go.

Can I still use plain Express middleware?

Yes. Register it in main.ts with app.use() or wrap it in a class that implements NestMiddleware. Just remember that Nest’s own middleware pipeline runs before/after Express middleware depending on registration order.

Do I have to rewrite all my existing Express routes?

Not immediately. You can mount an existing Express app inside a Nest module using NestFactory.createExpressApplication(). This lets you migrate incrementally.

Is the Nest CLI required?

No, but it scaffolds files, updates module metadata automatically, and speeds up common tasks like generating modules, controllers, and services. You can create the structure manually if you prefer.

Keep going

Originally published at switchbyskill.com.

Top comments (0)