Global middleware in NestJS is a function that runs before every route handler in the application. It can modify requests, responses, or perform actions like logging for all incoming requests.
Click to reveal answer
beginner
How do you apply middleware globally in a NestJS application?
You apply middleware globally by using the app.use() method inside the main.ts file, before the app starts listening. For example: app.use(yourMiddlewareFunction);
Click to reveal answer
intermediate
What is the difference between global middleware and route-specific middleware in NestJS?
Global middleware runs for every request to any route, while route-specific middleware runs only for the routes where it is applied. Global middleware is set in <code>main.ts</code>, route middleware is set in modules using <code>configure()</code> method of the module class implementing <code>NestModule</code>.
Click to reveal answer
beginner
Can global middleware in NestJS modify the request and response objects?
Yes, global middleware can modify both the request and response objects. This allows you to add properties, headers, or perform checks before the request reaches the route handler.
Click to reveal answer
beginner
Where in a NestJS project do you typically register global middleware?
Global middleware is typically registered in the main.ts file, right after creating the app instance and before calling app.listen().
Click to reveal answer
Where do you register global middleware in a NestJS app?
AIn the main.ts file using app.use()
BInside a controller method
CIn a service class
DIn the package.json file
✗ Incorrect
Global middleware is registered in main.ts using app.use() before the app starts listening.
What does global middleware affect in a NestJS app?
AOnly one specific route
BAll incoming requests to any route
COnly outgoing responses
DOnly static files
✗ Incorrect
Global middleware runs for every incoming request to any route.
Which of these is a valid way to apply global middleware in NestJS?
Aservice.use(yourMiddlewareFunction);
Bcontroller.use(yourMiddlewareFunction);
Cmodule.use(yourMiddlewareFunction);
Dapp.use(yourMiddlewareFunction);
✗ Incorrect
app.use() in main.ts is the correct way to apply global middleware.
Can global middleware modify the request object in NestJS?
ANo, it can only read the request
BNo, it only modifies the response
CYes, it can add or change properties
DNo, middleware cannot access request
✗ Incorrect
Global middleware can modify the request object before it reaches route handlers.
What is the main purpose of global middleware?
ATo run code before every route handler
BTo handle errors only
CTo define database models
DTo create UI components
✗ Incorrect
Global middleware runs code before every route handler to perform tasks like logging or authentication.
Explain how to set up global middleware in a NestJS application and what it can be used for.
Think about where the app starts and how middleware fits in the request flow.
You got /4 concepts.
Describe the difference between global middleware and route-specific middleware in NestJS.
Consider the scope of middleware application.
You got /4 concepts.
Practice
(1/5)
1. What is the main purpose of global middleware in a NestJS application?
easy
A. To define database models for the application
B. To run code on every incoming request before reaching route handlers
C. To create new routes dynamically
D. To handle errors after the response is sent
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 B
Quick Check:
Global middleware = runs on every request [OK]
Hint: Global middleware runs before routes on all requests [OK]
Common Mistakes:
Confusing middleware with route handlers
Thinking middleware only runs on some routes
Mixing middleware with error handling
2. Which of the following is the correct way to apply a middleware globally in NestJS?
easy
A. app.useGlobalMiddleware(MyMiddleware)
B. consumer.apply(MyMiddleware).forRoutes('users')
C. consumer.apply(MyMiddleware).forRoutes('*')
D. app.applyMiddlewareGlobally(MyMiddleware)
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 A
Quick Check:
Global middleware uses app.useGlobalMiddleware [OK]
Hint: Use app.useGlobalMiddleware to apply middleware globally [OK]
Common Mistakes:
Using consumer.apply(...).forRoutes('*') for global middleware
Trying to call non-existent app methods
Confusing middleware registration with guards
3. Given this middleware code, what will be logged for every request?
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('*')
medium
A. Logs the HTTP method only
B. Logs the response status code
C. Logs nothing because next() is missing
D. Logs the URL of every incoming request
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 D
Quick Check:
LoggerMiddleware logs req.url every request [OK]
Hint: Look for console.log inside middleware use() method [OK]
Common Mistakes:
Assuming HTTP method is logged instead of URL
Forgetting next() causes no further processing
Thinking response status is logged
4. Identify the error in this global middleware setup:
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('*')
medium
A. Missing call to next() to continue request processing
B. Middleware should not check headers
C. forRoutes('*') cannot be used for global middleware
D. res.status(401) is invalid syntax
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 A
Quick Check:
Middleware must call next() to proceed [OK]
Hint: Always call next() in middleware to continue [OK]
Common Mistakes:
Omitting next() call in middleware
Misunderstanding middleware flow control
Thinking forRoutes('*') is invalid
5. You want to apply a logging middleware globally but only for HTTP POST requests. Which approach correctly achieves this in NestJS?
hard
A. Use consumer.apply(LoggerMiddleware).forRoutes('*') and check req.method inside middleware
B. Apply middleware only on POST routes manually, no global option
C. Use consumer.apply(LoggerMiddleware).forRoutes({ path: '*', method: RequestMethod.POST })
D. Use app.useGlobalMiddleware(LoggerMiddleware) with method filter
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 C
Quick Check:
forRoutes with method filter = selective global middleware [OK]
Hint: Use forRoutes({ path: '*', method: RequestMethod.POST }) for selective global [OK]
Common Mistakes:
Applying middleware globally without method filter