NestJS Framework Cheat Sheet
Quick reference guide for NestJS: Controllers, Services, Modules, DTO validation, Interceptors, and Dependency Injection.
Languages
nestjs
nodejs
backend
NestJS is a progressive Node.js framework for building efficient, reliable, and scalable server-side applications built with and fully supporting TypeScript.
Core Decorators Reference
NestJS heavily uses TypeScript decorators to define metadata and dependency injection roles.
Table
| Decorator | Target | Purpose / Meaning |
|---|---|---|
@Module({ imports, controllers, providers }) | Class | Group related controllers, services, and sub-modules |
@Controller('prefix') | Class | Define route path controller handler |
@Injectable() | Class | Mark service class for Dependency Injection container |
@Get(), @Post(), @Put(), @Delete() | Method | Map HTTP method and sub-route path |
@Param('id'), @Query('page'), @Body() | Parameter | Extract URL params, query string, or body payload |
@UsePipes(), @UseGuards(), @UseInterceptors() | Class/Method | Attach Validation Pipes, Auth Guards, or Response Interceptors |
Controller & Service Example
typescript
// users.service.ts
import { Injectable, NotFoundException } from '@nestjs/common';
export interface User { id: string; name: string; email: string; }
@Injectable()
export class UsersService {
private users: User[] = [];
findAll(): User[] {
return this.users;
}
findOne(id: string): User {
const user = this.users.find(u => u.id === id);
if (!user) throw new NotFoundException(`User with ID ${id} not found`);
return user;
}
}
// users.controller.ts
import { Controller, Get, Param, Post, Body } from '@nestjs/common';
import { UsersService, User } from './users.service';
import { CreateUserDto } from './dto/create-user.dto';
@Controller('users')
export class UsersController {
constructor(private readonly usersService: UsersService) {}
@Get()
getAllUsers(): User[] {
return this.usersService.findAll();
}
@Get(':id')
getUserById(@Param('id') id: string): User {
return this.usersService.findOne(id);
}
}
DTO Validation (`class-validator`)
typescript
// dto/create-user.dto.ts
import { IsString, IsEmail, MinLength } from 'class-validator';
export class CreateUserDto {
@IsString()
@MinLength(2)
name: string;
@IsEmail()
email: string;
}
// main.ts
import { ValidationPipe } from '@nestjs/common';
import { NestFactory } from '@nestjs/core';
import { AppModule } from './app.module';
async function bootstrap() {
const app = await NestFactory.create(AppModule);
// Enable global DTO validation pipe
app.useGlobalPipes(new ValidationPipe({ whitelist: true, transform: true }));
await app.listen(3000);
}
bootstrap();
NestJS CLI Commands
Table
| Command | Action |
|---|---|
nest new project-name | Create a new NestJS project scaffold |
nest g module users | Generate a new module (users.module.ts) |
nest g controller users | Generate a controller (users.controller.ts) |
nest g service users | Generate a service (users.service.ts) |
nest g resource products | Generate full CRUD resource (Module, Controller, DTO, Service) |
Common Pitfalls & Tips
[!WARNING] Remember to register your Service in the
providersarray and your Controller in thecontrollersarray of their parent@Module(), otherwise Dependency Injection will throw anUnknownElementException.
[!TIP] Use
whitelist: trueinValidationPipeto automatically strip any undisclosed properties from incoming request DTO payloads.