Bird
Raised Fist0
NestJSframework~20 mins

Why middleware processes requests before handlers in NestJS - Challenge Your Understanding

Choose your learning style10 modes available
Challenge - 5 Problems
🎖️
Middleware Mastery
Get all challenges correct to earn this badge!
Test your skills under time pressure!
🧠 Conceptual
intermediate
2:00remaining
Why does middleware run before route handlers in NestJS?
In NestJS, middleware functions run before route handlers. Why is this order important?
AMiddleware runs first to modify or check the request before the handler uses it.
BMiddleware runs first to send the response directly without calling handlers.
CMiddleware runs after handlers to clean up resources.
DMiddleware runs randomly before or after handlers depending on configuration.
Attempts:
2 left
💡 Hint
Think about what middleware can do with the request before the main code runs.
❓ component_behavior
intermediate
2:00remaining
What happens if middleware modifies the request object?
Consider this NestJS middleware that adds a property to the request object. What will the route handler see?
NestJS
export function addUserId(req, res, next) {
  req.userId = 42;
  next();
}

// Route handler
@Get('profile')
getProfile(@Req() req) {
  return req.userId;
}
AThe handler receives req.userId as 42.
BThe handler throws an error because userId is not defined.
CThe handler receives req.userId as undefined.
DThe middleware blocks the request and handler is not called.
Attempts:
2 left
💡 Hint
Middleware can add properties to the request object that handlers can use.
❓ lifecycle
advanced
2:00remaining
Order of middleware and handlers in NestJS request lifecycle
Which sequence correctly shows the order of execution when a request comes in a NestJS app with middleware and a route handler?
A1,2,4,3
B2,1,4,3
C1,4,2,3
D4,1,2,3
Attempts:
2 left
💡 Hint
Middleware runs first and can modify request or response before handler runs.
📝 Syntax
advanced
2:00remaining
Identify the correct middleware usage in NestJS
Which option correctly applies middleware to a route in NestJS?
Aapp.route('/route').use(middlewareFunction);
Bapp.use('/route', middlewareFunction);
Capp.middleware('/route', middlewareFunction);
Dapp.applyMiddleware(middlewareFunction).forRoute('/route');
Attempts:
2 left
💡 Hint
Check the official NestJS way to apply middleware in main.ts or module.
🔧 Debug
expert
3:00remaining
Why does this middleware not run before the handler?
Given this NestJS setup, why does the middleware not run before the route handler?
NestJS
export class AppModule implements NestModule {
  configure(consumer: MiddlewareConsumer) {
    consumer
      .apply(loggingMiddleware)
      .forRoutes('users');
  }
}

@Get('/users')
getUsers() {
  return ['Alice', 'Bob'];
}
AMiddleware runs after handlers by default in NestJS.
BMiddleware must be applied globally in main.ts to run before handlers.
CMiddleware is not registered because configure method is missing @Injectable decorator.
DMiddleware path 'users' does not match route '/users' because it lacks a leading slash.
Attempts:
2 left
💡 Hint
Check how paths are matched in middleware configuration.

Practice

(1/5)
1. Why does middleware in NestJS process requests before the route handlers?
easy
A. To delay the request processing intentionally
B. To send the response after the handler finishes
C. To replace the route handler completely
D. To prepare or check the request before the handler uses it

Solution

  1. Step 1: Understand middleware role

    Middleware runs before handlers to prepare or validate requests, like checking authentication or adding data.
  2. Step 2: Compare with other options

    Middleware does not send responses after handlers or replace handlers; it only processes requests early.
  3. Final Answer:

    To prepare or check the request before the handler uses it -> Option D
  4. Quick Check:

    Middleware prepares requests = D [OK]
Hint: Middleware runs first to prep requests before handlers [OK]
Common Mistakes:
  • Thinking middleware runs after handlers
  • Believing middleware replaces handlers
  • Assuming middleware delays requests
2. Which of the following is the correct way to continue request processing inside a NestJS middleware?
easy
A. Return the response directly
B. Call next() function
C. Throw an error to stop processing
D. Call the route handler manually

Solution

  1. Step 1: Identify middleware flow control

    In NestJS, calling next() passes control to the next middleware or handler.
  2. Step 2: Eliminate incorrect options

    Returning response or throwing error stops flow; calling handler manually is not standard.
  3. Final Answer:

    Call next() function -> Option B
  4. Quick Check:

    Use next() to continue middleware chain [OK]
Hint: Always call next() to move forward in middleware [OK]
Common Mistakes:
  • Forgetting to call next(), causing request hang
  • Trying to call handler directly inside middleware
  • Returning response without next() when not ending request
3. Given this NestJS middleware code snippet, what will be logged first when a request arrives?
export function logger(req, res, next) {
  console.log('Middleware start');
  next();
  console.log('Middleware end');
}
medium
A. "Middleware start" then "Middleware end"
B. "Middleware end" then "Middleware start"
C. Only "Middleware start" is logged
D. No logs appear because next() stops execution

Solution

  1. Step 1: Analyze middleware execution order

    Console logs before and after next() run synchronously; first logs "Middleware start".
  2. Step 2: Understand next() behavior

    Calling next() passes control but does not pause middleware; "Middleware end" logs after next() call.
  3. Final Answer:

    "Middleware start" then "Middleware end" -> Option A
  4. Quick Check:

    Logs before and after next() run in order [OK]
Hint: Logs before and after next() run in sequence [OK]
Common Mistakes:
  • Thinking next() pauses middleware execution
  • Assuming logs after next() run later
  • Believing next() stops middleware code
4. 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();
}
medium
A. Middleware must not send responses directly
B. Authorization header check is incorrect syntax
C. next() is called even after sending response, causing errors
D. next() should be called before checking headers

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]
Hint: 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
5. You want to add a middleware that adds a timestamp to every request before handlers run. Which approach correctly ensures the timestamp is available in the handler?
hard
A. Add req.timestamp = Date.now() in middleware, then call next()
B. Call next() first, then add req.timestamp after
C. Add timestamp in the handler, not middleware
D. Send timestamp in response headers from middleware

Solution

  1. Step 1: Understand middleware purpose

    Middleware runs before handlers, so adding data to req here makes it available later.
  2. Step 2: Correct order of operations

    Assign req.timestamp before calling next() so handlers see the value.
  3. Final Answer:

    Add req.timestamp = Date.now() in middleware, then call next() -> Option A
  4. Quick Check:

    Add data before next() to share with handlers [OK]
Hint: Set request data before next() to share with handlers [OK]
Common Mistakes:
  • Adding data after next(), so handlers miss it
  • Trying to add data in handlers instead of middleware
  • Sending data only in response headers
Recommended

Ready to prove it?

Pass the test and this pattern moves unknown strong while earning +1 Grip toward your certificate.

10 questions~5 mineasy hard