What if you could write your security checks once and have them work everywhere automatically?
Why Global middleware in NestJS? - Purpose & Use Cases
Imagine you have to check user authentication on every single route in your app by writing the same code again and again.
Manually adding checks to each route is tiring, easy to forget, and makes your code messy and hard to maintain.
Global middleware runs once for all routes automatically, so you write the logic just once and it applies everywhere.
app.get('/profile', checkAuth, handler); app.get('/settings', checkAuth, handler);
app.use(globalAuthMiddleware); app.get('/profile', handler); app.get('/settings', handler);
You can enforce rules like authentication or logging across your whole app easily and consistently.
Every time a user visits any page, global middleware can check if they are logged in and redirect them if not.
Manual checks on every route are repetitive and error-prone.
Global middleware runs once for all routes automatically.
This keeps your code clean and your app secure.
Practice
Solution
Step 1: Understand middleware role
Middleware runs before route handlers to process requests or add features like logging.Step 2: Identify global middleware scope
Global middleware runs on every request, so it applies common logic everywhere.Final Answer:
To run code on every incoming request before reaching route handlers -> Option BQuick Check:
Global middleware = runs on every request [OK]
- Confusing middleware with route handlers
- Thinking middleware only runs on some routes
- Mixing middleware with error handling
Solution
Step 1: Recall global middleware syntax
In NestJS, the recommended way to apply middleware globally is using app.useGlobalMiddleware(MyMiddleware).Step 2: Compare options
consumer.apply(MyMiddleware).forRoutes('*') applies middleware to all routes but is not truly global middleware; app.useGlobalMiddleware applies middleware globally.Final Answer:
app.useGlobalMiddleware(MyMiddleware) -> Option AQuick Check:
Global middleware uses app.useGlobalMiddleware [OK]
- Using consumer.apply(...).forRoutes('*') for global middleware
- Trying to call non-existent app methods
- Confusing middleware registration with guards
export class LoggerMiddleware implements NestMiddleware {
use(req: Request, res: Response, next: Function) {
console.log(`Request to: ${req.url}`);
next();
}
}
// Applied globally with consumer.apply(LoggerMiddleware).forRoutes('*')Solution
Step 1: Analyze middleware code
The middleware logs the string 'Request to:' plus the request URL from req.url.Step 2: Understand global application
Since applied globally, this log happens on every request URL received by the app.Final Answer:
Logs the URL of every incoming request -> Option DQuick Check:
LoggerMiddleware logs req.url every request [OK]
- Assuming HTTP method is logged instead of URL
- Forgetting next() causes no further processing
- Thinking response status is logged
export class AuthMiddleware implements NestMiddleware {
use(req: Request, res: Response) {
if (!req.headers.authorization) {
res.status(401).send('Unauthorized');
}
}
}
// Applied with consumer.apply(AuthMiddleware).forRoutes('*')Solution
Step 1: Check middleware method signature
The use method lacks the next parameter and does not call next(), so request stops here.Step 2: Understand middleware flow
Without calling next(), the request will hang or not proceed to route handlers after middleware.Final Answer:
Missing call to next() to continue request processing -> Option AQuick Check:
Middleware must call next() to proceed [OK]
- Omitting next() call in middleware
- Misunderstanding middleware flow control
- Thinking forRoutes('*') is invalid
Solution
Step 1: Understand route filtering in middleware
NestJS allows filtering middleware by path and HTTP method using forRoutes with an object.Step 2: Apply middleware globally but only for POST
Using forRoutes({ path: '*', method: RequestMethod.POST }) applies middleware to all paths but only POST requests.Step 3: Evaluate other options
Use consumer.apply(LoggerMiddleware).forRoutes('*') and check req.method inside middleware applies middleware on all methods, not just POST. Apply middleware only on POST routes manually, no global option is manual, not global. Use app.useGlobalMiddleware(LoggerMiddleware) with method filter is invalid syntax.Final Answer:
Use consumer.apply(LoggerMiddleware).forRoutes({ path: '*', method: RequestMethod.POST }) -> Option CQuick Check:
forRoutes with method filter = selective global middleware [OK]
- Applying middleware globally without method filter
- Trying non-existent app.useGlobalMiddleware method
- Manually applying middleware on each POST route
Ready to prove it?
Pass the test and this pattern moves unknown
