0
0
NextjsDebug / FixBeginner · 4 min read

How to Handle CORS in Next.js API Routes Correctly

To handle 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.

javascript
export default function handler(req, res) {
  res.status(200).json({ message: 'Hello from API' });
}
Output
Access to fetch at 'http://localhost:3000/api/hello' from origin 'http://localhost:3001' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource.
🔧

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.

javascript
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!' });
}
Output
{"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-Credentials is missing but cookies or auth headers are sent.
  • Wrong methods allowed: If your API only allows GET but client sends POST.

Key Takeaways

Add Access-Control-Allow-Origin header to Next.js API responses to fix CORS errors.
Use a CORS middleware package to handle preflight and multiple methods easily.
Avoid using wildcard '*' origin in production; specify allowed domains for security.
Handle OPTIONS requests in your API to support preflight checks.
Test your API from different origins to confirm CORS headers work correctly.