Search Authority

Next.js CORS: Fix API Errors & Enable Cross-Origin Requests Fast

Next.js CORS configuration is a common pain point when building APIs and integrating third party frontends. Misconfigured headers can block legitimate requests or expose your ro...

Mara Ellison Jul 25, 2026
Next.js CORS: Fix API Errors & Enable Cross-Origin Requests Fast

Next.js CORS configuration is a common pain point when building APIs and integrating third party frontends. Misconfigured headers can block legitimate requests or expose your routes unintentionally.

Understanding how CORS works in Next.js helps you balance security and accessibility while keeping your API predictable and debuggable.

Key Concepts at a Glance

Concept Description Default in Next.js API Routes Recommended Action
CORS Headers HTTP headers that control which origins can access resources Not added automatically Add Access-Control-Allow-Origin selectively
Preflight Request OPTIONS request sent by browsers to check permissions Handled by Next.js only if you define an options route Implement OPTIONS or use middleware to respond
Middleware CORS Centralized handling before request reaches pages or API Not enabled by default Use next.config.js or middleware.ts for global rules
Route Specifics CORS rules can vary per API route or page proxy Isolation per file Align origins per route sensitivity

How CORS Works in Next.js API Routes

When you create API routes under pages/api, Next.js does not add CORS headers automatically. Without explicit headers, browsers block frontend code on another origin from reading the response, even if the server returns a 200 status.

You can set Access-Control-Allow-Origin in getServerSideProps, API routes, or middleware. For simple GET requests, adding the header is straightforward, but for complex scenarios involving credentials or custom methods, you must handle preflight OPTIONS requests correctly.

Controlling which methods and headers are allowed using Access-Control-Allow-Methods and Access-Control-Allow-Headers reduces errors during development and prevents surprising runtime blocks in production.

Using Middleware for Global CORS Management

Middleware gives you a single place to enforce CORS policies across your entire Next.js app. By running before a request reaches a page or an API route, you can add headers or short circuit unwanted traffic based on origin.

This approach is ideal when multiple routes need the same rules, and it keeps each page or API file focused on business logic. You can conditionally allow origins, log cross origin attempts, or route requests differently depending on the environment.

Use middleware when you want consistent security headers, easier audits, and less duplicated code compared to repeating CORS logic in every handler.

CORS Configuration for Server Components in App Router

With the App Router, server actions and server components run on the server by default, so CORS is rarely an issue for direct calls. However, client side fetch calls from the browser still rely on proper headers if the route origin differs.

You can set CORS headers in route handlers inside the App Router by exporting GET, POST, and similar methods in a dedicated file. Middleware remains a powerful option to apply rules globally, including runtime based conditions.

Keep in mind that static generation and caching strategies can affect when headers are applied, so coordinate caching headers with your CORS policy to avoid stale or overly permissive responses.

Common Misconfigurations and Debugging Tips

Developers sometimes allow all origins with a wildcard and then wonder why credentials are rejected. Browsers block wildcard origins when credentials are involved, so you must specify exact origins dynamically.

Another frequent issue is handling OPTIONS preflight only in the client or proxy layer, while the server route does not respond to OPTIONS at all. Ensure your API route or middleware replies to OPTIONS with the appropriate headers and a 204 status.

Use browser dev tools, server logs, and curl to compare expected and actual headers, and test from multiple origins to confirm that your rules work as intended.

Best Practices and Next Steps for Secure CORS

  • Specify exact origins instead of using wildcards when credentials are involved
  • Centralize policy with middleware and avoid duplicating logic across routes
  • Handle OPTIONS preflight explicitly to prevent browser blocks
  • Log unexpected origins to detect misconfigurations or abuse attempts
  • Align caching and security headers so CORS rules do not undermine cache correctness
  • Test across browsers and environments to catch subtle differences in behavior

FAQ

Reader questions

Why does my frontend get a CORS error even though the API route returns data?

The browser blocks the response because the Access-Control-Allow-Origin header is missing or does not match the requesting origin. Add the correct origin based on your frontend URL, and ensure credentials mode is consistent between client and server.

How do I allow credentials with a dynamic origin list in Next.js CORS?

Read the Origin header from the request, validate it against an allowed list, and then set Access-Control-Allow-Origin to that specific origin. Also include Access-Control-Allow-Credentials and do not use a wildcard when credentials are required.

What is the best way to handle OPTIONS preflight in Next.js API routes?

Respond to OPTIONS requests early in your handler or middleware with Access-Control-Allow-Methods and Access-Control-Allow-Headers, then send a 204 status. This prevents browsers from blocking the actual request due to missing preflight approval.

Can I set CORS headers in middleware instead of in each route handler?

Yes, middleware is ideal for global rules. You can add headers for all responses or conditionally skip CORS for internal routes, keeping your page and API files cleaner and more focused on their core responsibilities.

Related Reading

More pages in this topic cluster.

How to Tell the Difference Between Silver and Aluminum (Silver vs Aluminum)

Spotting the difference between silver and aluminum helps you verify purchases, appraise items, and avoid overpaying for misidentified metals. While they look similar at first g...

Read next
Excel Keyboard Shortcut for Strikethrough: Easy Step-by-Step Guide

Mastering the Excel keyboard shortcut for strikethrough helps you track completed tasks, revisions, and action items without leaving the keyboard. This small efficiency habit sp...

Read next
Durham NC News Today: Latest Headlines & Updates

Durham NC news keeps the Research Triangle region informed about breakthrough healthcare, education, and downtown development. Local reporting connects residents and visitors to...

Read next