Middleware trong NestJS

Bài 7 – Middleware và vai trò trong pipeline của NestJS

20/11/2025 DaiPhan
Bài 7 / 8

Middleware trong NestJS

Middleware xử lý request trước khi chúng đến controller. Đây là nơi phù hợp để thực hiện các tác vụ như logging, xác thực cơ bản, hoặc thao tác dữ liệu request.


1. Nội dung chính

  • Middleware là gì trong NestJS.
  • Middleware áp dụng toàn cục, theo module hoặc theo route.
  • Tạo middleware bằng Nest CLI.
  • Sử dụng consumer để cấu hình middleware.
  • Trường hợp sử dụng phổ biến: logging, check header, attach metadata.

2. Ví dụ

// Tạo middleware
// nest g middleware logger

import { Injectable, NestMiddleware } from '@nestjs/common';
import { Request, Response, NextFunction } from 'express';

@Injectable()
export class LoggerMiddleware implements NestMiddleware {
  use(req: Request, res: Response, next: NextFunction) {
    console.log(`Request: ${req.method} ${req.url}`);
    next();
  }
}

// Áp dụng middleware trong module
import { Module, NestModule, MiddlewareConsumer } from '@nestjs/common';
import { UsersController } from './users.controller';

@Module({
  controllers: [UsersController],
})
export class UsersModule implements NestModule {
  configure(consumer: MiddlewareConsumer) {
    consumer.apply(LoggerMiddleware).forRoutes(UsersController);
  }
}
3. Kiến thức trọng tâm
Middleware chạy trước controller và không dùng decorator.

Dùng MiddlewareConsumer để áp middleware theo module hoặc theo route cụ thể.

Middleware phù hợp cho logging, check auth bản, validate header hoặc thao tác dữ liệu request.

4. Bài tập nhanh
Tạo middleware authCheck kiểm tra header x-api-key.

Nếu thiếu key, trả về response 403; nếu có, cho phép request đi tiếp.

Áp dụng middleware này cho module products.

5. Kết luận
Middleware lớp xử đầu tiên trong pipeline của NestJS. Khi áp dụng đúng, middleware giúp chuẩn hóa request, tăng tính bảo mật đảm bảo luồng xử thống nhất.