Middleware helps you run code before your route handles a request. It can check or change requests easily.
Applying middleware to routes in NestJS
import { Injectable, NestMiddleware } from '@nestjs/common'; import { Request, Response, NextFunction } from 'express'; @Injectable() export class MyMiddleware implements NestMiddleware { use(req: Request, res: Response, next: NextFunction) { // your code here next(); } } // In your module import { MiddlewareConsumer, Module, RequestMethod } from '@nestjs/common'; @Module({ providers: [MyMiddleware] }) export class AppModule { configure(consumer: MiddlewareConsumer) { consumer .apply(MyMiddleware) .forRoutes('route-path'); } }
Middleware class must implement NestMiddleware and have a use method.
Use consumer.apply(...).forRoutes(...) to attach middleware to routes.
LoggerMiddleware to all requests to the /cats route.consumer.apply(LoggerMiddleware).forRoutes('cats');AuthMiddleware only to GET requests on /dogs.consumer.apply(AuthMiddleware).forRoutes({ path: 'dogs', method: RequestMethod.GET });/users route.consumer.apply(LoggerMiddleware, AuthMiddleware).forRoutes('users');consumer.apply(MyMiddleware).forRoutes({ path: '*', method: RequestMethod.ALL });This example creates a simple logger middleware that prints the HTTP method and URL for GET requests to /hello. It shows how to apply middleware to a specific route and method.
import { Injectable, NestMiddleware, MiddlewareConsumer, Module, RequestMethod } 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 to: ${req.method} ${req.url}`); next(); } } @Module({ providers: [LoggerMiddleware] }) export class AppModule { configure(consumer: MiddlewareConsumer) { consumer .apply(LoggerMiddleware) .forRoutes({ path: 'hello', method: RequestMethod.GET }); } } // Assume a controller with GET /hello route exists
Always call next() in middleware to continue the request cycle.
You can apply middleware to multiple routes or methods by passing arrays.
Middleware runs before route handlers, so it can block or modify requests early.
Middleware runs code before routes handle requests.
Use consumer.apply(...).forRoutes(...) to attach middleware to routes.
Middleware can log, check, or change requests easily.
Practice
Solution
Step 1: Understand middleware role
Middleware runs before the route handler to process or modify requests.Step 2: Identify middleware effect on routes
It does not replace handlers or generate docs but can log or check requests first.Final Answer:
To run code before the route handler processes the request -> Option AQuick Check:
Middleware runs before route handlers [OK]
- Thinking middleware replaces route handlers
- Confusing middleware with response sending
- Assuming middleware auto-generates docs
LoggerMiddleware to all routes in a NestJS module?Solution
Step 1: Recall NestJS middleware syntax
The correct method to apply middleware isconsumer.apply(...).forRoutes(...).Step 2: Identify correct route pattern for all routes
Using'/'applies middleware to all routes;'*'is invalid.Final Answer:
consumer.apply(LoggerMiddleware).forRoutes('/'); -> Option BQuick Check:
Use apply + forRoutes('/') for all routes [OK]
- Using use() instead of apply()
- Using toRoutes() which is invalid
- Using '*' instead of '/' for all routes
consumer.apply(AuthMiddleware).forRoutes('users');Which routes will have the
AuthMiddleware applied?Solution
Step 1: Understand forRoutes string behavior
Passing 'users' applies middleware to all routes starting with '/users', including parameters.Step 2: Confirm middleware coverage
This includes '/users', '/users/123', '/users/profile', etc., not the entire app.Final Answer:
All routes including '/users' and '/users/:id' -> Option AQuick Check:
forRoutes('users') covers prefix routes [OK]
- Thinking only exact path matches get middleware
- Assuming middleware applies globally without '*'
- Believing invalid path disables middleware
export class AppModule implements NestModule {
configure(consumer: MiddlewareConsumer) {
consumer.apply(AuthMiddleware).forRoutes();
}
}What is the issue with this code?
Solution
Step 1: Check forRoutes usage
The method forRoutes requires at least one argument specifying routes; empty call is invalid.Step 2: Identify error type
Calling forRoutes() without arguments causes a runtime error because no routes are defined.Final Answer:
Missing route argument in forRoutes causes a runtime error -> Option CQuick Check:
forRoutes() needs routes argument [OK]
- Leaving forRoutes empty
- Assuming middleware applies globally without routes
- Ignoring missing @Injectable on middleware
LoggerMiddleware only to POST requests on the /orders route in NestJS. Which approach correctly applies middleware only to POST /orders requests?Solution
Step 1: Understand method filtering in middleware
NestJS allows specifying method with an object: { path, method } in forRoutes.Step 2: Identify correct syntax for POST-only middleware
Using consumer.apply(...).forRoutes({ path: 'orders', method: RequestMethod.POST }) applies middleware only to POST /orders.Final Answer:
Use consumer.apply(LoggerMiddleware).forRoutes({ path: 'orders', method: RequestMethod.POST }); -> Option DQuick Check:
Use object with path and method in forRoutes for method filtering [OK]
- Applying middleware to all methods without filtering
- Checking method inside middleware instead of in forRoutes
- Applying middleware globally and filtering inside middleware
Ready to prove it?
Pass the test and this pattern moves unknown
