How to Handle CORS in Next.js API Routes Correctly
CORS in Next.js API routes, you need to set the appropriate Access-Control-Allow-Origin header in the API response. You can do this manually by adding headers or use a middleware like cors package to manage CORS policies easily.Why This Happens
CORS (Cross-Origin Resource Sharing) errors happen because browsers block requests from one origin (domain) to another unless the server explicitly allows it. If your Next.js API route does not send the right headers, the browser will refuse to share the response.
export default function handler(req, res) { res.status(200).json({ message: 'Hello from API' }); }
The Fix
You fix this by adding the Access-Control-Allow-Origin header to your API response. For simple cases, add it directly in your handler. For more control, use the cors middleware package to handle preflight requests and methods.
import Cors from 'cors'; import initMiddleware from '../../lib/init-middleware'; // Initialize the cors middleware const cors = initMiddleware( Cors({ methods: ['GET', 'POST', 'OPTIONS'], origin: '*', // Allow all origins or specify your domain }) ); export default async function handler(req, res) { // Run cors middleware await cors(req, res); res.status(200).json({ message: 'CORS is handled!' }); }
Prevention
Always add CORS headers or middleware to your API routes if they will be accessed from different origins. Use middleware to handle OPTIONS preflight requests automatically. Avoid using origin: '*' in production; specify allowed domains for security.
Related Errors
Other common errors include:
- Preflight request fails: Happens if OPTIONS method is not handled.
- Credentials not allowed: When
Access-Control-Allow-Credentialsis missing but cookies or auth headers are sent. - Wrong methods allowed: If your API only allows GET but client sends POST.