NestJS Cheatsheet

🛠️
Controllers
Core
Handle incoming requests and return responses. Controllers are the main entry point for handling HTTP requests.
@Controller('users')
export class UsersController {

  @Get()
  async findAll() {
    return this.usersService.findAll();
  }
}
        
💡 Tip
Controllers must be decorated with @Controller() and can use route decorators like @Get(), @Post()
⚙️
Services
Core
Handle business logic and data operations. Services are injectable classes that provide specific functionality.
@Injectable()
export class UsersService {
  findAll(): Promise {}
}
        
⚠️ Note
Services must be decorated with @Injectable() to be injectable into other classes
📦
Modules
Core
Organize related components and dependencies. Modules group related functionality and manage dependencies.
@Module({
  controllers: [UsersController],
  providers: [UsersService]
})
        
💡 Tip
Modules are the basic building blocks of NestJS applications and help organize code into logical units
🏷️
Decorators
Core
Add metadata and behavior to classes and methods. Decorators are used to modify or enhance classes and methods.
@Controller()
@Get()
@Post()
@Injectable()
@Serialize(GetUserDto)
        
⚠️ Note
Decorators are a key feature of TypeScript that NestJS heavily relies on for its functionality
📝
Middleware
HTTP
Process requests before they reach route handlers. Similar to Express middleware, but with NestJS features.
app.use(loggerMiddleware);
        
💡 Tip
Middleware can be used to log requests, authenticate users, or modify request/response objects
🔄
Interceptors
HTTP
Process requests and responses. Interceptors can modify incoming requests or outgoing responses.
@UseInterceptors(LoggingInterceptor)
@UseInterceptors(SerializeInterceptor)
        
⚠️ Note
Interceptors are more powerful than middleware as they have access to both request and response objects
🔄
Pipes
Validation
Transform and validate input data. Pipes ensure that incoming data conforms to expected formats.
app.useGlobalPipes(new ValidationPipe());
        
💡 Tip
Pipes are great for data validation and transformation before it reaches your business logic
🔒
Guards
Security
Control access to routes and methods. Guards implement the authorization logic in your application.
@UseGuards(AuthGuard)
@UseGuards(RolesGuard)
        
⚠️ Note
Guards are used to protect routes and methods based on user roles or permissions
❌
Exception Filters
Error Handling
Handle exceptions globally. Exception filters catch and process errors that occur during request processing.
@Catch(HttpException)
handleException(exception: HttpException) {}
        
💡 Tip
Exception filters help maintain consistent error handling across your application
⚡
Events
Async
Handle events and notifications. Events allow components to communicate asynchronously.
@EventEmitter()
emit('user.created', user)
        
⚠️ Note
Events are great for implementing publish-subscribe patterns in your application