Lesson 9 / 23

Writing Custom Middleware

Build your own reusable request-handling steps.

A simple gate-keeper

Check a header and either continue or stop the chain by sending a response.

function requireApiKey(req, res, next) {
  if (req.headers['x-api-key'] !== 'secret123') {
    return res.status(401).json({ error: 'Missing or invalid API key' });
  }
  next();
}

app.get('/admin', requireApiKey, (req, res) => {
  res.send('Welcome, admin');
});

Global vs per-route

app.use(fn) applies to every request. Passing fn as an extra argument to a route, like app.get('/admin', fn, handler), applies it only there.

Quick check: What happens if a middleware never calls next() or sends a response?

  • Express skips to the next route automatically
  • The request hangs — the client waits forever
  • Node throws a compile error
Answer

The request hangs — the client waits forever — Without next() or a response, the request-response cycle never completes and the client times out.