Bird
Raised Fist0
NestJSframework~20 mins

Middleware ordering in NestJS - Practice Problems & Coding Challenges

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!
❓ component_behavior
intermediate
2:00remaining
Order of Middleware Execution in NestJS
Given the following NestJS middleware setup, what will be the order of console logs when a request hits the '/test' route?
NestJS
import { Injectable, NestMiddleware } from '@nestjs/common';

@Injectable()
class FirstMiddleware implements NestMiddleware {
  use(req, res, next) {
    console.log('First');
    next();
  }
}

@Injectable()
class SecondMiddleware implements NestMiddleware {
  use(req, res, next) {
    console.log('Second');
    next();
  }
}

// In AppModule
export class AppModule {
  configure(consumer) {
    consumer
      .apply(FirstMiddleware, SecondMiddleware)
      .forRoutes('/test');
  }
}
AFirst
BSecond\nFirst
CSecond
DFirst\nSecond
Attempts:
2 left
💡 Hint
Middleware are executed in the order they are applied in the consumer.
❓ lifecycle
intermediate
2:00remaining
Middleware Execution with next() Skipped
What happens if a middleware in NestJS does NOT call next() in its use() method?
NestJS
import { Injectable, NestMiddleware } from '@nestjs/common';

@Injectable()
class BlockMiddleware implements NestMiddleware {
  use(req, res, next) {
    res.status(403).send('Blocked');
    // next() is NOT called
  }
}

// Applied as the only middleware on '/block' route
AAn error is thrown because next() is missing.
BThe request stops at BlockMiddleware and response 'Blocked' is sent; no further middleware or route handlers run.
CThe request continues to next middleware or route handler despite missing next().
DThe server crashes due to unhandled middleware.
Attempts:
2 left
💡 Hint
Calling next() passes control to the next middleware or handler.
🔧 Debug
advanced
2:00remaining
Unexpected Middleware Execution Order
You applied two middleware in this order: AuthMiddleware, LoggerMiddleware. But the logs show LoggerMiddleware runs before AuthMiddleware. What is the most likely cause?
NestJS
consumer
  .apply(AuthMiddleware, LoggerMiddleware)
  .forRoutes('*');
ALoggerMiddleware was globally applied before this consumer.apply call, so it runs first.
BMiddleware order in apply() is reversed internally by NestJS.
CMiddleware with longer names run later automatically.
DAuthMiddleware calls next() asynchronously, so LoggerMiddleware runs first.
Attempts:
2 left
💡 Hint
Global middleware run before route-specific middleware.
📝 Syntax
advanced
2:00remaining
Correct Middleware Application Syntax
Which option correctly applies two middleware to the '/api' route in NestJS?
Aconsumer.use(AuthMiddleware, LoggerMiddleware).forRoutes('/api');
Bconsumer.apply([AuthMiddleware, LoggerMiddleware]).forRoutes('/api');
Cconsumer.apply(AuthMiddleware, LoggerMiddleware).forRoutes('/api');
Dconsumer.apply(AuthMiddleware).apply(LoggerMiddleware).forRoutes('/api');
Attempts:
2 left
💡 Hint
apply() accepts middleware as separate arguments, not as an array.
❓ state_output
expert
3:00remaining
Middleware Modifying Request Object
Consider two middleware applied in order: AddUserMiddleware adds req.user = {id: 1}, then LogUserMiddleware logs req.user. What will LogUserMiddleware output?
NestJS
import { Injectable, NestMiddleware } from '@nestjs/common';

@Injectable()
class AddUserMiddleware implements NestMiddleware {
  use(req, res, next) {
    req.user = { id: 1 };
    next();
  }
}

@Injectable()
class LogUserMiddleware implements NestMiddleware {
  use(req, res, next) {
    console.log(req.user);
    next();
  }
}

// Applied as consumer.apply(AddUserMiddleware, LogUserMiddleware).forRoutes('*');
A{ id: 1 }
Bundefined
Cnull
DThrows ReferenceError
Attempts:
2 left
💡 Hint
Middleware run in order and share the same request object.

Practice

(1/5)
1. In NestJS, why is the order of middleware important when using the apply() method?
easy
A. Because middleware order controls the type of HTTP methods allowed.
B. Because middleware order changes the port number the server listens on.
C. Because middleware order determines the database connection settings.
D. Because middleware runs in the order they are applied, affecting request processing sequence.

Solution

  1. Step 1: Understand middleware execution flow

    Middleware functions run in the order they are applied to the request pipeline.
  2. Step 2: Recognize impact on request handling

    The order affects how requests are logged, authenticated, or modified before reaching the route handler.
  3. Final Answer:

    Because middleware runs in the order they are applied, affecting request processing sequence. -> Option D
  4. Quick Check:

    Middleware order = request handling sequence [OK]
