Learn NESTJS with Real Code Examples
Updated Nov 25, 2025
Code Sample Descriptions
1
NestJS Simple Counter API
import { Controller, Get, Post } from '@nestjs/common';
import { Module } from '@nestjs/common';
import { NestFactory } from '@nestjs/core';
class CounterService {
private count = 0;
getCount() { return this.count; }
increment() { this.count++; return this.count; }
decrement() { this.count--; return this.count; }
reset() { this.count = 0; return this.count; }
}
@Controller('counter')
class CounterController {
constructor(private readonly service: CounterService) {}
@Get() getCount() { return { count: this.service.getCount() }; }
@Post('increment') increment() { return { count: this.service.increment() }; }
@Post('decrement') decrement() { return { count: this.service.decrement() }; }
@Post('reset') reset() { return { count: this.service.reset() }; }
}
@Module({ controllers: [CounterController], providers: [CounterService] })
class AppModule {}
async function bootstrap() {
const app = await NestFactory.create(AppModule);
await app.listen(3000);
console.log('NestJS server running on http://localhost:3000');
}
bootstrap();
Demonstrates a simple NestJS REST API with a counter using a service and controller.
2
NestJS Hello World API
import { Controller, Get } from '@nestjs/common';
import { Module } from '@nestjs/common';
import { NestFactory } from '@nestjs/core';
@Controller()
class AppController {
@Get() hello() { return { message: 'Hello World' }; }
}
@Module({ controllers: [AppController] })
class AppModule {}
async function bootstrap() {
const app = await NestFactory.create(AppModule);
await app.listen(3000);
}
bootstrap();
A basic NestJS REST API returning 'Hello World'.
3
NestJS Simple Todo API
import { Controller, Get, Post, Body } from '@nestjs/common';
import { Module } from '@nestjs/common';
import { NestFactory } from '@nestjs/core';
class TodoService {
private todos: string[] = [];
getAll() { return this.todos; }
add(todo: string) { this.todos.push(todo); return todo; }
}
@Controller('todos')
class TodoController {
constructor(private readonly service: TodoService) {}
@Get() getTodos() { return this.service.getAll(); }
@Post() addTodo(@Body('todo') todo: string) { return this.service.add(todo); }
}
@Module({ controllers: [TodoController], providers: [TodoService] })
class AppModule {}
async function bootstrap() {
const app = await NestFactory.create(AppModule);
await app.listen(3000);
}
bootstrap();
A minimal Todo REST API with in-memory storage.
4
NestJS Query Params Example
import { Controller, Get, Query } from '@nestjs/common';
import { Module } from '@nestjs/common';
import { NestFactory } from '@nestjs/core';
@Controller('greet')
class GreetController {
@Get() hello(@Query('name') name: string) { return { message: `Hello ${name || 'Guest'}` }; }
}
@Module({ controllers: [GreetController] })
class AppModule {}
async function bootstrap() {
const app = await NestFactory.create(AppModule);
await app.listen(3000);
}
bootstrap();
An API endpoint demonstrating query parameter usage.
5
NestJS POST JSON Example
import { Controller, Post, Body } from '@nestjs/common';
import { Module } from '@nestjs/common';
import { NestFactory } from '@nestjs/core';
@Controller('echo')
class EchoController {
@Post() echo(@Body() data: any) { return data; }
}
@Module({ controllers: [EchoController] })
class AppModule {}
async function bootstrap() {
const app = await NestFactory.create(AppModule);
await app.listen(3000);
}
bootstrap();
A POST endpoint receiving JSON data and returning it.
6
NestJS Middleware Example
import { Injectable, NestMiddleware, Module } from '@nestjs/common';
import { NestFactory } from '@nestjs/core';
import { Request, Response, NextFunction } from 'express';
@Injectable()
class LoggerMiddleware implements NestMiddleware {
use(req: Request, res: Response, next: NextFunction) {
console.log(`${req.method} ${req.url}`);
next();
}
}
@Module({})
class AppModule {
configure(consumer) {
consumer.apply(LoggerMiddleware).forRoutes('*');
}
}
async function bootstrap() {
const app = await NestFactory.create(AppModule);
await app.listen(3000);
}
bootstrap();
Shows how to use middleware to log requests in NestJS.
7
NestJS Exception Filter Example
import { ExceptionFilter, Catch, ArgumentsHost, HttpException, Module } from '@nestjs/common';
import { NestFactory } from '@nestjs/core';
import { Controller, Get } from '@nestjs/common';
@Catch(HttpException)
class HttpErrorFilter implements ExceptionFilter {
catch(exception: HttpException, host: ArgumentsHost) {
const ctx = host.switchToHttp();
const response = ctx.getResponse();
response.status(exception.getStatus()).json({ message: exception.message });
}
}
@Controller()
class AppController {
@Get('error') throwError() { throw new HttpException('Custom error', 400); }
}
@Module({ controllers: [AppController] })
class AppModule {}
async function bootstrap() {
const app = await NestFactory.create(AppModule);
app.useGlobalFilters(new HttpErrorFilter());
await app.listen(3000);
}
bootstrap();
A custom exception filter catching HTTP errors.
8
NestJS Param Example
import { Controller, Get, Param, Module } from '@nestjs/common';
import { NestFactory } from '@nestjs/core';
@Controller('users')
class UserController {
@Get(':id') getUser(@Param('id') id: string) { return { id, name: `User ${id}` }; }
}
@Module({ controllers: [UserController] })
class AppModule {}
async function bootstrap() {
const app = await NestFactory.create(AppModule);
await app.listen(3000);
}
bootstrap();
An endpoint demonstrating route parameters.
9
NestJS Service Injection Example
import { Injectable, Controller, Get, Module } from '@nestjs/common';
import { NestFactory } from '@nestjs/core';
@Injectable()
class HelloService { getMessage() { return 'Hello from Service'; } }
@Controller()
class AppController {
constructor(private readonly helloService: HelloService) {}
@Get() hello() { return { message: this.helloService.getMessage() }; }
}
@Module({ controllers: [AppController], providers: [HelloService] })
class AppModule {}
async function bootstrap() {
const app = await NestFactory.create(AppModule);
await app.listen(3000);
}
bootstrap();
Demonstrates dependency injection of a service into a controller.
10
NestJS Async Service Example
import { Injectable, Controller, Get, Module } from '@nestjs/common';
import { NestFactory } from '@nestjs/core';
@Injectable()
class AsyncService {
async fetchData() { return new Promise(resolve => setTimeout(() => resolve('Async Data'), 500)); }
}
@Controller()
class AppController {
constructor(private readonly service: AsyncService) {}
@Get('data') async getData() { return { data: await this.service.fetchData() }; }
}
@Module({ controllers: [AppController], providers: [AsyncService] })
class AppModule {}
async function bootstrap() {
const app = await NestFactory.create(AppModule);
await app.listen(3000);
}
bootstrap();
Shows a service returning data asynchronously using Promises.