Bird
0
0

You want to apply a logging middleware globally but only for HTTP POST requests. Which approach correctly achieves this in NestJS?

hard📝 Application Q15 of 15
NestJS - Middleware
You want to apply a logging middleware globally but only for HTTP POST requests. Which approach correctly achieves this in NestJS?
AUse consumer.apply(LoggerMiddleware).forRoutes('*') and check req.method inside middleware
BApply middleware only on POST routes manually, no global option
CUse consumer.apply(LoggerMiddleware).forRoutes({ path: '*', method: RequestMethod.POST })
DUse app.useGlobalMiddleware(LoggerMiddleware) with method filter
Step-by-Step Solution
Solution:
  1. Step 1: Understand route filtering in middleware

    NestJS allows filtering middleware by path and HTTP method using forRoutes with an object.
  2. Step 2: Apply middleware globally but only for POST

    Using forRoutes({ path: '*', method: RequestMethod.POST }) applies middleware to all paths but only POST requests.
  3. 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.
  4. Final Answer:

    Use consumer.apply(LoggerMiddleware).forRoutes({ path: '*', method: RequestMethod.POST }) -> Option C
  5. Quick Check:

    forRoutes with method filter = selective global middleware [OK]
Quick Trick: Use forRoutes({ path: '*', method: RequestMethod.POST }) for selective global [OK]
Common Mistakes:
  • Applying middleware globally without method filter
  • Trying non-existent app.useGlobalMiddleware method
  • Manually applying middleware on each POST route

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More NestJS Quizzes