Node.js Express Middleware — The Complete Guide

Understand Express middleware: built-in, custom, error-handling middleware, and how to build middleware pipelines.

Node.js Intermediate 📖 8 min

What Is Middleware?

Middleware functions have access to the request, response, and next function. They can execute code, modify req/res, end the request-response cycle, or call next().

Custom Middleware

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

// Timing middleware
function timer(req, res, next) {
  const start = Date.now();
  res.on('finish', () => {
    console.log(`${req.method} ${req.url} took ${Date.now() - start}ms`);
  });
  next();
}

app.use(logger);
app.use(timer);

Route-Specific Middleware

function authMiddleware(req, res, next) {
  const token = req.headers.authorization?.split(' ')[1];
  if (!token) return res.status(401).json({ error: 'Unauthorized' });
  // verify token...
  next();
}

app.get('/api/profile', authMiddleware, (req, res) => {
  res.json({ user: req.user });
});

Error-Handling Middleware

// Must have 4 parameters to be recognized as error handler
app.use((err, req, res, next) => {
  console.error(err.stack);
  res.status(err.status || 500).json({
    error: process.env.NODE_ENV === 'production' ? 'Server error' : err.message
  });
});

Ready to Level Up Your Coding Skills?

Join Coderz Club and learn to code with challenges, battles, and an AI mentor.

Join Coderz Club Free →