Hint: Middleware order controls request flow sequence [OK]
Common Mistakes:
  • Thinking middleware order changes server port
  • Confusing middleware order with database settings
  • Assuming middleware order controls HTTP methods
2. Which of the following is the correct way to apply two middleware functions authMiddleware and loggerMiddleware in order using NestJS apply() method?
easy
A. apply([authMiddleware, loggerMiddleware]).forRoutes('*')
B. apply(loggerMiddleware, authMiddleware).forRoutes('*')
C. apply(authMiddleware, loggerMiddleware).forRoutes('*')
D. apply(loggerMiddleware).apply(authMiddleware).forRoutes('*')

Solution

  1. Step 1: Recall correct syntax for multiple middleware

    Use apply(middleware1, middleware2) to apply middleware in order.
  2. Step 2: Confirm order matches desired sequence

    To run authMiddleware before loggerMiddleware, list authMiddleware first.
  3. Final Answer:

    apply(authMiddleware, loggerMiddleware).forRoutes('*') -> Option C
  4. Quick Check:

    apply(mw1, mw2) = correct syntax [OK]
Hint: List middleware in apply() in desired run order [OK]
Common Mistakes:
  • Reversing middleware order in apply()
  • Using multiple apply() calls incorrectly
  • Passing middleware as an array inside apply()
3. Given the following middleware setup in NestJS:
apply(authMiddleware, loggerMiddleware).forRoutes('users')
What will be the order of middleware execution when a request hits the 'users' route?
medium
A. authMiddleware runs first, then loggerMiddleware
B. loggerMiddleware runs first, then authMiddleware
C. Both run simultaneously
D. Only authMiddleware runs

Solution

  1. Step 1: Identify middleware order in apply()

    Middleware listed first runs first; here, authMiddleware is first.
  2. Step 2: Confirm sequence on route match

    When a request matches 'users', authMiddleware runs before loggerMiddleware.
  3. Final Answer:

    authMiddleware runs first, then loggerMiddleware -> Option A
  4. Quick Check:

    apply order = execution order [OK]
Hint: First middleware in apply() runs first [OK]
Common Mistakes:
  • Assuming middleware run simultaneously
  • Thinking last middleware runs first
  • Ignoring route matching
4. You wrote this middleware setup in NestJS:
apply(loggerMiddleware, authMiddleware).forRoutes('profile')
But you want authMiddleware to run before loggerMiddleware. What is the fix?
medium
A. Use apply(authMiddleware).apply(loggerMiddleware).forRoutes('profile')
B. Swap the middleware order to apply(authMiddleware, loggerMiddleware).forRoutes('profile')
C. Change forRoutes to forRoutes('auth')
D. No fix needed; order does not matter

Solution

  1. Step 1: Identify current middleware order

    Currently, loggerMiddleware runs before authMiddleware.
  2. Step 2: Swap middleware order in apply()

    To run authMiddleware first, list it first in apply().
  3. Final Answer:

    Swap the middleware order to apply(authMiddleware, loggerMiddleware).forRoutes('profile') -> Option B
  4. Quick Check:

    Middleware order in apply() = execution order [OK]
Hint: Swap middleware order in apply() to fix sequence [OK]
Common Mistakes:
  • Changing route instead of middleware order
  • Using multiple apply() calls incorrectly
  • Assuming order does not affect execution
5. You want to log every request before authenticating it and then modify the request body only after authentication in NestJS. Which middleware order should you apply?
hard
A. apply(loggerMiddleware, authMiddleware, modifyBodyMiddleware).forRoutes('*')
B. apply(authMiddleware, loggerMiddleware, modifyBodyMiddleware).forRoutes('*')
C. apply(modifyBodyMiddleware, loggerMiddleware, authMiddleware).forRoutes('*')
D. apply(authMiddleware, modifyBodyMiddleware, loggerMiddleware).forRoutes('*')

Solution

  1. Step 1: Determine desired middleware sequence

    Requests should be logged first, then authenticated, then modified.
  2. Step 2: Arrange middleware in apply() accordingly

    List loggerMiddleware first, then authMiddleware, then modifyBodyMiddleware.
  3. Final Answer:

    apply(loggerMiddleware, authMiddleware, modifyBodyMiddleware).forRoutes('*') -> Option A
  4. Quick Check:

    Middleware order = log -> auth -> modify [OK]
Hint: Order middleware as log, auth, then modify [OK]
Common Mistakes:
  • Placing modifyBodyMiddleware before authMiddleware
  • Logging after authentication
  • Incorrect middleware sequence in apply()
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