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í | NestJS | Express | Fastify | Koa |
|---|---|---|---|---|
| TypeScript | Native | Plugin | Plugin | Plugin |
| Architecture | Opinionated | Minimalist | Minimalist | Minimalist |
| DI Container | Built-in | ❌ | ❌ | ❌ |
| CLI | Powerful | express-generator | fastify-cli | ❌ |
| GraphQL | @nestjs/graphql | apollo-server | mercurius | apollo-server |
| WebSocket | @nestjs/websockets | socket.io | fastify-websocket | Manual |
| Microservices | Built-in | ❌ | ❌ | ❌ |
| Testing | Testing module | Manual setup | Manual setup | Manual setup |
| Learning Curve | Trung bình | Thấp | Thấp | Thấp |
| Phù hợp | Enterprise, Team lớn | MVP, Small apps | High performance | Middleware-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ú:
| Package | Mục đích |
|---|---|
| @nestjs/typeorm | TypeORM integration cho SQL databases |
| @nestjs/mongoose | Mongoose integration cho MongoDB |
| @nestjs/graphql | GraphQL API với Apollo/Mercurius |
| @nestjs/websockets | Real-time với WebSocket/Socket.IO |
| @nestjs/microservices | Microservices (TCP, Redis, NATS, RabbitMQ, Kafka, gRPC) |
| @nestjs/passport | Authentication strategies |
| @nestjs/jwt | JWT token generation/verification |
| @nestjs/throttler | Rate limiting |
| @nestjs/config | Configuration management |
| @nestjs/schedule | Task scheduling (Cron jobs) |
| @nestjs/cache-manager | Caching (Memory, Redis) |
| @nestjs/swagger | OpenAPI/Swagger documentation |
| @nestjs/terminus | Health checks |
| @nestjs/event-emitter | Event-driven architecture |
| @nestjs/cqrs | Command 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.