Bird
0
0

You wrote this NestJS middleware but requests never reach the handler. What is the problem?

medium📝 Debug Q14 of 15
NestJS - Middleware
You wrote this NestJS middleware but requests never reach the handler. What is the problem?
export function authMiddleware(req, res, next) {
  if (!req.headers.authorization) {
    res.status(401).send('Unauthorized');
    return;
  }
  next();
}
AMiddleware must not send responses directly
BAuthorization header check is incorrect syntax
Cnext() is called even after sending response, causing errors
Dnext() should be called before checking headers
Step-by-Step Solution
Solution:
  1. Step 1: Review middleware flow control

    If authorization header is missing, response is sent but next() is still called, causing request to continue incorrectly.
  2. Step 2: Fix flow by returning early

    To stop processing after sending response, return immediately without calling next().
  3. Final Answer:

    next() is called even after sending response, causing errors -> Option C
  4. Quick Check:

    Don't call next() after sending response [OK]
Quick Trick: Return after sending response to avoid calling next() [OK]
Common Mistakes:
  • Calling next() after response ends
  • Not returning early to stop middleware
  • Misunderstanding middleware flow control

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More NestJS Quizzes