Bird
Raised Fist0
NestJSframework~20 mins

Applying middleware to routes 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
Middleware effect on route response
Given this NestJS middleware that adds a header, what will be the response headers when accessing the /hello route?
NestJS
import { Injectable, NestMiddleware } from '@nestjs/common';
import { Request, Response, NextFunction } from 'express';

@Injectable()
export class HeaderMiddleware implements NestMiddleware {
  use(req: Request, res: Response, next: NextFunction) {
    res.setHeader('X-Custom-Header', 'NestJS');
    next();
  }
}

// In AppModule
import { Module, MiddlewareConsumer, RequestMethod } from '@nestjs/common';
import { HeaderMiddleware } from './header.middleware';
import { HelloController } from './hello.controller';

@Module({
  controllers: [HelloController],
})
export class AppModule {
  configure(consumer: MiddlewareConsumer) {
    consumer
      .apply(HeaderMiddleware)
      .forRoutes({ path: 'hello', method: RequestMethod.GET });
  }
}

// HelloController
import { Controller, Get } from '@nestjs/common';

@Controller('hello')
export class HelloController {
  @Get()
  getHello() {
    return 'Hello World';
  }
}
AThe middleware will cause a runtime error and no response is sent.
BThe response will not include any custom headers.
CThe response will include the header 'X-Custom-Header' but with an empty value.
DThe response will include the header 'X-Custom-Header' with value 'NestJS'.
Attempts:
2 left
💡 Hint
Middleware runs before the route handler and can modify the response.
📝 Syntax
intermediate
2:00remaining
Correct middleware application syntax
Which option correctly applies a middleware to all POST routes in NestJS?
NestJS
import { MiddlewareConsumer, Module, RequestMethod } from '@nestjs/common';
import { LoggerMiddleware } from './logger.middleware';

