0
0
NestJSframework~5 mins

Functional middleware in NestJS

Choose your learning style9 modes available
Introduction

Functional middleware lets you run code before your NestJS route handlers. It helps you add features like logging or checking user access simply.

You want to log every request to your server.
You need to check if a user is logged in before accessing certain pages.
You want to modify request data before it reaches your route.
You want to add headers or cookies to responses.
You want to block requests from certain IP addresses.
Syntax
NestJS
import { Request, Response, NextFunction } from 'express';

export function myMiddleware(req: Request, res: Response, next: NextFunction) {
  // your code here
  next();
}

Functional middleware is a simple function with three parameters: request, response, and next.

Always call next() to pass control to the next middleware or route handler.

Examples
This middleware logs the URL of every request.
NestJS
export function logger(req, res, next) {
  console.log(`Request to: ${req.url}`);
  next();
}
This middleware checks if the request has an authorization header and blocks if missing.
NestJS
export function checkAuth(req, res, next) {
  if (!req.headers.authorization) {
    return res.status(401).send('Unauthorized');
  }
  next();
}
Sample Program

This example shows a functional middleware logger that logs every request's method and URL. It is applied to all routes in the app module. When you visit http://localhost:3000, the middleware logs the request, and the controller returns 'Hello World!'.

NestJS
import { NestFactory } from '@nestjs/core';
import { Module, NestModule, MiddlewareConsumer } from '@nestjs/common';
import { Request, Response, NextFunction } from 'express';

// Functional middleware to log requests
export function logger(req: Request, res: Response, next: NextFunction) {
  console.log(`Request Method: ${req.method}, URL: ${req.url}`);
  next();
}

// Simple controller
import { Controller, Get } from '@nestjs/common';

@Controller()
class AppController {
  @Get()
  getHello() {
    return 'Hello World!';
  }
}

@Module({
  controllers: [AppController],
})
class AppModule implements NestModule {
  configure(consumer: MiddlewareConsumer) {
    consumer
      .apply(logger) // apply functional middleware
      .forRoutes('*'); // for all routes
  }
}

async function bootstrap() {
  const app = await NestFactory.create(AppModule);
  await app.listen(3000);
  console.log('Server running on http://localhost:3000');
}

bootstrap();
OutputSuccess
Important Notes

Functional middleware is easy to write and use for simple tasks.

Remember to always call next() or the request will hang.

You can apply middleware to specific routes or all routes.

Summary

Functional middleware is a simple function that runs before route handlers.

It helps add features like logging, authentication, or modifying requests.

Always call next() to continue the request cycle.