Q15: How do you use Node.js middleware in Pages Router API routes?

API handlers can execute standard Express/Connect middleware helper functions or custom wrapper functions to inspect request headers, authenticate tokens, or log requests before returning data.

API Middleware Wrapper Pattern
function withAuth(handler) {
  return async (req, res) => {
    if (!req.headers.authorization) {
      return res.status(401).json({ error: 'Unauthorized' });
    }
    return handler(req, res);
  };
}

export default withAuth(function handler(req, res) {
  res.status(200).json({ data: 'Secret Data' });
});
💡 Wrapper functions execute authentication logic prior to calling core request handlers.
Key Takeaways
  • Wrap API handlers or use helper functions to integrate custom middleware.
  • Runs within standard Node.js server contexts.
Knowledge Check

Where does custom API route middleware execute in the Pages Router?