Middleware Functions in Node.js

From the Express.js REST API cheat sheet · Express.js Basic Setup · verified Jul 2026

Middleware Functions

Create custom middleware for authentication, logging, and request processing

javascript
// Custom middleware
const auth = (req, res, next) => {
  const token = req.header('Authorization');
  if (!token) {
    return res.status(401).json({ error: 'Access denied' });
  }
  next();
};

// Apply middleware
app.use(auth);
app.get('/protected', auth, (req, res) => {
  res.json({ message: 'Protected route' });
});
🟢 Essential - Middleware is the heart of Express
💡 Order matters - middleware runs in sequence
⚠️ Don't forget next() or response will hang
📌 app.use() applies to all routes, router.use() to specific routes
⚡ Keep middleware focused on single responsibility

Continue with Express.js REST API

Save the full cheat sheet or work through every related task.

More Node.js tasks

Back to the full Express.js REST API cheat sheet