0
0
Expressframework~5 mins

Middleware factory pattern in Express

Choose your learning style9 modes available
Introduction

The middleware factory pattern helps create reusable middleware functions that can be customized with different settings.

When you want to create middleware that behaves differently based on input parameters.
When you need to reuse similar middleware logic with small variations.
When you want to keep your code clean by avoiding repeated middleware code.
When building APIs that require configurable request handling.
When you want to add logging or validation with different rules per route.
Syntax
Express
function middlewareFactory(options) {
  return function middleware(req, res, next) {
    // middleware logic using options
    next();
  };
}
The factory function returns the actual middleware function.
You can pass any configuration to customize middleware behavior.
Examples
This factory creates middleware that logs a greeting message.
Express
function greetFactory(greeting) {
  return function (req, res, next) {
    console.log(`${greeting}, user!`);
    next();
  };
}
This factory creates middleware to check if the user has a specific role.
Express
const checkRole = (role) => (req, res, next) => {
  if (req.user?.role === role) {
    next();
  } else {
    res.status(403).send('Forbidden');
  }
};
Sample Program

This Express app uses a middleware factory to create logging middleware with different messages. The first middleware logs a message for all requests. The second logs a message only for GET / requests.

Express
import express from 'express';

const app = express();

// Middleware factory that logs a custom message
function loggerFactory(message) {
  return function (req, res, next) {
    console.log(message);
    next();
  };
}

// Use middleware with different messages
app.use(loggerFactory('First middleware running'));
app.get('/', loggerFactory('Handling GET /'), (req, res) => {
  res.send('Hello from middleware factory!');
});

app.listen(3000, () => {
  console.log('Server started on http://localhost:3000');
});
OutputSuccess
Important Notes

Middleware factories help keep your code DRY (Don't Repeat Yourself).

Always call next() inside middleware to continue the request cycle.

You can pass any data to the factory to customize middleware behavior.

Summary

Middleware factory pattern creates customizable middleware functions.

It helps reuse similar middleware logic with different settings.

Use it to keep your Express code clean and flexible.