Discover how one simple function can save you from endless middleware copy-pasting!
Why Middleware factory pattern in Express? - Purpose & Use Cases
Imagine you need to create several similar middleware functions in Express, each with slightly different settings, like logging different messages or checking different user roles.
You write each middleware by hand, copying and changing code for every variation.
This manual approach leads to repeated code, making your app harder to maintain and prone to mistakes.
Every time you want a new variation, you must copy, paste, and carefully edit, risking bugs and wasted time.
The middleware factory pattern lets you write one function that creates customized middleware based on parameters you give it.
This means you write less code, avoid repetition, and can easily create many middleware variations by just calling the factory with different options.
function logAdmin(req, res, next) { console.log('Admin access'); next(); } function logUser(req, res, next) { console.log('User access'); next(); }function createLogger(role) { return function(req, res, next) { console.log(`${role} access`); next(); } } const logAdmin = createLogger('Admin'); const logUser = createLogger('User');This pattern enables flexible, reusable middleware that adapts easily to different needs without rewriting code.
In a web app, you can create one middleware factory to check user roles, then generate middleware for 'admin', 'editor', or 'viewer' roles simply by passing the role name.
Manual middleware duplication wastes time and risks errors.
Middleware factory pattern creates customizable middleware with one function.
It improves code reuse, clarity, and maintenance.