@Module({})
export class AppModule {
  configure(consumer: MiddlewareConsumer) {
    // Apply middleware here
  }
}
Aconsumer.apply(LoggerMiddleware).forRoutes({ path: '*', method: RequestMethod.POST });
Bconsumer.apply(LoggerMiddleware).forRoutes({ path: '*', method: 'POST' });
Cconsumer.apply(LoggerMiddleware).forRoutes({ path: '*', method: RequestMethod.GET });
Dconsumer.apply(LoggerMiddleware).forRoutes('*', RequestMethod.POST);
Attempts:
2 left
💡 Hint
Use RequestMethod enum for HTTP methods.
🔧 Debug
advanced
2:00remaining
Middleware not running on expected route
Why does this middleware not run when accessing /api/users even though it is applied to /api/*?
NestJS
consumer.apply(AuthMiddleware).forRoutes('api/*');
AThe middleware must be applied in the controller, not in the module.
BThe forRoutes method does not support wildcard strings like 'api/*'.
CThe middleware only runs on POST requests by default.
DThe middleware is missing the @Injectable decorator.
Attempts:
2 left
💡 Hint
Check how forRoutes accepts paths.
❓ state_output
advanced
2:00remaining
Order of middleware execution
Given two middlewares applied in this order, what will be the console output when accessing /test?
NestJS
consumer
  .apply(FirstMiddleware, SecondMiddleware)
  .forRoutes('test');

// FirstMiddleware logs 'First start' before next() and 'First end' after next()
// SecondMiddleware logs 'Second start' before next() and 'Second end' after next()
A
Second start
First start
First end
Second end
B
First start
Second start
First end
Second end
C
First start
Second start
Second end
First end
D
Second start
First start
Second end
First end
Attempts:
2 left
💡 Hint
Middleware calls next() to pass control to the next middleware.
🧠 Conceptual
expert
3:00remaining
Middleware scope and lifecycle
Which statement about NestJS middleware is true?
AMiddleware can modify the request and response objects before reaching route handlers.
BMiddleware is instantiated per request and can hold request-specific state.
CMiddleware can only be applied globally, not to specific routes.
DMiddleware is instantiated once per application and shared across all requests.
Attempts:
2 left
💡 Hint
Think about what middleware does in the request lifecycle.

Practice

(1/5)
1. What is the main purpose of applying middleware to routes in a NestJS application?
easy
A. To run code before the route handler processes the request
B. To directly send responses without reaching the route handler
C. To replace the route handler with a new function
D. To automatically generate API documentation

Solution

  1. Step 1: Understand middleware role

    Middleware runs before the route handler to process or modify requests.
  2. Step 2: Identify middleware effect on routes

    It does not replace handlers or generate docs but can log or check requests first.
  3. Final Answer:

    To run code before the route handler processes the request -> Option A
  4. Quick Check:

    Middleware runs before route handlers [OK]
Hint: Middleware always runs before route handlers [OK]
Common Mistakes:
  • Thinking middleware replaces route handlers
  • Confusing middleware with response sending
  • Assuming middleware auto-generates docs
2. Which of the following is the correct syntax to apply a middleware named LoggerMiddleware to all routes in a NestJS module?
easy
A. consumer.use(LoggerMiddleware).forRoutes('/');
B. consumer.apply(LoggerMiddleware).forRoutes('/');
C. consumer.apply(LoggerMiddleware).forRoutes('*');
D. consumer.apply(LoggerMiddleware).toRoutes('*');

Solution

  1. Step 1: Recall NestJS middleware syntax

    The correct method to apply middleware is consumer.apply(...).forRoutes(...).
  2. Step 2: Identify correct route pattern for all routes

    Using '/' applies middleware to all routes; '*' is invalid.
  3. Final Answer:

    consumer.apply(LoggerMiddleware).forRoutes('/'); -> Option B
  4. Quick Check:

    Use apply + forRoutes('/') for all routes [OK]
Hint: Use apply() with forRoutes('/') to cover all routes [OK]
Common Mistakes:
  • Using use() instead of apply()
  • Using toRoutes() which is invalid
  • Using '*' instead of '/' for all routes
3. Given this middleware application code in a NestJS module:
consumer.apply(AuthMiddleware).forRoutes('users');

Which routes will have the AuthMiddleware applied?
medium
A. All routes including '/users' and '/users/:id'
B. Only routes with path exactly '/users'
C. All routes in the application
D. No routes, because the path is invalid

Solution

  1. Step 1: Understand forRoutes string behavior

    Passing 'users' applies middleware to all routes starting with '/users', including parameters.
  2. Step 2: Confirm middleware coverage

    This includes '/users', '/users/123', '/users/profile', etc., not the entire app.
  3. Final Answer:

    All routes including '/users' and '/users/:id' -> Option A
  4. Quick Check:

    forRoutes('users') covers prefix routes [OK]
Hint: forRoutes('path') applies middleware to that path and subpaths [OK]
Common Mistakes:
  • Thinking only exact path matches get middleware
  • Assuming middleware applies globally without '*'
  • Believing invalid path disables middleware
4. Examine this NestJS middleware setup:
export class AppModule implements NestModule {
  configure(consumer: MiddlewareConsumer) {
    consumer.apply(AuthMiddleware).forRoutes();
  }
}

What is the issue with this code?
medium
A. Middleware class must be decorated with @Injectable
B. Middleware is applied globally without specifying routes
C. Missing route argument in forRoutes causes a runtime error
D. MiddlewareConsumer is not imported correctly

Solution

  1. Step 1: Check forRoutes usage

    The method forRoutes requires at least one argument specifying routes; empty call is invalid.
  2. Step 2: Identify error type

    Calling forRoutes() without arguments causes a runtime error because no routes are defined.
  3. Final Answer:

    Missing route argument in forRoutes causes a runtime error -> Option C
  4. Quick Check:

    forRoutes() needs routes argument [OK]
Hint: Always provide routes to forRoutes() [OK]
Common Mistakes:
  • Leaving forRoutes empty
  • Assuming middleware applies globally without routes
  • Ignoring missing @Injectable on middleware
5. You want to apply LoggerMiddleware only to POST requests on the /orders route in NestJS. Which approach correctly applies middleware only to POST /orders requests?
hard
A. Apply middleware globally and skip non-POST requests inside middleware
B. Use consumer.apply(LoggerMiddleware).forRoutes('orders'); and check method inside middleware
C. Use consumer.apply(LoggerMiddleware).forRoutes('orders'); without method filtering
D. Use consumer.apply(LoggerMiddleware).forRoutes({ path: 'orders', method: RequestMethod.POST });

Solution

  1. Step 1: Understand method filtering in middleware

    NestJS allows specifying method with an object: { path, method } in forRoutes.
  2. Step 2: Identify correct syntax for POST-only middleware

    Using consumer.apply(...).forRoutes({ path: 'orders', method: RequestMethod.POST }) applies middleware only to POST /orders.
  3. Final Answer:

    Use consumer.apply(LoggerMiddleware).forRoutes({ path: 'orders', method: RequestMethod.POST }); -> Option D
  4. Quick Check:

    Use object with path and method in forRoutes for method filtering [OK]
Hint: Use forRoutes({path, method}) to target HTTP methods [OK]
Common Mistakes:
  • Applying middleware to all methods without filtering
  • Checking method inside middleware instead of in forRoutes
  • Applying middleware globally and filtering inside middleware
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