如何在 AppModule 中全局注册中间件?如何为特定路由或模块限定中间件作用范围?

解读

这道题是国内一线/二线大厂后端面试的“必答题”。面试官想验证三件事:

  1. 你是否理解 NestJS 的 IoC 生命周期——中间件在 Express/Fastify 层与 Nest 容器之间如何桥接;
  2. 你是否能区分“全局”与“局部”两种注册方式对依赖注入、可测试性、性能的影响;
  3. 你是否能在真实业务里做“精细化”控制,比如只对 /admin 接口做鉴权,而不影响 /health。
    回答时切忌只贴代码,要给出“为什么这么做”以及“踩过哪些坑”。

知识点

  1. MiddlewareConsumer:Module 类里实现 configure(consumer: MiddlewareConsumer) 方法,consumer.apply().forRoutes() 决定作用范围。
  2. 全局中间件两种写法:
    a. main.ts 里 app.use() —— 纯 Express/Fastify 行为,无法注入 Nest 容器依赖;
    b. 在 AppModule 实现 configure() 并 forRoutes('*') —— 仍受 IoC 管理,可注入服务。
  3. 路由匹配粒度:支持通配符、路径、Method、RouteInfo 对象,甚至用自定义的 RouteInfo[] 做白名单/黑名单。
  4. 多模块场景:中间件必须注册在“引入目标 Controller 的 Module”里,否则顺序错乱;若需跨模块复用,可封装成可配置工厂。
  5. 性能陷阱:forRoutes('*') 会把静态资源、graphql、ws 一起拦截,通常要 .exclude('/graphql', '/health')。
  6. 测试策略:用 Test.createTestingModule 覆盖 configure,配合 supertest 断言中间件行为,避免启动真实端口。
  7. 国内合规:日志中间件需脱敏手机号、身份证,否则等保测评直接挂;鉴权中间件必须兼容国密 SM2 网关 header。

答案

  1. 全局注册(推荐在 AppModule 内完成,保持可注入、可测试)
// logger.middleware.ts
import { Injectable, NestMiddleware } from '@nestjs/common';
@Injectable()
export class LoggerMiddleware implements NestMiddleware {
  use(req: any, res: any, next: () => void) {
    console.log(`[${Date.now()}] ${req.method} ${req.originalUrl}`);
    next();
  }
}

// app.module.ts
import { MiddlewareConsumer, Module, NestModule } from '@nestjs/common';
@Module({})
export class AppModule implements NestModule {
  configure(consumer: MiddlewareConsumer) {
    consumer
      .apply(LoggerMiddleware)
      .exclude('/health', '/metrics')   // 国内运维监控路径必须放行
      .forRoutes('*');                  // 全局生效,仍受 IoC 管理
  }
}
  1. 限定作用范围(只给 AdminModule 的 /admin 路由加鉴权)
// auth.middleware.ts
@Injectable()
export class AuthMiddleware implements NestMiddleware {
  constructor(private readonly authService: AuthService) {}
  use(req: any, res: any, next: () => void) {
    const token = req.headers['x-access-token'];
    if (!this.authService.verifySm2Token(token)) {
      return res.status(401).json({ code: 401, msg: '未登录或令牌失效' });
    }
    next();
  }
}

// admin.module.ts
@Module({ controllers: [AdminController] })
export class AdminModule implements NestModule {
  configure(consumer: MiddlewareConsumer) {
    consumer
      .apply(AuthMiddleware)
      .forRoutes({ path: '/admin/*', method: RequestMethod.ALL });
  }
}
  1. 若中间件需要可配置参数,封装工厂函数:
export function loggerFactory(opts: { maskPhone: boolean }) {
  return (req, res, next) => {
    let url = req.originalUrl;
    if (opts.maskPhone) url = url.replace(/\d{11}/, '***********');
    console.log(url);
    next();
  };
}
// 使用 .apply(loggerFactory({ maskPhone: true }))
  1. 启动文件 main.ts 里不要再 app.use(),否则顺序不可控;如果必须引入第三方 Express 中间件(如 compression),在 main.ts 里 app.use(compression()) 即可,但它无法注入 Nest 服务。

拓展思考

  1. 微服务场景:MQTT/Redis 传输层不走 HTTP,中间件无效;此时应改用 NestJS 的 Interceptor 或 Guard,在 transport 层做鉴权。
  2. Serverless(阿里云 FC、腾讯云 SCF):冷启动要求“0 副作用”,全局中间件里若做同步 IO(读文件、建库链)会拖垮首次延迟,应把耗时逻辑延后到惰性工厂。
  3. 多租户 SaaS:在中间件里根据 host 或 header 注入 TENANT_ID,后续通过 AsyncLocalStorage 传递,避免每次解析 token;注意 Node 18 以下要装 cls-hooked,否则高并发下上下文丢失。
  4. 链路追踪:国内用 SkyWalking 或阿里 Arms,中间件里把 traceId 写进响应头 X-Trace-Id,方便前端一键定位;但要配合 Nginx 删除该头,防止外部伪造。
  5. 灰度发布:在 middleware 里读取配置中心(Nacos/Apollo)的灰度名单,动态 rewrite 到 v2 Controller,实现“零重启”切流;记得给 rewrite 路径加白名单,避免循环重写。