03 / 12

What is the difference between app.use() and NestJS middleware?

app.use() registers Express/Fastify middleware directly — it works but bypasses NestJS DI so it cannot inject services. NestJS middleware classes implement NestMiddleware, are decorated with @Injectable(), and are applied via configure() in a module implementing NestModule — allowing them to use injected services.

NestJS middleware with DI
Key differences:
  1. 1

    app.use() — functional middleware, no DI, registered globally.

  2. 2

    NestJS middleware — class-based, supports DI, can be scoped to specific routes.

  3. 3

    NestJS middleware can be excluded from specific routes using .exclude().

  4. 4

    Use app.use() for simple third-party middleware (helmet, cors, compression).