Q49: How do you enable Cross-Origin Resource Sharing (CORS) in Pages Router API routes?

To enable CORS in an API route, attach standard CORS response headers (Access-Control-Allow-Origin, Access-Control-Allow-Methods) directly using res.setHeader(), or wrap the handler using the cors npm package.

CORS Headers in API Route
export default async function handler(req, res) {
  res.setHeader('Access-Control-Allow-Origin', '*');
  res.setHeader('Access-Control-Allow-Methods', 'GET,POST,OPTIONS');
  if (req.method === 'OPTIONS') {
    return res.status(200).end(); // Respond to preflight
  }
  return res.json({ status: 'success' });
}
💡 Responds to OPTIONS preflight checks and sets origin headers to permit cross-site requests.
Key Takeaways
  • Set Access-Control-Allow-Origin using res.setHeader().
  • Handle HTTP OPTIONS preflight requests explicitly.
Knowledge Check

Which HTTP request method must be handled to respond to browser CORS preflight checks inside an API route handler?