Performance: Global middleware
Global middleware affects the request processing time and overall server response speed by running on every incoming request.
app.use((req, res, next) => {
if (req.path.startsWith('/api')) {
lightweightCheck();
}
next();
});app.use((req, res, next) => {
heavyComputation();
next();
});| Pattern | DOM Operations | Reflows | Paint Cost | Verdict |
|---|---|---|---|---|
| Heavy synchronous global middleware | N/A (server-side) | N/A | N/A | [X] Bad |
| Lightweight conditional global middleware | N/A (server-side) | N/A | N/A | [OK] Good |
export class LoggerMiddleware implements NestMiddleware {
use(req: Request, res: Response, next: Function) {
console.log(`Request to: ${req.url}`);
next();
}
}
// Applied globally with consumer.apply(LoggerMiddleware).forRoutes('*')export class AuthMiddleware implements NestMiddleware {
use(req: Request, res: Response) {
if (!req.headers.authorization) {
res.status(401).send('Unauthorized');
}
}
}
// Applied with consumer.apply(AuthMiddleware).forRoutes('*')Pass the test and this pattern moves unknown