Bird
0
0

How can you create middleware that only runs for routes under '/api' but excludes '/api/auth' in NestJS?

hard📝 Application Q9 of 15
NestJS - Middleware
How can you create middleware that only runs for routes under '/api' but excludes '/api/auth' in NestJS?
AUse consumer.apply(Middleware).exclude('/api/auth').forRoutes('/api')
BApply middleware globally and skip '/api/auth' inside middleware
CUse multiple middleware instances for '/api' and '/api/auth'
DNestJS middleware cannot exclude specific routes
Step-by-Step Solution
Solution:
  1. Step 1: Recall exclude() method usage

    NestJS allows excluding routes from middleware using exclude() before forRoutes().
  2. Step 2: Verify correct chaining

    Use consumer.apply(Middleware).exclude('/api/auth').forRoutes('/api') correctly chains exclude('/api/auth') before applying middleware to '/api'.
  3. Final Answer:

    Use consumer.apply(Middleware).exclude('/api/auth').forRoutes('/api') -> Option A
  4. Quick Check:

    Use exclude() to skip routes in middleware [OK]
Quick Trick: Use exclude() before forRoutes() to skip routes [OK]
Common Mistakes:
  • Trying to exclude routes inside middleware logic
  • Applying middleware globally without exclusions
  • Assuming exclude() is not supported

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More NestJS Quizzes