Bird
0
0

You want to apply a middleware only to POST requests on the '/login' route. How can you achieve this in NestJS?

hard📝 Application Q15 of 15
NestJS - Middleware
You want to apply a middleware only to POST requests on the '/login' route. How can you achieve this in NestJS?
AUse consumer.apply(MyMiddleware).forRoutes('/login') and check method inside middleware
BUse consumer.apply(MyMiddleware).forRoutes({ path: '/login', method: RequestMethod.POST })
CApply middleware globally and filter POST requests inside middleware
DNestJS does not support method-specific middleware
Step-by-Step Solution
Solution:
  1. Step 1: Understand method-specific middleware application

    In NestJS, you can specify route and HTTP method using an object with path and method in forRoutes.
  2. Step 2: Evaluate options

    Use consumer.apply(MyMiddleware).forRoutes({ path: '/login', method: RequestMethod.POST }) correctly uses { path: '/login', method: RequestMethod.POST }. Use consumer.apply(MyMiddleware).forRoutes('/login') and check method inside middleware applies middleware to all methods on '/login', requiring manual filtering. Apply middleware globally and filter POST requests inside middleware applies globally, which is less efficient. NestJS does not support method-specific middleware is false.
  3. Final Answer:

    Use consumer.apply(MyMiddleware).forRoutes({ path: '/login', method: RequestMethod.POST }) -> Option B
  4. Quick Check:

    Use forRoutes with path and method object [OK]
Quick Trick: Use forRoutes with path and method object for specific HTTP verbs [OK]
Common Mistakes:
  • Applying middleware to all methods unintentionally
  • Not importing RequestMethod enum
  • Assuming method-specific middleware is unsupported

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More NestJS Quizzes