0
0
NestJSframework~10 mins

Applying middleware to routes in NestJS - Step-by-Step Execution

Choose your learning style9 modes available
Concept Flow - Applying middleware to routes
Define Middleware Function
Create Middleware Class
Apply Middleware in Module
Specify Routes or Route Patterns
Incoming Request Matches Route?
NoSkip Middleware
Yes
Middleware Executes
Pass Control to Next Handler
Route Handler Executes
Middleware is defined, applied to specific routes, and runs on matching requests before the route handler.
Execution Sample
NestJS
import { Injectable, NestMiddleware, Module, NestModule, MiddlewareConsumer } from '@nestjs/common';

@Injectable()
export class LoggerMiddleware implements NestMiddleware {
  use(req: any, res: any, next: () => void) {
    console.log('Request logged');
    next();
  }
}

// In module
@Module({})
export class AppModule implements NestModule {
  configure(consumer: MiddlewareConsumer) {
    consumer.apply(LoggerMiddleware).forRoutes('cats');
  }
}
This code defines a LoggerMiddleware that logs requests and applies it only to the '/cats' route.
Execution Table
StepIncoming Request URLRoute MatchMiddleware ActionNext CalledRoute Handler Called
1/catsYesLogs 'Request logged'YesYes
2/dogsNoMiddleware skippedN/AYes
3/cats/123NoMiddleware skippedN/AYes
4/birdsNoMiddleware skippedN/AYes
5End of requestsN/AN/AN/AN/A
💡 Requests not matching 'cats' route skip middleware; matching requests run middleware then route handler.
Variable Tracker
VariableStartAfter 1After 2After 3After 4Final
req.url/start/cats/dogs/cats/123/birdsEnd
middlewareExecutedfalsetruefalsefalsefalseN/A
routeHandlerExecutedfalsetruetruetruetrueN/A
Key Moments - 2 Insights
Why does the middleware not run for the '/dogs' request?
Because the middleware is applied only to routes matching 'cats', so '/dogs' does not match and middleware is skipped as shown in execution_table row 2.
What happens if middleware does not call next()?
The request will hang and the route handler will not execute. In the example, next() is called every time middleware runs (rows 1 and 3), allowing the route handler to run.
Visual Quiz - 3 Questions
Test your understanding
Look at the execution table, what is the middlewareExecuted value after the third request?
Afalse
Btrue
CN/A
Dundefined
💡 Hint
Check the 'middlewareExecuted' row at 'After 3' column in variable_tracker.
At which step does the middleware get skipped because the route does not match?
AStep 1
BStep 3
CStep 2
DStep 4
💡 Hint
Look at the 'Route Match' and 'Middleware Action' columns in execution_table.
If we apply middleware to all routes, how would the middlewareExecuted values change?
AAll would be false
BAll would be true
COnly first and last true
DNo change
💡 Hint
Middleware runs on all routes if applied globally, so check variable_tracker for middlewareExecuted.
Concept Snapshot
Define middleware as a class with a use() method.
Apply middleware in a module using consumer.apply().forRoutes(route).
Middleware runs only on matching routes.
Middleware must call next() to continue.
Non-matching routes skip middleware.
Middleware runs before route handler.
Full Transcript
Middleware in NestJS is a function or class that runs before route handlers. You define middleware by creating a class with a use() method that takes request, response, and next. You apply middleware in a module using the configure method and MiddlewareConsumer, specifying which routes it applies to. When a request comes in, NestJS checks if the URL matches the middleware's routes. If yes, the middleware runs, does its work (like logging), then calls next() to pass control to the route handler. If no, middleware is skipped and the route handler runs directly. This process ensures middleware only affects intended routes and runs before the handler.