Facebook Pixel

What Is Express Middleware? Explained With Examples

Middleware is the heart of Express. Here is what it is and how to write your own.

What Is Express Middleware? Explained With Examples

Middleware is the heart of Express. Almost everything in Express is middleware: body parsing, CORS, auth, logging, error handling. Here is what middleware is and how to write your own.

What Is Middleware

A function with the signature (req, res, next) => {}. It runs on every request (or on every request to a path). It can:

  • Modify req (e.g., set req.user).
  • Send a response (and end the cycle).
  • Call next() to pass to the next middleware.
  • Call next(err) to jump to the error handler.

Where Middleware Fits

When a request arrives, Express runs middlewares in the order you added them. Each middleware sees the same req and res. After all middlewares, the matched route handler runs (it is just a final middleware).

Example: A Logger Middleware

const logger = (req, res, next) => {
  console.log(`${req.method} ${req.url}`);
  next();
};
app.use(logger);

Logs every request, then passes control.

Example: An Auth Middleware

const auth = (req, res, next) => {
  const token = req.cookies.token;
  if (!token) return res.status(401).json({ error: 'Not authenticated' });
  try {
    req.user = jwt.verify(token, process.env.JWT_SECRET);
    next();
  } catch {
    return res.status(401).json({ error: 'Invalid token' });
  }
};

Either sets req.user and calls next, or sends 401 and stops.

Example: A Validation Middleware

const validateSignup = (req, res, next) => {
  const { email, password } = req.body;
  if (!email || !password) return res.status(400).json({ error: 'Missing fields' });
  next();
};

Types of Middleware

  • App-level: app.use(middleware). Runs for every request.
  • Router-level: router.use(middleware). Runs for routes in that router.
  • Built-in: express.json, express.static.
  • Third-party: cors, helmet, morgan.
  • Error-handling: four parameters (err, req, res, next).

Order Matters

Middlewares run in the order you add them. Add body parser before routes. Add auth before protected routes. Add error handler last.

The Takeaway

Express middleware is a function (req, res, next) that runs on requests. It can modify req, send a response, call next, or pass an error to the error handler. Types: app-level, router-level, built-in, third-party, and error-handling. Order matters.

A function with the signature (req, res, next) that runs on requests. It can modify req, send a response, call next to continue, or call next(err) to jump to the error handler. Almost everything in Express is middleware.

Modify req (e.g., set req.user from JWT), send a response and end the cycle, call next() to pass to the next middleware, or call next(err) to jump to the error handler.

App-level (app.use), router-level (router.use), built-in (express.json), third-party (cors, helmet), and error-handling (four parameters: err, req, res, next).

Express runs middlewares in the order you add them. Add body parser before routes that need req.body. Add auth before protected routes. Add the error handler last. Wrong order causes silent bugs.

A route handler is just a final middleware. It is the last function in the chain for that route. The same (req, res, next) signature applies, but handlers usually send the response instead of calling next.

Ready to master Node.js completely?

Want to upskill yourself, crack your next interview, and get your dream job? Join our comprehensive course to dive deeper with high-quality video tutorials, solve interview questions, and a premium community.

Please Login.
Please Login.
Please Login.
Please Login.
Please Login.
Please Login.
Please Login.
Please Login.
Please Login.
Please Login.
Please Login.
Please Login.