NestJS Tutorial
Learn NestJS step by step: 42 lessons in 10 chapters with examples, quizzes, diagrams and projects.
Start learning →
of lessons completed
Getting Started
- What is NestJS? Learn what NestJS is, why it adds structure on top of Express or Fastify, when it beats plain Express, and see its core idea in a small runnable stand-in.
- How a Nest App Boots See what happens when NestFactory.create runs: the module graph is scanned, the DI container builds providers, routes are registered and a platform adapter starts.
- Project Structure and the CLI Create a project with nest new, understand main.ts and app.module, learn Nest naming conventions, use nest generate schematics and organize code in feature folders.
Controllers and Routing
- Controllers and Routing Learn how NestJS controllers map HTTP requests to methods: @Controller prefixes, route decorators, status codes, route order, wildcards and API versioning.
- Reading Request Data Read request data in NestJS with @Param, @Query, @Body and @Headers, model payloads with DTO classes, shape responses, and avoid the @Res and @Req pitfalls.
- Providers and Dependency Injection Understand NestJS providers, @Injectable and constructor injection, how the injector builds singletons, why DI helps testing, and how to avoid circular dependencies.
- Modules Learn how NestJS modules group controllers and providers, how imports and exports control visibility, and when to use shared, global and re-exporting modules.
The Request Pipeline
- Middleware Learn NestJS middleware: class and functional middleware, consumer.apply with forRoutes and exclude, execution order, and when guards or interceptors fit better.
- Pipes and Validation Learn NestJS pipes: ParseIntPipe, ValidationPipe with class-validator DTOs, whitelist and transform options, and how to write custom pipes.
- Guards and Authorization Learn NestJS guards: implement CanActivate, read metadata with Reflector and SetMetadata, build a roles guard, and mark public routes under a global auth guard.
- Interceptors Learn NestJS interceptors: NestInterceptor and CallHandler, RxJS pipe basics, and how to log, time, reshape responses, cache and time out handlers.
- Exception Filters and Errors Learn NestJS error handling: HttpException and the built-in exceptions, writing @Catch filters, binding them globally, and returning one consistent error body.
- Custom Decorators Write your own NestJS decorators: createParamDecorator for @CurrentUser, SetMetadata wrappers such as @Roles, and applyDecorators to bundle several decorators into one.
Advanced Dependency Injection
- Custom Providers Learn NestJS custom providers: useClass, useValue, useFactory and useExisting, injection tokens, @Inject, optional dependencies, and how to swap providers.
- Configuration and Environment Learn NestJS configuration with ConfigModule and ConfigService: .env files, typed config namespaces with registerAs, and validating environment variables at startup.
- Dynamic Modules and Provider Scopes Learn NestJS dynamic modules (forRoot, register, forRootAsync, global modules) and the DEFAULT, REQUEST and TRANSIENT provider scopes with their performance cost.
Data and Persistence
- Connecting to a Database Learn how to connect NestJS to a database: TypeORM, Prisma and MikroORM compared, module setup, async connection config, the repository seam and health checks.
- Repositories, Entities and Relations Model data in NestJS with entities and repositories, map one-to-many and many-to-many relations, avoid the N+1 query problem, paginate lists and separate DTOs from entities.
- Transactions and Migrations Learn how to keep NestJS data consistent: database transactions in services, the unit of work, a safe migration workflow, seeding and detecting schema drift.
- MongoDB with Mongoose Use MongoDB in NestJS with @nestjs/mongoose: define schemas with decorators, register them with forFeature, inject models, write a CRUD service, populate references and compare with TypeORM.
Building Real APIs
- Authentication with JWT Build JWT authentication in NestJS: hash passwords, sign tokens with JwtService, write an auth guard, rotate refresh tokens and see how Passport fits in.
- OpenAPI and Swagger Docs Document a NestJS API with @nestjs/swagger: DocumentBuilder, ApiProperty, the CLI schema plugin, versioned docs, client generation, and how the spec is built.
- Caching, Throttling and Scheduling Speed up and protect a NestJS API: CacheModule and cache-manager, ThrottlerGuard rate limits, and cron jobs with @nestjs/schedule, plus runnable stand-ins.
- File Uploads with Multer Accept file uploads in NestJS with FileInterceptor and Multer, validate size and type with ParseFilePipe, choose disk or memory storage, and stream downloads with StreamableFile.
- Calling External APIs with HttpModule Call external APIs from NestJS with @nestjs/axios: HttpModule and HttpService, firstValueFrom, timeouts, retries with backoff, and mapping upstream errors to clean responses.
- GraphQL with NestJS Build a GraphQL API in NestJS with @nestjs/graphql: code-first versus schema-first, @ObjectType and @Field, resolvers, @Args, @ResolveField and guards on resolvers.
- Server-Side Views and Static Files Serve HTML from NestJS: set up a view engine with Handlebars, return data with @Render, escape output safely, and serve CSS, images and a built SPA with useStaticAssets and ServeStaticModule.
Beyond HTTP
- Microservices and Transports Learn NestJS microservices: transports (TCP, Redis, NATS, RabbitMQ, Kafka, gRPC), message vs event patterns, ClientProxy, hybrid apps, with a loopback TCP stand-in.
- Queues and Events Decouple work in NestJS with the EventEmitter module and BullMQ queues: producers, workers, retries with backoff, idempotency, plus a runnable event bus and job queue.
- WebSockets and Gateways Build real-time features in NestJS with @WebSocketGateway: message handlers, rooms, guards and pipes on gateways, adapters, scaling with Redis, plus a loopback demo.
- CQRS Basics Learn CQRS in NestJS with @nestjs/cqrs: commands, queries, events, handlers, sagas, a read model, and an honest look at when the pattern is worth its extra code.
Testing and Production
- Testing Nest Applications Learn to test NestJS apps: Test.createTestingModule, overriding providers, unit tests with mocks, e2e tests with supertest, and test databases.
- Security and Hardening Harden a NestJS API: security headers with helmet, CORS, CSRF, rate limiting, whitelisting DTOs against mass assignment, secrets and dependency hygiene.
- Deployment and Performance Ship a NestJS app: build output, a Docker image, the Fastify adapter, compression, graceful shutdown hooks, Terminus health checks, logging and monorepos.
Projects
- Project: Todo REST API Build a Todo REST API in NestJS: module layout, DTOs with validation, an in-memory service, filtering, pagination, an error filter and tests.
- Project: Auth Service Build an auth service in NestJS: registration, password hashing, login, JWT access tokens, a global guard, roles, and rotating refresh tokens.
- Project: Blog API with Relations Build a blog API in NestJS: posts, comments and authors with relations, pagination with totals, and an interceptor that gives every response one shape.
- Project: Realtime Chat Gateway Build a realtime chat gateway in NestJS: authenticate on connect, join rooms, validate every message, keep room history, and watch it all run in a loopback demo.
Practice and Review
- Exercises: Core Concepts Practice NestJS core concepts with six exercises on controllers, dependency injection, modules, pipes, guards and pipeline order, each with a full solution.
- Exercises: Advanced Patterns Practice advanced NestJS patterns: dynamic modules, interceptors, database transactions and retrying job queues, with solutions and runnable stand-ins.
- NestJS Interview Questions 25 NestJS interview questions with short answers: DI, lifecycle, request pipeline order, scopes, guards vs middleware, microservices and testing, plus live demos.
- NestJS Cheat Sheet A one-page NestJS cheat sheet: decorators, request pipeline order, provider forms, lifecycle hooks, CLI commands, testing and config snippets, plus two live demos.