All quizzesMedium
Custom Middleware
Preview — 3 of 10 questions
You want a lightweight middleware with no dependencies to inject. Which form is most appropriate?
javascript
import { Request, Response, NextFunction } from 'express';
export function correlationId(req: Request, _res: Response, next: NextFunction): void {
req.headers['x-correlation-id'] ??= crypto.randomUUID();
next();
}
// in module
consumer.apply(correlationId).forRoutes('*');AA plain function (req, res, next) => { ... } passed to consumer.apply()
BAn interceptor returned from @Module()
CA guard implementing canActivate
DA class implementing NestMiddleware registered in providers
What does consumer.apply(MiddlewareA, MiddlewareB).forRoutes('cats') do?
javascript
consumer
.apply(MiddlewareA, MiddlewareB)
.forRoutes('cats'); // order: A -> B -> handlerAOnly MiddlewareA runs; MiddlewareB is ignored
BBoth run on cats routes in the order they are listed: A then B
CThey run in reverse order: B then A
DThey run in parallel with no ordering guarantee
How do you apply a middleware to all controller routes except cats/health?
javascript
import { RequestMethod } from '@nestjs/common';
consumer
.apply(LoggerMiddleware)
.exclude({ path: 'cats/health', method: RequestMethod.GET })
.forRoutes(CatsController);Aconsumer.apply(M).forRoutes('cats').not('cats/health')
Bconsumer.apply(M).forRoutes('cats/*').skip('cats/health')
CExclusion is impossible; you must list every included route
Dconsumer.apply(M).exclude('cats/health').forRoutes(CatsController)
Sign up free to play
Answer all 10 questions (7 more), see explanations for every answer, and track your score.