Blog>
Snippets

CORS Configuration Middleware

Configure Cross-Origin Resource Sharing (CORS) policy for specific Next.js API routes using middleware.
import { NextApiRequest, NextApiResponse } from 'next';

export function corsMiddleware(req, res, next) {
  // Set CORS headers
  res.setHeader('Access-Control-Allow-Origin', '*');

  // Allow the methods you wish to support
  res.setHeader('Access-Control-Allow-Methods', 'GET,POST,PUT,PATCH,DELETE,OPTIONS');

  // Allow headers you wish to support
  res.setHeader('Access-Control-Allow-Headers', 'Content-Type,Authorization');

  // Handle preflight OPTIONS request
  if (req.method === 'OPTIONS') {
    res.status(200).end();
    return;
  }

  // Call next() to pass control to the next handler
  next();
}

// Example usage with a Next.js API route
export default function handler(req: NextApiRequest, res: NextApiResponse) {
  corsMiddleware(req, res, () => {
    // Your API logic here
    res.json({ message: 'This API endpoint supports CORS.' });
  });
}
This code defines a CORS middleware function for a Next.js API route. It sets the appropriate 'Access-Control-Allow-*' headers and handles preflight OPTIONS requests. The middleware is then used in an example API handler function, which passes the request through the CORS middleware before executing the endpoint's logic.