0
0
ExpressHow-ToBeginner · 4 min read

How to Create Reusable Middleware in Express: Simple Guide

In Express, create reusable middleware by defining a function that takes req, res, and next parameters and then export it. You can import and use this middleware in multiple routes or apps by calling app.use() or attaching it to specific routes.
📐

Syntax

A reusable middleware in Express is a function with three parameters: req (request), res (response), and next (a function to pass control to the next middleware). You define your logic inside and call next() when done.

Example syntax:

function middlewareName(req, res, next) {
  // your code here
  next();
}

You can export this function and use it in any route or app instance.

javascript
function reusableMiddleware(req, res, next) {
  console.log('Middleware running');
  next();
}
💻

Example

This example shows how to create a reusable middleware that logs the request method and URL, then use it in an Express app for all routes.

javascript
import express from 'express';

// Reusable middleware function
function logger(req, res, next) {
  console.log(`${req.method} ${req.url}`);
  next();
}

const app = express();

// Use middleware for all routes
app.use(logger);

app.get('/', (req, res) => {
  res.send('Hello World');
});

app.get('/about', (req, res) => {
  res.send('About page');
});

app.listen(3000, () => {
  console.log('Server running on http://localhost:3000');
});
Output
Server running on http://localhost:3000 GET / GET /about
⚠️

Common Pitfalls

Common mistakes when creating reusable middleware include:

  • Not calling next(), which causes the request to hang.
  • Modifying req or res incorrectly, leading to unexpected behavior.
  • Forgetting to export the middleware function if it is in a separate file.

Always ensure next() is called unless you end the response.

javascript
/* Wrong: missing next() call */
function badMiddleware(req, res, next) {
  console.log('This will hang the request');
  // next() is missing
}

/* Correct: calls next() */
function goodMiddleware(req, res, next) {
  console.log('This passes control');
  next();
}
📊

Quick Reference

Tips for reusable middleware in Express:

  • Middleware functions always have (req, res, next) signature.
  • Call next() to continue to next middleware or route handler.
  • Use app.use() to apply middleware globally or attach to specific routes.
  • Export middleware from separate files for reuse across projects.

Key Takeaways

Reusable middleware in Express is a function with (req, res, next) parameters.
Always call next() inside middleware to avoid hanging requests.
Use app.use() to apply middleware globally or on specific routes.
Export middleware functions to reuse them across different files or projects.
Keep middleware focused on a single task for easier reuse and testing.