6 min read
Node.js developer learning NestJS: what carries over, what's new, 30-day plan
Practical guide for Node.js developers transitioning to NestJS, covering transferable skills, new concepts, pitfalls, a 30‑day roadmap, and FAQs.
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
- Keep functions pure when possible – Service methods in Nest should still avoid side effects unless they interact with I/O.
- 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. - Use async/await for DB calls – Whether you use
mongoose,typeorm, or rawpg, the async patterns stay identical. - Write unit tests that mock external calls – Nest’s testing utilities (
Test.createTestingModule) let you inject mocks the same way you would withsinonorjest.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'));
NestJS
// src/app.controller.ts
import { Controller, Get } from '@nestjs/common';
@Controller()
export class AppController {
@Get('hello')
getHello() {
return { message: 'Hello from NestJS' };
}
}
// 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();
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
- Forgetting to add providers to a module – Declaring a service class is not enough; you must list it in the
providersarray of the module that uses it, otherwise DI will throw “Nest can’t resolve dependencies”. - 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.
- Over‑using the global scope – Declaring everything as
@Global()makes the module graph opaque and defeats the purpose of explicit imports. Keep modules granular. - 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
OnModuleInitor async providers (useFactoryreturning a promise). - Assuming Express middleware works unchanged – While you can still use Express middleware, you must wrap it with
NestMiddlewareor register it viaapp.use()inmain.ts. Directly passingreq, res, nextto a Nest controller method will not work. - 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. - Neglecting validation pipes – Nest’s
ValidationPipeworks 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
- Install the Nest CLI:
npm i -g @nestjs/cliand generate a starter project withnest new demo. - Explore the generated module tree (
AppModule,AppController,AppService). Identify where providers, controllers, and imports live. - Rewrite a simple Express route (e.g.,
/ping) as a Nest controller method. Verify it works withnpm run start:dev. - Mini‑project: Build a “Todo API” with in‑memory storage. Create a
TodoModule,TodoController, andTodoService. Use DTOs (CreateTodoDto) but skip validation for now.
Week 2 – Dependency injection & configuration
- Create a reusable service (e.g.,
UuidServicethat wrapsuuid/v4). Register it in a dedicated module and inject it into the Todo controller. - Add environment configuration: install
@nestjs/config, create a.envfile, and load aPORTvariable inmain.ts. - Introduce a database: add
@nestjs/typeormand a SQLite (or Postgres) connection. Define aTodoEntityand switch the in‑memory store to a real repository. - Mini‑project: Extend the Todo API to persist items. Implement
GET /todos,POST /todos, andDELETE /todos/:id.
Week 3 – Validation, pipes, guards, and testing
- Add class‑validator: decorate
CreateTodoDtowith@IsString(),@Length(). ApplyValidationPipeglobally inmain.ts. - Write a guard that checks for a custom header
x-api-key. Return403if missing. Apply it to thePOST /todosroute. - Create an interceptor that logs execution time of each request. Use
Loggerservice inside. - Testing: generate a unit test for
TodoServiceusingTest.createTestingModule. Mock the repository withjest.fn(). Runnpm run test.
Week 4 – Advanced patterns and deployment
- Implement a custom decorator (e.g.,
@CurrentUser()) that extracts a user object from the request (simulated). Use it in a newUserController. - Set up Swagger: install
@nestjs/swagger, addDocumentBuilderinmain.ts, and verify API docs at/api. - Dockerize the app: write a
Dockerfilethat uses a multi‑stage build (node:18-alpine→npm run build). Test container locally. - Mini‑project: Add a simple authentication flow (JWT). Create
AuthModule,AuthService, and aPOST /auth/loginendpoint 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
#nodejs #nestjs #learning #roadmap