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

Bài 1: Giới thiệu NestJS - Tại sao chọn NestJS?

Tìm hiểu NestJS là gì, so sánh với Express, Fastify, Koa. Kiến trúc Module-based, Dependency Injection, TypeScript-first. Hệ sinh thái và use cases thực tế.

💻 Lập trình — Bài 1 Bài 1: Giới thiệu NestJS - Tại sao chọn NestJS?

NestJS: Từ Cơ bản đến Nâng cao

Phần 1: Nền tảng NestJS

xdev.asia

1. NestJS là gì?

NestJS là một framework Node.js progressive, sử dụng TypeScript làm ngôn ngữ chính, được thiết kế để xây dựng server-side applications hiệu quả, đáng tin cậy và có khả năng mở rộng cao. Được tạo bởi Kamil Myśliwiec vào năm 2017, NestJS lấy cảm hứng từ Angular với kiến trúc Module-based, Dependency Injection và Decorator pattern.

NestJS chạy trên nền Express.js (mặc định) hoặc Fastify, cung cấp tầng abstraction phía trên nhưng vẫn cho phép truy cập trực tiếp API của platform bên dưới khi cần.

Tại sao chọn NestJS?

  • TypeScript-first: Được viết hoàn toàn bằng TypeScript, hỗ trợ type safety mạnh mẽ

  • Architecture opinionated: Cung cấp kiến trúc rõ ràng, dễ maintain cho team lớn

  • Dependency Injection: IoC container built-in, dễ dàng testing và loose coupling

  • Hệ sinh thái phong phú: GraphQL, WebSockets, Microservices, CQRS, và hơn 200+ packages chính thức

  • Enterprise-ready: Được sử dụng bởi Adidas, Roche, Trilon, và nhiều công ty lớn

2. So sánh NestJS với các Framework khác

Tiêu chíNestJSExpressFastifyKoa
TypeScriptNativePluginPluginPlugin
ArchitectureOpinionatedMinimalistMinimalistMinimalist
DI ContainerBuilt-in❌❌❌
CLIPowerfulexpress-generatorfastify-cli❌
GraphQL@nestjs/graphqlapollo-servermercuriusapollo-server
WebSocket@nestjs/websocketssocket.iofastify-websocketManual
MicroservicesBuilt-in❌❌❌
TestingTesting moduleManual setupManual setupManual setup
Learning CurveTrung bìnhThấpThấpThấp
Phù hợpEnterprise, Team lớnMVP, Small appsHigh performanceMiddleware-focused

3. Kiến trúc NestJS

NestJS tuân theo kiến trúc 3-layer kết hợp với module system:

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

Các thành phần chính

  • Modules: Đơn vị tổ chức code, nhóm các thành phần liên quan lại với nhau

  • Controllers: Xử lý HTTP requests, định nghĩa routes và trả về responses

  • Providers/Services: Chứa business logic, được inject vào Controllers qua DI

  • Guards: Kiểm tra authorization trước khi request đến handler

  • Interceptors: Transform data trước/sau khi handler xử lý

  • Pipes: Validate và transform input data

  • Filters: Xử lý exceptions và format error responses

  • Middleware: Chạy trước route handler, tương tự Express middleware

4. Request Lifecycle trong NestJS

Khi một HTTP request đến NestJS application, nó đi qua các lớp theo thứ tự:

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

Hiểu rõ lifecycle này rất quan trọng vì nó giúp bạn biết đặt logic ở đâu cho phù hợp.

5. Hệ sinh thái NestJS

NestJS có hệ sinh thái packages chính thức rất phong phú:

PackageMục đích
@nestjs/typeormTypeORM integration cho SQL databases
@nestjs/mongooseMongoose integration cho MongoDB
@nestjs/graphqlGraphQL API với Apollo/Mercurius
@nestjs/websocketsReal-time với 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. Khi nào nên dùng NestJS?

Nên dùng NestJS khi:

  • Dự án enterprise, team lớn cần kiến trúc rõ ràng
  • Cần TypeScript native support
  • Cần Microservices architecture
  • Cần tích hợp nhiều protocols (REST + GraphQL + WebSocket)
  • Dự án dài hạn cần maintainability cao
  • Backend cho Angular/React/Vue applications

Cân nhắc alternatives khi:

  • MVP nhỏ, cần ship nhanh → Express/Fastify
  • Serverless functions đơn giản → AWS Lambda trực tiếp
  • API cực đơn giản, vài endpoints → Hono, Elysia

7. Tổng kết

NestJS là framework Node.js hiện đại nhất cho backend development, đặc biệt phù hợp cho các dự án enterprise cần kiến trúc rõ ràng và khả năng mở rộng. Với TypeScript-first approach, Dependency Injection built-in và hệ sinh thái phong phú, NestJS giúp developer xây dựng applications chất lượng cao một cách hiệu quả.

Trong bài tiếp theo, chúng ta sẽ ôn tập TypeScript essentials — những kiến thức TypeScript cần thiết để làm việc hiệu quả với NestJS.