Back to Backend & APIs

Module 6: NestJS Framework

Build enterprise-grade, scalable applications with NestJS and TypeScript.

What is NestJS?

NestJS is a progressive Node.js framework for building efficient, reliable, and scalable server-side applications. Think of it as Angular for the backend - it brings structure, TypeScript, and enterprise patterns to Node.js development.

🚀 Why NestJS?

  • TypeScript First: Full type safety
  • Modular Architecture: Organized, maintainable code
  • Dependency Injection: Testable, decoupled components
  • Decorators: Clean, declarative syntax
  • Built-in Features: Guards, pipes, interceptors
  • Microservices Ready: Built-in support

Getting Started

Create NestJS Project:

# Install Nest CLI

npm i -g @nestjs/cli

# Create new project

nest new my-api

cd my-api

# Run development server

npm run start:dev

# Generate resources

nest g module users

nest g controller users

nest g service users

NestJS Architecture

Complete Example:

// users.entity.ts

export class User {

id: number;

name: string;

email: string;

}

// users.service.ts

import { Injectable } from '@nestjs/common';

@Injectable()

export class UsersService {

private users: User[] = [];

private nextId = 1;

findAll(): User[] {

return this.users;

}

findOne(id: number): User {

return this.users.find(u => u.id =>= id);

}

create(user: Partial<User>): User {

const newUser = { id: this.nextId++, ...user } as User;

this.users.push(newUser);

return newUser;

}

update(id: number, user: Partial<User>): User {

const index = this.users.findIndex(u => u.id =>= id);

this.users[index] = { ...this.users[index], ...user };

return this.users[index];

}

remove(id: number): void {

this.users = this.users.filter(u => u.id !=> id);

}

}

// users.controller.ts

import { Controller, Get, Post, Put, Delete, Body, Param } from '@nestjs/common';

@Controller('users')

export class UsersController {

constructor(private usersService: UsersService) {}

@Get()

findAll() {

return this.usersService.findAll();

}

@Get(':id')

findOne(@Param('id') id: string) {

return this.usersService.findOne(+id);

}

@Post()

create(@Body() user: Partial<User>) {

return this.usersService.create(user);

}

@Put(':id')

update(@Param('id') id: string, @Body() user: Partial<User>) {

return this.usersService.update(+id, user);

}

@Delete(':id')

remove(@Param('id') id: string) {

return this.usersService.remove(+id);

}

}

// users.module.ts

import { Module } from '@nestjs/common';

@Module({

controllers: [UsersController],

providers: [UsersService],

exports: [UsersService]

})

export class UsersModule {}

Guards, Pipes & Interceptors

Guards (Authentication):

import { Injectable, CanActivate, ExecutionContext } from '@nestjs/common';

@Injectable()

export class AuthGuard implements CanActivate {

canActivate(context: ExecutionContext): boolean {

const request = context.switchToHttp().getRequest();

return !!request.headers.authorization;

}

}

// Use guard

@UseGuards(AuthGuard)

@Get('profile')

getProfile() {

return { message: 'Protected route' };

}

Pipes (Validation):

import { IsEmail, IsNotEmpty } from 'class-validator';

export class CreateUserDto {

@IsNotEmpty()

name: string;

@IsEmail()

email: string;

}

@Post()

create(@Body(ValidationPipe) dto: CreateUserDto) {

return this.usersService.create(dto);

}

📚 Module Summary

You've mastered NestJS:

  • ✓ NestJS architecture and modules
  • ✓ Controllers and services
  • ✓ Dependency injection
  • ✓ Guards, pipes, and interceptors
  • ✓ TypeScript integration

Next: Learn microservices architecture!