IntegrationsNEXT.JS

Handle Next.js CORS across server and client components

Next.js separates data fetching into server execution and client execution. Client components can route calls to public APIs without CORS headers through cors.dev by prefixing the URL with https://proxy.cors.dev/, while server-side code bypasses browser origin restrictions entirely. APIs that send explicit response headers need no proxy.

Client fetches require cross-origin headers

A component marked with 'use client' that fetches cross-origin data runs directly in the user browser. The target API must return Access-Control-Allow-Origin matching your site origin, or the browser drops the response. Third-party APIs lacking these headers block direct client requests completely.

Client component, public data, no CORS on the API
'use client';

import { useEffect, useState } from 'react';

export function WeatherNow() {
  const [temperature, setTemperature] = useState(null);

  useEffect(() => {
    fetch('https://proxy.cors.dev/https://api.example.com/data')
      .then((response) => (response.ok ? response.json() : Promise.reject(response.status)))
      .then((data) => setTemperature(data.value))
      .catch(() => setTemperature(null));
  }, []);

  return <p>{temperature === null ? 'Unavailable' : `${temperature}°C`}</p>;
}

Prefixing a supported endpoint with https://proxy.cors.dev/ routes the request through cors.dev, which attaches standard origin headers. Routing traffic through an intermediary allows the proxy operator to observe the transmitted data, making this method appropriate for public read-only APIs.

Server components run outside the browser

Server Components, Route Handlers, and Server Actions execute on your server environment. Your server issues these HTTP requests directly to upstream APIs, so the browser never participates. Environment secrets stay protected on your infrastructure and never leak into client bundles.

app/weather/page.tsx — server component
export default async function WeatherPage() {
  const response = await fetch(
    'https://api.open-meteo.com/v1/forecast?latitude=51.92&longitude=4.48&current=temperature_2m',
    { next: { revalidate: 300 } },
  );
  if (!response.ok) throw new Error(`Request failed: ${response.status}`);
  const data = await response.json();

  return <p>It is {data.current.temperature_2m}°C in Rotterdam.</p>;
}

The Next.js fetch cache stores responses according to your revalidate settings. Server fetches suit authenticated requests, database queries, and data required for initial page rendering.

Manage public variables and private credentials

Next.js inlines variables prefixed with NEXT_PUBLIC_ into client JavaScript bundles at build time. The cors.dev X-Cors-Key header is designed for browser exposure: it is a publishable identifier, and origin checks stop other websites from reusing it in browser code. It is not an anti-abuse secret, so rotate or revoke a key that gets misused. Private tokens and credentials belong exclusively in server environments like Route Handlers.

Good questions.

Can I use Next.js rewrites as a production proxy?

Next.js rewrites forward browser requests through your own Node.js server. This approach consumes your server bandwidth and compute budget for every proxied byte. Routing public calls through cors.dev, or fetching directly on the server, avoids converting your web tier into an open streaming proxy.

Does a route handler need CORS headers for my own frontend?

Requests from your own Next.js frontend to a Route Handler on the same host and port share the same origin. The browser permits these requests without any CORS configuration. Cross-origin headers become necessary only when a different domain or native application queries your route handlers cross-origin.

Static export changes what?

Running next build with output: 'export' removes the Node.js runtime entirely. All page components execute as client-side code in the visitor browser. Cross-origin calls from an export go through cors.dev when the API sends no CORS headers, or straight to APIs that permit the static site origin.