Middleware & Filters

Preview — 3 of 10 questions

In the NestJS request lifecycle, where does a middleware function run?

javascript
import { Injectable, NestMiddleware } from '@nestjs/common';
import { Request, Response, NextFunction } from 'express';

@Injectable()
export class LoggerMiddleware implements NestMiddleware {
  use(req: Request, res: Response, next: NextFunction): void {
    console.log(`${req.method} ${req.originalUrl}`);
    next(); // hand control to the next middleware / route handler
  }
}
ABefore the route handler, with access to the request and response objects
BAfter the route handler returns its response
COnly inside the database layer, wrapping Prisma queries
DExclusively during application bootstrap, never per-request

Which method must a class implement to satisfy the NestMiddleware interface?

javascript
import { Injectable, NestMiddleware } from '@nestjs/common';
import { Request, Response, NextFunction } from 'express';

@Injectable()
export class AuthHeaderMiddleware implements NestMiddleware {
  use(req: Request, _res: Response, next: NextFunction): void {
    req.headers['x-traced'] = 'true';
    next();
  }
}
Ahandle(req, res)
Bintercept(context, next)
Cuse(req, res, next)
Dtransform(value, metadata)

How is class-based middleware registered in NestJS?

javascript
import { Module, NestModule, MiddlewareConsumer } from '@nestjs/common';
import { LoggerMiddleware } from './logger.middleware';

@Module({})
export class AppModule implements NestModule {
  configure(consumer: MiddlewareConsumer): void {
    consumer.apply(LoggerMiddleware).forRoutes('*');
  }
}
ABy adding it to the providers array of the module
BBy passing it to @Module({ middleware: [...] })
CBy decorating the controller with @Middleware()
DBy implementing NestModule and applying it inside the configure(consumer) method

Sign up free to play

Answer all 10 questions (7 more), see explanations for every answer, and track your score.