Middleware & Filters — Series 2

Preview — 3 of 10 questions

What happens to a request that passes through this middleware?

javascript
@Injectable()
export class LoggerMiddleware implements NestMiddleware {
  use(req: Request, res: Response, next: NextFunction) {
    console.log(`${req.method} ${req.originalUrl}`);
    // next() is missing
  }
}
AIt hangs — nothing passes control to the next middleware, the guards or the handler, so no response is ever sent and the client eventually times out
BIt proceeds normally; next() is optional when the middleware sends no response
CNest detects the missing call and invokes next() automatically
DIt fails immediately with a 500

What does this configuration do?

javascript
@Module({ /* ... */ })
export class AppModule implements NestModule {
  configure(consumer: MiddlewareConsumer) {
    consumer.apply(LoggerMiddleware).forRoutes('*');
  }
}
AIt applies the middleware only to routes declared directly in AppModule
BIt applies it to GET routes only, since * is a read-only wildcard
CIt applies the middleware to every route in the application, which is what the module-level configure() hook exists for
DIt replaces every other middleware previously registered

Why can a third-party Express middleware be dropped in like this?

javascript
import helmet from 'helmet';

const app = await NestFactory.create(AppModule);
app.use(helmet());
ABecause Nest recompiles the function into a NestMiddleware class at runtime
BBecause helmet ships a dedicated Nest adapter
CBecause app.use() accepts only functions written specifically for Nest
DBecause the default platform is Express, and app.use() forwards to the underlying instance — so any (req, res, next) middleware works unchanged

Sign up free to play

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