DEV Community

Cover image for Middleware in Express.js – A Complete Guide
Vasanth S
Vasanth S

Posted on

Middleware in Express.js – A Complete Guide

Middleware are function that runs between request from the client and response from the server.

Each middleware function has access to :

  • req - request object
  • res- response object
  • next() - a function that pass control to next middleware.

Signature of middleware function

function middlewareName(req, res, next) {
  // Do something
  next(); // move to next middleware
}
Enter fullscreen mode Exit fullscreen mode

if forgot to call next(), the request-response cycle will hang.

Express has 5 types of middleware:

  • Application-level
  • Router-level
  • Built-in
  • Third-party
  • Error-handling

Application-level middleware

  • Bound to an app object using app.use() or app.METHOD().
  • Runs for every request or specific routes.
app.use((req, res, next) => {
  console.log("Application middleware executed");
  next();
});
Enter fullscreen mode Exit fullscreen mode

Router-level Middleware

  • Works the same as application-level, but bound to an express.Router() instance.
  • Useful for modular route handling.
const router = express.Router();
router.use((req, res, next) => {
  console.log("Router middleware executed");
  next();
});
app.use("/api", router);
Enter fullscreen mode Exit fullscreen mode

Built-in Middleware

Comes with Express by default.

Common ones are:

  • express.json() → parse JSON body
  • express.urlencoded() → parse form data
  • express.static() → serve static files
app.use(express.json());
app.use(express.static("public"));
Enter fullscreen mode Exit fullscreen mode

Third-party Middleware

Installed via npm to add extra features.

Examples:

  • morgan → request logging
  • cookie-parser → parse cookies
  • cors → handle cross-origin requests
  • helmet → security headers
const morgan = require("morgan");
app.use(morgan("dev"));
Enter fullscreen mode Exit fullscreen mode

Error-handling Middleware

  • Special middleware with 4 parameters: (err, req, res, next).
  • Used to handle errors globally.
app.use((err, req, res, next) => {
  console.error(err.message);
  res.status(500).send("Something broke!");
});
Enter fullscreen mode Exit fullscreen mode

Top comments (0)