Which of the following is the correct way to apply a middleware globally in NestJS?
easy📝 Syntax Q12 of 15
NestJS - Middleware
Which of the following is the correct way to apply a middleware globally in NestJS?
Aapp.useGlobalMiddleware(MyMiddleware)
Bconsumer.apply(MyMiddleware).forRoutes('users')
Cconsumer.apply(MyMiddleware).forRoutes('*')
Dapp.applyMiddlewareGlobally(MyMiddleware)
Step-by-Step Solution
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]
Quick Trick: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
Master "Middleware" in NestJS
9 interactive learning modes - each teaches the same concept differently