What is NestJS middleware vs guards vs interceptors?
Answer
These three mechanisms all run during request processing but at different points and serve different purposes. Middleware: runs before the route is dispatched. Has access to req and res. Used for logging, CORS, body parsing, and non-route-specific concerns. Applied with app.use() or in the module's configure() method. Guards: run after middleware. Determine if the request is authorized. Return boolean. Used for authentication/authorization. Pipes: run after guards. Transform and validate route handler parameters. Interceptors: run before and after the route handler. Can transform request/response data, add caching, or log timing. Exception Filters: run when an exception is thrown. The order is: Middleware → Guards → Interceptors (before) → Pipes → Route Handler → Interceptors (after) → Filters.