We use cookies to understand how the site is used and to display ads. Analytics and advertising only run after you accept. You can change your choice anytime. Privacy policy

Skip to content
devvkit
$devvkit learn --librarie nestjs-guide

NestJS Guide

[nodejs][backend][typescript][api]
JavaScript / TypeScript
Install
npm install -g @nestjs/cli
nest new my-app --package-manager npm

NestJS brings Angular-style architecture to Node.js. It uses controllers (routing), providers/services (business logic), modules (organization), and decorators for metadata.

NestJS is framework-agnostic under the hood: it can run on Express (default) or Fastify via adapters. GraphQL, WebSockets, queues, and caching are first-class plugins.

Dependency injection is baked in. Providers are singletons by default. Guards control auth, interceptors transform responses, pipes validate inputs, and filters handle errors.

Setup

Create project· Scaffold NestJS app.
nest new my-app --strict
cd my-app
npm run start:dev
Generate resource· CRUD module.
nest g resource users
# Generates module, controller, service, DTOs, entity

Controllers

Controller· Route handler.
@Controller('users')
export class UsersController {
  constructor(private readonly usersService: UsersService) {}

  @Get()
  findAll() { return this.usersService.findAll() }

  @Get(':id')
  findOne(@Param('id', ParseIntPipe) id: number) { return this.usersService.findOne(id) }

  @Post()
  create(@Body() dto: CreateUserDto) { return this.usersService.create(dto) }
}

Providers

Service· Business logic provider.
@Injectable()
export class UsersService {
  constructor(private readonly prisma: PrismaService) {}

  async findAll() { return this.prisma.user.findMany() }
  async findOne(id: number) { return this.prisma.user.findUnique({ where: { id } }) }
  async create(dto: CreateUserDto) { return this.prisma.user.create({ data: dto }) }
}

Modules

Module· Organize related code.
@Module({
  controllers: [UsersController],
  providers: [UsersService],
  imports: [PrismaModule],
})
export class UsersModule {}

Pipes & Validation

Validation pipe· Auto-validate DTOs.
import { IsString, IsEmail, IsOptional } from 'class-validator'

export class CreateUserDto {
  @IsString()
  name!: string

  @IsEmail()
  email!: string

  @IsOptional()
  @IsString()
  bio?: string
}

// main.ts:
app.useGlobalPipes(new ValidationPipe({ whitelist: true }))

Guards

Auth guard· Protect routes.
@Injectable()
export class AuthGuard implements CanActivate {
  canActivate(context: ExecutionContext): boolean {
    const request = context.switchToHttp().getRequest()
    return validateToken(request.headers.authorization)
  }
}

// Usage:
@UseGuards(AuthGuard)
@Get('profile')
getProfile() {}

Swagger

Swagger setup· Auto-generated OpenAPI docs.
import { DocumentBuilder, SwaggerModule } from '@nestjs/swagger'

const config = new DocumentBuilder()
  .setTitle('My API')
  .setVersion('1.0')
  .addBearerAuth()
  .build()
const document = SwaggerModule.createDocument(app, config)
SwaggerModule.setup('docs', app, document)