0
0
ExpressHow-ToBeginner · 3 min read

How to Create Custom Middleware in Express: Simple Guide

In Express, create custom middleware by writing a function with req, res, and next parameters. Call next() inside it to pass control to the next middleware or route handler.
📐

Syntax

A custom middleware in Express is a function that takes three parameters: req (request object), res (response object), and next (a function to pass control). You write your logic inside this function and call next() when done to continue the request cycle.

javascript
function customMiddleware(req, res, next) {
  // Your code here
  next();
}
💻

Example

This example shows a custom middleware that logs the request method and URL, then passes control to the next middleware or route.

javascript
import express from 'express';
const app = express();

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

app.use(logger);

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

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

Common Pitfalls

One common mistake is forgetting to call next(), which causes the request to hang and never reach the next middleware or route. Another is sending a response and then calling next(), which can cause errors because the response is already sent.

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

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

Quick Reference

  • Middleware function signature: (req, res, next) => void
  • Call next() to continue: Always call next() unless you send a response.
  • Use app.use() to apply middleware: This adds middleware globally or to specific routes.
  • Order matters: Middleware runs in the order it is added.

Key Takeaways

Custom middleware in Express is a function with req, res, and next parameters.
Always call next() to pass control unless sending a response ends the cycle.
Use app.use() to apply middleware globally or to specific routes.
Middleware runs in the order it is added, so order affects behavior.
Avoid sending a response and calling next() afterward to prevent errors.