0
0
NestJSframework~5 mins

Why middleware processes requests before handlers in NestJS

Choose your learning style9 modes available
Introduction

Middleware runs before request handlers to prepare or check the request. It can change the request or stop it early if needed.

Check if a user is logged in before allowing access to a page.
Log details about every request for monitoring.
Add extra information to requests, like user data.
Block bad requests before they reach the main code.
Modify request data to fit what handlers expect.
Syntax
NestJS
import { Injectable, NestMiddleware } from '@nestjs/common';
import { Request, Response, NextFunction } from 'express';

@Injectable()
export class ExampleMiddleware implements NestMiddleware {
  use(req: Request, res: Response, next: NextFunction) {
    // code to run before handler
    next(); // call next to continue
  }
}

The use method runs before the request handler.

Calling next() passes control to the next middleware or handler.

Examples
Logs a message before the handler runs.
NestJS
use(req, res, next) {
  console.log('Request received');
  next();
}
Stops the request if no authorization header is found.
NestJS
use(req, res, next) {
  if (!req.headers['authorization']) {
    return res.status(401).send('Unauthorized');
  }
  next();
}
Sample Program

This example shows a middleware logging every request URL before the handler sends a response.

NestJS
import { Injectable, NestMiddleware, Module, Controller, Get, MiddlewareConsumer } from '@nestjs/common';
import { Request, Response, NextFunction } from 'express';

@Injectable()
class LoggerMiddleware implements NestMiddleware {
  use(req: Request, res: Response, next: NextFunction) {
    console.log(`Request to: ${req.url}`);
    next();
  }
}

@Controller()
class AppController {
  @Get()
  getRoot() {
    return 'Hello from handler!';
  }
}

@Module({
  controllers: [AppController],
  providers: [LoggerMiddleware],
})
class AppModule {
  configure(consumer: MiddlewareConsumer) {
    consumer.apply(LoggerMiddleware).forRoutes('*');
  }
}
OutputSuccess
Important Notes

Middleware runs in the order you add them.

If middleware does not call next(), the request stops there.

Middleware can modify request and response objects before handlers use them.

Summary

Middleware runs before handlers to prepare or check requests.

It can stop requests early or add info for handlers.

Always call next() to continue the request flow.