Multiple Route Handlers

Pass several functions to a route and move between them with next().

Syntaxapp.get(path, handler1, handler2)

A route can have more than one handler. Express runs them in order. Each handler either sends a response or calls next() to pass control to the next one.

This is useful for putting shared logic, such as a permission check, in front of the main handler.

Example

Example · javascript
const checkAuth = (req, res, next) => {
  if (!req.query.token) {
    return res.status(401).send('No token');
  }
  next(); // allowed, continue
};

app.get('/dashboard', checkAuth, (req, res) => {
  res.send('Secret dashboard');
});

When to use it

  • A protected endpoint chains an authentication middleware handler before the main handler that fetches the user's data.
  • A file-upload route uses three handlers: validate the token, check file size, then write the file to storage.
  • A developer separates the logic for logging and the business logic into two sequential route handlers for cleaner code.

More examples

Single route handler

The simplest form — a single callback function handles the entire request-response cycle.

Example · js
app.get('/profile', (req, res) => {
  res.json({ user: 'Alice', plan: 'pro' });
});

Multiple handlers in sequence

Passes two named handler functions: the first logs the request and calls next(), the second sends the response.

Example · js
function logRequest(req, res, next) {
  console.log(`${req.method} ${req.path}`);
  next();
}

function sendProfile(req, res) {
  res.json({ user: 'Alice' });
}

app.get('/profile', logRequest, sendProfile);

Handler array with auth guard

Passes an array of handlers — requireAuth blocks unauthenticated requests before getOrders runs.

Example · js
function requireAuth(req, res, next) {
  if (!req.headers.authorization) {
    return res.status(401).json({ error: 'Unauthorized' });
  }
  next();
}

function getOrders(req, res) {
  res.json([{ id: 1, item: 'Widget' }]);
}

app.get('/orders', [requireAuth, getOrders]);

Discussion

  • Be the first to comment on this lesson.