Backend
NestJS
A progressive TypeScript Node.js framework with modules, decorators and dependency injection.
What it is
NestJS gives the structure Express lacks: modules, controllers, providers and a DI container. Its architecture resembles Angular and Spring.
Express or Fastify runs underneath, your choice. Out of the box it supports validation through pipes, guards for authorization, interceptors and microservice transports.
It is a good fit for large teams: uniform code structure and easy testing thanks to DI. The price is more boilerplate and a steeper learning curve.
Use it when
- A large backend where the team needs a single architecture.
- You know Angular or Spring and want familiar patterns.
- You need GraphQL, WebSocket, queues and microservices in one framework.
Avoid it when
- A tiny service or prototype: the ceremony outweighs the benefit.
- The team does not work with TypeScript and decorators.
Key concepts
- Module
- A unit of code organization grouping controllers and providers.
- Provider / DI
- A class injected into another class's constructor.
- Guard
- Checks whether a request may proceed (authorization).
- Pipe
- Transforms and validates input data.
- Interceptor
- Wraps a handler call: logging, cache, response mapping.
Example
Cheat sheet
| Command or code | What it does |
|---|---|
npm i -g @nestjs/cli | Installs the Nest CLI |
nest new app | Creates a project |
nest g resource users | Generates module, controller, service |
@Module({ controllers, providers }) | Module declaration |
@Controller('users') | Controller with a route prefix |
@Get(':id') find(@Param('id') id: string) | GET handler with a parameter |
@Post() create(@Body() dto: CreateDto) | POST handler with a body |
@Injectable() | Marks a service for DI |
@UseGuards(AuthGuard) | Protects a route |
app.useGlobalPipes(new ValidationPipe()) | Global DTO validation |
npm run test:e2e | Runs e2e tests |
How to learn it
- Learn TypeScript and Node.js basics with Express.
- Understand decorators and dependency injection on simple examples.
- Create a project with the Nest CLI and study the module structure.
- Write controllers, services and providers.
- Add validation with DTOs, ValidationPipe and class-validator.
- Connect a database with Prisma or TypeORM.
- Implement authentication with guards and JWT.
- Write the unit and e2e tests that Nest generates.
Interview questions
1. What is the DI container for?
It creates dependencies and passes them into classes, so code stays loosely coupled. In tests you can swap a service for a mock easily.
2. How does a guard differ from middleware?
A guard knows the execution context (which controller and method) and decides whether to let the request in. Middleware runs earlier and knows nothing about the handler.
3. Express or Fastify underneath?
Nest supports both through adapters. Fastify is faster, Express has wider middleware compatibility.
Interview questions from the bank
- A decorator based DI container (Nest, InversifyJS) with
emitDecoratorMetadatastopped starting after a linter autofix: a dependency is now imported withimport type. What exactly doestscwrite intodesign:paramtypesfor an interface and forimport type, and why does DI break?MiddleTypeScript - A payment service has expected failures (card declined, insufficient funds) and unexpected ones (network, a bug). How do you type them: exceptions or Result? How do they reach the HTTP response?SeniorTypeScript
- A team wants a base generic repository
Repository<T extends Entity>for all services. What is good about it in terms of types, what doestsccatch, and where do you stop generalizing?SeniorTypeScript - You need every log line and every SQL query to know the
requestIdandtenantIdwithout passing parameters through all functions. How do you do this withAsyncLocalStorage? What goes into the store, and what are the risks?MiddleNode.js - After an incident you find that a NestJS API returned a database driver error, with the password from the connection string, to the client in a 500 response. How could that happen if Nest's default filter hides details, and how do you make it impossible?MiddleNestJS
- In a NestJS project the JWT and role check was done in Express middleware, and a separate map of paths to roles had to be maintained. Why does Nest have guards for this, and what does a guard see that middleware does not?MiddleNestJS
- In NestJS,
UsersServicedepends onMailService, which is declared inprovidersofMailModule, andUsersModulehasimports: [MailModule]. The app does not start withNest can't resolve dependencies. Why, and how do you fix it?MiddleNestJS - In a NestJS integration test you need to replace
PaymentsClient, which calls the real payment API, with a fake while keeping the rest of the module real. How do you do it, and when would you useuseValueversususeClassoruseFactory?MiddleNestJS
Comparisons with this technology
Related technologies
- Node.jsA server-side JavaScript runtime built on the V8 engine with an event-driven, non-blocking I/O model.
- ExpressA minimalist web framework for Node.js with routing and a middleware chain.
- FastifyA fast Node.js framework with a plugin architecture and JSON Schema validation.
- TypeScriptA superset of JavaScript with static types that compiles to plain JS.
- AngularA full TypeScript framework for large web apps: routing, forms, DI and tooling out of the box.
- PrismaAn ORM for Node.js and TypeScript with a schema file, a generated type-safe client and migrations.
Logos belong to their owners and are used for identification only. Icons: Simple Icons (CC0), Devicon (MIT).