- Middleware is a function that is called before the route handler (controller)
- Middleware in NestJs is a way to intercept and handle incoming requests before they reach the route handlers. It allows you to perform actions such as authentication, validation, logging, and error handling at a global or local level in your application.
Type of middleware
- Module-based
- Global Middleware
Method of creating middleware
- Function-based
- Class-Based
Function-based
function globalMiddlewareOne(req:Request,res:Response,next:NextFunction){
console.log("This is global middleware one")
next()
}
Class-Based
@Injectable()
export class BookMiddleware implements NestMiddleware {
use(req: Request, res: Response, next: NextFunction) {
let protocol = req.protocol; //http https
let host = req.get('host'); //localhost
let url = req.originalUrl;
let method = req.method;
let date = new Date().toDateString();
console.log(
protocol + '://' + host + url + ' ' + method + ' ' + date,
);
next();
}
}