0
0
Expressframework~3 mins

Why Middleware factory pattern in Express? - Purpose & Use Cases

Choose your learning style9 modes available
The Big Idea

Discover how one simple function can save you from endless middleware copy-pasting!

The Scenario

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.

The Problem

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 Solution

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.

Before vs After
Before
function logAdmin(req, res, next) { console.log('Admin access'); next(); } function logUser(req, res, next) { console.log('User access'); next(); }
After
function createLogger(role) { return function(req, res, next) { console.log(`${role} access`); next(); } } const logAdmin = createLogger('Admin'); const logUser = createLogger('User');
What It Enables

This pattern enables flexible, reusable middleware that adapts easily to different needs without rewriting code.

Real Life Example

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.

Key Takeaways

Manual middleware duplication wastes time and risks errors.

Middleware factory pattern creates customizable middleware with one function.

It improves code reuse, clarity, and maintenance.