Careeroza
Functional Middleware
A Plain Function
If middleware needs no dependencies, a plain function is simpler.
src/common/middleware/block-bots.middleware.ts
import type { NextFunction, Request, Response } from 'express';
const BLOCKED = [/curl\/7\.0/, /BadBot/i];
export function blockBots(req: Request, res: Response, next: NextFunction) {
const ua = req.headers['user-agent'] ?? '';
if (BLOCKED.some((re) => re.test(ua))) {
res.status(403).json({ statusCode: 403, message: 'Forbidden' });
return; // do not call next()
}
next();
}Global functional middleware can also be added in main.ts with app.use(blockBots). Libraries like helmet() and cookieParser() are added this way.