Writing Custom Middleware
Jab koi logic MULTIPLE routes mein repeat ho — auth check, request timing, tenant resolve karna — use middleware bana do. Signature simple hai: (req, res, next), aur request par kuch bhi attach kiya ja sakta hai (req.user, req.requestId).
Configurable middleware ke liye FACTORY PATTERN use hota hai: ek function jo options leta hai aur middleware function RETURN karta hai. requireRole("admin") isi pattern ka example hai.
function requireRole(role) { // factory
return (req, res, next) => { // actual middleware
if (req.user?.role !== role) return res.status(403).json({ error: "Forbidden" });
next();
};
}
app.delete("/users/:id", requireAuth, requireRole("admin"), deleteUser);- Repeat hone waala cross-cutting logic middleware mein nikaalo
- req par data attach karke aage ke handlers tak pahunchao (req.user)
- Factory pattern se configurable middleware banao — requireRole("admin")
Middleware req par kuch bhi attach kar sakta hai jo aage ke handlers padh sakein — req.user (auth ke baad), req.requestId (tracing ke liye), req.tenant (multi-tenant apps). Ye Express mein data pass karne ka standard tareeka hai.
const { randomUUID } = require("crypto");
app.use((req, res, next) => {
req.id = req.get("X-Request-Id") || randomUUID();
res.set("X-Request-Id", req.id);
next();
});Jab middleware ko configuration chahiye, to ek OUTER function likho jo options le aur ACTUAL middleware return kare. Isse ek hi middleware alag-alag settings ke saath kai jagah use ho jaata hai.
function cacheFor(seconds) {
return (req, res, next) => {
res.set("Cache-Control", `public, max-age=${seconds}`);
next();
};
}
app.get("/products", cacheFor(300), listProducts);
app.get("/config", cacheFor(86400), getConfig);