Bird
0
0

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:
  1. Step 1: Recall global middleware syntax

    In NestJS, the recommended way to apply middleware globally is using app.useGlobalMiddleware(MyMiddleware).
  2. Step 2: Compare options

    consumer.apply(MyMiddleware).forRoutes('*') applies middleware to all routes but is not truly global middleware; app.useGlobalMiddleware applies middleware globally.
  3. Final Answer:

    app.useGlobalMiddleware(MyMiddleware) -> Option A
  4. 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

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More NestJS Quizzes