>_
EngineeringNotes
← Back to Node.js & Runtimes
Module 07

NestJS (Scalable Backend)

The progressive Node.js framework for building efficient, reliable, and enterprise-grade scalable server-side applications.

01

What is NestJS?

Definition: NestJS is a progressive Node.js framework for building efficient, scalable, and maintainable server-side applications using TypeScript. It provides a structured architecture (similar to Spring Boot) on top of Node.js.

Key Engineering Concept

NestJS is a TypeScript-first framework built on top of Express (or Fastify) that utilizes dependency injection and modular architecture.

  • Highly structured and opinionated.
  • Extensive use of functional programming and OOP principles.
02

Why NestJS over Express?

The Express Problem

  • No structure enforced by default.
  • Extremely difficult to scale large, team-based apps.
  • No built-in architectural patterns.

The NestJS Solution

  • Out-of-the-box modular architecture.
  • Native Dependency Injection system.
  • Strict clean code organization.
03

Core Architecture (The Blueprint)

NestJS enforces a strict tree-based structure:

Module
Controller
Service
1. Module

The gateway to functionality. Groups related controllers and providers.

2. Controller

The entry point. Responsible for handling incoming requests and returning responses.

3. Service

The engine. Contains the core business logic and data processing.

04

Project Structure & Setup

Recommended CLI Setup

npm i -g @nestjs/cli
nest new app-name

Enterprise Structure

src/
 ├── app.module.ts (Root)
 ├── users/
 │    ├── users.module.ts
 │    ├── users.controller.ts
 │    └── users.service.ts
05

Controllers & Services Implementation

The Controller (Request Handler)

users.controller.ts
typescript
import { Controller, Get } from '@nestjs/common';

@Controller('users')
export class UsersController {
  @Get()
  getUsers() {
    return "Returning all users via NestJS structure";
  }
}

@Controller('users') sets the root path to /users.

The Service (Business Logic)

users.service.ts
typescript
import { Injectable } from '@nestjs/common';

@Injectable() // Marks this as a provider for DI
export class UsersService {
  fetchData() {
    return ["User Alpha", "User Sigma"];
  }
}
06

Dependency Injection & Modularization

Dependency Injection (DI) Concept

NestJS automatically manages and provides instances of classes (providers) where they are requested in constructors.

Dependency link
typescript
constructor(private readonly usersService: UsersService) {}

@Get()
getUsers() {
  return this.usersService.fetchData();
}

The Module Wrapper

users.module.ts
typescript
@Module({
  controllers: [UsersController],
  providers: [UsersService],
})
export class UsersModule {}

This organizes the feature into a single reusable unit within the application tree.

07

Advanced Request Context Parsing

NestJS provides decorators to extract payload data cleanly from the HTTP context.

params-query.ts
typescript
// Route Parameters
@Get(':id')
getUser(@Param('id') id: string) {
  return id;
}

// Query String
@Get()
search(@Query('q') query: string) {
  return query;
}
body-headers.ts
typescript
// Request Body
@Post()
create(@Body() dto: any) {
  return dto;
}

// Response Headers
@Get()
fetch(@Header('X-API-Key') key: string) {
  return key;
}
08

Middleware & Pipes (Transformation)

Middleware

Standard functions called before the route handler, following the Express pattern.

typescript
typescript
export function logger(req, res, next) {
  console.log("Logged Request Path...");
  next();
}

Pipes (Transformation)

Used to transform or validate input data before it reaches the controller.

typescript
typescript
@Get(':id')
find(@Param('id', ParseIntPipe) id: number) {
  return id; // Automatically cast to int
}
09

Guards & Interceptors (Security & Logic)

Guards

Responsible for Authorization. Guards determine if a request should be handled by the route or blocked.

typescript
typescript
@Injectable()
export class AuthGuard {
  canActivate() {
    return true;
  }
}

Interceptors

Wrap request/response streams. Used for logging, data mapping, and performance monitoring.

typescript
typescript
// Logic before & after response execution
return next
  .handle()
  .pipe(tap(() => console.log('End')));
10

Global Exception Filtering

NestJS includes a built-in exceptions layer responsible for processing all unhandled exceptions across the application.

global-exception.filter.ts
typescript
@Catch(HttpException)
export class HttpExceptionFilter {
  catch(exception: HttpException, host: ArgumentsHost) {
     // Manually construct high-quality error responses
  }
}
11

Core Comparison: Express vs NestJS

Operational FeatureExpress.jsNestJS
ArchitectureMinimal / UnstructuredStrictly Modular / DI
ScalabilityMedium (Manual overhead)Excellent (Enterprise-ready)
Learning CurveEasy (Low entry barrier)Medium (Requires OOP/TS knowledge)
Dependency InjectionNone Out-of-the-boxNative Implementation
12

Enterprise Interview Preparation

What is NestJS?
Answer:A progressive Node.js framework for building scalable server-side applications, offering a highly modular structure inspired by Spring Boot/Angular.
What is Dependency Injection in NestJS?
Answer:A design pattern where the framework automatically instantiates and provides dependencies (like Services) into classes (like Controllers) via the constructor.
Explain the difference between a Controller and a Service.
Answer:Controllers handle incoming HTTP requests and map them to routes; Services contain the actual business logic and interact with databases/external APIs.
What are Pipes and when should you use them?
Answer:Pipes are used for transformation (casting types) and validation (ensuring input schema matches expectations) before the data reaches the controller.
How do Guards manage authorization?
Answer:Guards implement logic to determine whether a request meets certain conditions (like checking a JWT token) before allowing access to a route.
Why choose NestJS over Express for a large-scale project?
Answer:NestJS enforces a standard architecture, encourages TypeScript by default, and provides built-in tools for scalability and maintainability that must be manually configured in Express.

The NestJS Mental Model

MODULEFeature Grouping
CONTROLLERRequest Entry
SERVICEBusiness Engine
D. I.Connectivity