03 / 03

How do you apply middleware to specific routes or exclude certain routes in NestJS?

MiddlewareConsumer provides a fluent API. Use forRoutes() to target specific controllers, paths, or route objects with method constraints. Use exclude() to skip specific paths. Multiple middleware classes can be chained in a single apply() call and execute left to right.

MiddlewareConsumer fluent API
forRoutes() accepts three forms:
  1. 1

    Controller class — applies to all routes of that controller.

  2. 2

    Path string — e.g. 'users' or 'admin/*' with wildcard support.

  3. 3

    Route object — { path: 'users', method: RequestMethod.GET } for method-specific binding.

  4. 4

    Multiple middleware in apply(Mw1, Mw2) execute in order from left to right.

  5. 5

    exclude() path matching is based on path-to-regexp — patterns like 'auth/(.*) are supported.