Chuyển đến nội dung chính

Lesson 1: Introducing NestJS - Why choose NestJS?

Find out what NestJS is, compare with Express, Fastify, Koa. Module-based architecture, Dependency Injection, TypeScript-first. Ecosystem and practical use cases.

💻 Programming — Lesson 1 Lesson 1: Introducing NestJS - Why choose NestJS?

NestJS: From Basics to Advanced

Part 1: NestJS Platform

xdev.asia

1. What is NestJS?

NestJS is a progressive Node.js framework, using TypeScript as the main language, designed to build efficient, reliable and highly scalable server-side applications. Created by Kamil Myśliwiec in 2017, NestJS took inspiration from Angular with its architecture Module-based, Dependency Injection and Decorator patterns.

NestJS runs on Express.js (default) or Fastify, providing an abstraction layer above but still allowing direct access to the underlying platform's API when needed.

Why choose NestJS?

  • TypeScript-first: Written entirely in TypeScript, supports strong type safety

  • Architecture opinionated: Provides a clear, easy-to-maintain architecture for large teams

  • Dependency Injection: IoC container built-in, easy testing and loose coupling

  • Rich ecosystem: GraphQL, WebSockets, Microservices, CQRS, and 200+ official packages

  • Enterprise-ready: Used by Adidas, Roche, Trilon, and many large companies

2. Compare NestJS with other Frameworks

CriteriaNestJSExpressFastifyKoa
TypeScriptNativePluginsPluginsPlugins
ArchitectureOpinionatedMinimalistMinimalistMinimalist
DI ContainersBuilt-in❌❌❌
CLIPowerfulexpress-generatorfastify-cli❌
GraphQL@nestjs/graphqlapollo-servermercuriusapollo-server
WebSockets@nestjs/websocketssocket.iofastify-websocketManual
MicroservicesBuilt-in❌❌❌
TestingTesting moduleManual setupManual setupManual setup
Learning CurveAverageLowLowLow
SuitableEnterprise, Big TeamMVP, Small appsHigh performanceMiddleware-focused

3. NestJS architecture

NestJS follows the architecture 3-layer Combined with module system:

┌──────────────────────────────────────────────┐
│                  Application                  │
├──────────────────────────────────────────────┤
│  ┌─────────────┐  ┌─────────────┐            │
│  │ Module A     │  │ Module B     │           │
│  │ ┌─────────┐ │  │ ┌─────────┐ │           │
│  │ │Controller│ │  │ │Controller│ │           │
│  │ └────┬────┘ │  │ └────┬────┘ │           │
│  │      ↓      │  │      ↓      │           │
│  │ ┌─────────┐ │  │ ┌─────────┐ │           │
│  │ │ Service  │ │  │ │ Service  │ │           │
│  │ └────┬────┘ │  │ └────┬────┘ │           │
│  │      ↓      │  │      ↓      │           │
│  │ ┌─────────┐ │  │ ┌─────────┐ │           │
│  │ │  Repo   │ │  │ │  Repo   │ │           │
│  │ └─────────┘ │  │ └─────────┘ │           │
│  └─────────────┘  └─────────────┘            │
├──────────────────────────────────────────────┤
│           Platform (Express/Fastify)          │
└──────────────────────────────────────────────┘

Main ingredients

  • Modules: Code organization unit, grouping related components together

  • Controllers: Handles HTTP requests, defines routes and returns responses

  • Providers/Services: Contains business logic, injected into Controllers via DI

  • Guards: Check authorization before request to handler

  • Interceptors: Transform data before/after handler processing

  • Pipes: Validate and transform input data

  • Filters: Handle exceptions and format error responses

  • Middleware: Runs before the route handler, similar to Express middleware

4. Request Lifecycle in NestJS

When an HTTP request comes to the NestJS application, it goes through the classes in this order:

Request
  → Middleware
    → Guards
      → Interceptors (before)
        → Pipes
          → Route Handler (Controller method)
        → Interceptors (after)
      → Exception Filters (nếu có lỗi)
Response

Understanding this lifecycle is important because it helps you know where to place logic appropriately.

5. NestJS ecosystem

NestJS has a very rich official packages ecosystem:

PackagePurpose
@nestjs/typebugTypeORM integration for SQL databases
@nestjs/mongooseMongoose integration for MongoDB
@nestjs/graphqlGraphQL API with Apollo/Mercurius
@nestjs/websocketsReal-time with WebSocket/Socket.IO
@nestjs/microservicesMicroservices (TCP, Redis, NATS, RabbitMQ, Kafka, gRPC)
@nestjs/passportAuthentication strategies
@nestjs/jwtJWT token generation/verification
@nestjs/throttlerRate limiting
@nestjs/configConfiguration management
@nestjs/scheduleTask scheduling (Cron jobs)
@nestjs/cache-managerCaching (Memory, Redis)
@nestjs/swaggerOpenAPI/Swagger documentation
@nestjs/terminusHealth checks
@nestjs/event-emitterEvent-driven architecture
@nestjs/cqrsCommand Query Responsibility Segregation

6. When should you use NestJS?

You should use NestJS when:

  • Enterprise projects and large teams need clear architecture
  • Needs TypeScript native support
  • Need Microservices architecture
  • Need to integrate many protocols (REST + GraphQL + WebSocket)
  • Long-term projects need high maintainability
  • Backend for Angular/React/Vue applications

Consider alternatives when:

  • Small MVP, needs fast shipping → Express/Fastify
  • Simple Serverless functions → Live AWS Lambda
  • Extremely simple API, few endpoints → Hono, Elysia

7. Summary

NestJS is the most modern Node.js framework for backend development, especially suitable for enterprise projects that need clear architecture and scalability. With TypeScript-first approach, Dependency Injection built-in and rich ecosystem, NestJS helps developers build high-quality applications efficiently.

In the next article, we will review TypeScript essentials — the TypeScript knowledge needed to work effectively with NestJS.