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
DecoratorTargetPurpose / Meaning
@Module({ imports, controllers, providers })ClassGroup related controllers, services, and sub-modules
@Controller('prefix')ClassDefine route path controller handler
@Injectable()ClassMark service class for Dependency Injection container
@Get(), @Post(), @Put(), @Delete()MethodMap HTTP method and sub-route path
@Param('id'), @Query('page'), @Body()ParameterExtract URL params, query string, or body payload
@UsePipes(), @UseGuards(), @UseInterceptors()Class/MethodAttach 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
CommandAction
nest new project-nameCreate a new NestJS project scaffold
nest g module usersGenerate a new module (users.module.ts)
nest g controller usersGenerate a controller (users.controller.ts)
nest g service usersGenerate a service (users.service.ts)
nest g resource productsGenerate full CRUD resource (Module, Controller, DTO, Service)

Common Pitfalls & Tips

[!WARNING] Remember to register your Service in the providers array and your Controller in the controllers array of their parent @Module(), otherwise Dependency Injection will throw an UnknownElementException.

[!TIP] Use whitelist: true in ValidationPipe to automatically strip any undisclosed properties from incoming request DTO payloads.