Functional middleware lets you run code before your NestJS route handlers. It helps you add features like logging or checking user access simply.
Functional middleware in 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.
export function logger(req, res, next) {
console.log(`Request to: ${req.url}`);
next();
}export function checkAuth(req, res, next) {
if (!req.headers.authorization) {
return res.status(401).send('Unauthorized');
}
next();
}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!'.
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();
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.
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.