0
0
NestJSframework~20 mins

Applying middleware to routes in NestJS - Practice Problems & Coding Challenges

Choose your learning style9 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.