Middleware lets you run code before your app handles a request. It helps you check or change requests easily.
Creating middleware in NestJS
import { Injectable, NestMiddleware } from '@nestjs/common'; import { Request, Response, NextFunction } from 'express'; @Injectable() export class YourMiddleware implements NestMiddleware { use(req: Request, res: Response, next: NextFunction) { // Your code here next(); } }
Middleware is a class with a use method that runs on each request.
Always call next() to continue to the next step in request handling.
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) { console.log(`Request to: ${req.url}`); next(); } }
import { Injectable, NestMiddleware } from '@nestjs/common'; import { Request, Response, NextFunction } from 'express'; @Injectable() export class AuthMiddleware implements NestMiddleware { use(req: Request, res: Response, next: NextFunction) { if (!req.headers.authorization) { return res.status(401).send('Unauthorized'); } next(); } }
This example creates a middleware that logs the HTTP method and URL of every request. It then applies this middleware to all routes in the app.
import { Injectable, NestMiddleware, MiddlewareConsumer, Module, NestModule } from '@nestjs/common'; import { Request, Response, NextFunction } from 'express'; @Injectable() export class SimpleLoggerMiddleware implements NestMiddleware { use(req: Request, res: Response, next: NextFunction) { console.log(`Method: ${req.method}, URL: ${req.url}`); next(); } } @Module({}) export class AppModule implements NestModule { configure(consumer: MiddlewareConsumer) { consumer.apply(SimpleLoggerMiddleware).forRoutes('*'); } }
Middleware runs in the order you apply it, so order matters.
Use forRoutes to apply middleware only to specific paths or controllers.
Middleware can modify requests and responses before they reach your route handlers.
Middleware runs code before your app handles requests.
Create middleware by making a class with a use method.
Apply middleware to routes using MiddlewareConsumer.
Practice
Solution
Step 1: Understand middleware role
Middleware is code that runs before the main route handler processes a request.Step 2: Compare options
Only To run code before the request reaches the route handler describes this behavior correctly; others describe unrelated tasks.Final Answer:
To run code before the request reaches the route handler -> Option CQuick Check:
Middleware runs before routes [OK]
- Confusing middleware with controllers
- Thinking middleware handles UI rendering
- Assuming middleware manages database models
Solution
Step 1: Recall NestJS middleware pattern
Middleware must be a class with a method namedusethat takesreq, res, next.Step 2: Check options
Only class MyMiddleware { use(req, res, next) { next(); } } defines a class with ausemethod correctly. class MyMiddleware { handle(req, res, next) { next(); } } useshandle, which is invalid. Options C and D define functions, not classes.Final Answer:
class MyMiddleware { use(req, res, next) { next(); } } -> Option DQuick Check:
Middleware class must have use() method [OK]
- Using method name other than use
- Defining middleware as a function instead of class
- Forgetting to call next() inside use
class LoggerMiddleware {
use(req, res, next) {
console.log('Request URL:', req.url);
next();
}
}Solution
Step 1: Analyze middleware behavior
The middleware logs the request URL fromreq.urland then callsnext()to continue.Step 2: Predict output
When a request to '/some-path' arrives, it logs 'Request URL: /some-path'. No errors occur becauseuseis defined andnext()is called.Final Answer:
Request URL: /some-path -> Option AQuick Check:
Middleware logs req.url correctly [OK]
- Forgetting to call next() causing no further processing
- Assuming req.url is undefined
- Confusing method name use with handle
class LoggerMiddleware {
use(req, res, next) {
console.log('Request received');
}
}
export class AppModule implements NestModule {
configure(consumer: MiddlewareConsumer) {
consumer.apply(LoggerMiddleware).forRoutes('users');
}
}Solution
Step 1: Check middleware code
The registration uses MiddlewareConsumer correctly, but examine the LoggerMiddleware class.Step 2: Identify the error
Theusemethod does not callnext(), causing the request to hang without reaching the route handler.Final Answer:
Missing call to next() inside LoggerMiddleware -> Option AQuick Check:
Middleware must call next() to continue [OK]
- Forgetting next() call causing request hang
- Thinking configure must return a value
- Confusing import sources for MiddlewareConsumer
Solution
Step 1: Understand method-specific middleware application
In NestJS, you can specify route and HTTP method using an object withpathandmethodinforRoutes.Step 2: Evaluate options
Use consumer.apply(MyMiddleware).forRoutes({ path: '/login', method: RequestMethod.POST }) correctly uses{ path: '/login', method: RequestMethod.POST }. Use consumer.apply(MyMiddleware).forRoutes('/login') and check method inside middleware applies middleware to all methods on '/login', requiring manual filtering. Apply middleware globally and filter POST requests inside middleware applies globally, which is less efficient. NestJS does not support method-specific middleware is false.Final Answer:
Use consumer.apply(MyMiddleware).forRoutes({ path: '/login', method: RequestMethod.POST }) -> Option BQuick Check:
Use forRoutes with path and method object [OK]
- Applying middleware to all methods unintentionally
- Not importing RequestMethod enum
- Assuming method-specific middleware is unsupported
Ready to prove it?
Pass the test and this pattern moves unknown
