CORS with Cookies Between Next.js and a NestJS API: Preflights, Credentials, and When to Proxy Instead — Field Notes
Headline: CORS (Cross-Origin Resource Sharing) is a browser rule that decides whether page JavaScript may read a response from another origin; it does not stop the request from reaching your server. For a Next.js fronten
Headline: CORS (Cross-Origin Resource Sharing) is a browser rule that decides whether page JavaScript may read a response from another origin; it does not stop the request from reaching your server. For a Next.js frontend calling a NestJS API with cookies, either return the exact origin with
Access-Control-Allow-Credentials: trueand a 2xx preflight, or proxy/apithrough a Next.js rewrite so the browser never makes a cross-origin call.
Every project where I split a Next.js frontend from a NestJS API hits the same three CORS errors, in order: the preflight fails, the wildcard origin is rejected once cookies are involved, and then every call returns 200 while the user stays logged out because the session cookie never travels. Here is what each failure means and the setup I ended up with.
Key takeaways
- CORS is enforced by the browser, not the server: it controls whether page JavaScript can read a cross-origin response, and it does not stop the request from reaching your API.
-
A JSON
Content-Type, anAuthorizationheader, or aPUT/PATCH/DELETEmethod makes a request non-simple, so the browser first sends anOPTIONSpreflight — without cookies — and needs a 2xx response with matching allow headers. -
Credentialed requests (
credentials: 'include') requireAccess-Control-Allow-Credentials: trueplus the exact requesting origin;Access-Control-Allow-Origin: *is rejected. -
Cookies cross origins only when the request opts in and
SameSiteallows it; across different sites that meansSameSite=None; Secure, which Safari's default third-party cookie blocking still defeats. -
Proxying
/api/*through a Next.js rewrite makes the API same-origin: no preflights and first-party cookies, at the cost of one extra network hop.
What does CORS actually protect?
CORS protects the user's data inside the browser, not your server. An origin is the combination of scheme, host, and port, so https://app.example.com and https://api.example.com are different origins. The same-origin policy stops a page on one origin from reading responses from another, and CORS response headers are how a server opts specific origins back in.
Three consequences took me too long to internalize:
-
Only browsers enforce CORS. curl, Postman, a Next.js Server Component, and a NestJS service calling another service never send preflights or check
Access-Control-*headers. - A blocked request may still have run. For a simple cross-origin request, the browser sends it, the server executes it, and only the response is hidden from JavaScript.
-
CORS is not CSRF protection. A forged form POST from another site still reaches the API with whatever cookies the browser attaches;
SameSitecookies, CSRF tokens, or anOriginheader check are what stop it.
Same-origin and same-site are different tests, and cookies follow the same-site test. A site is the scheme plus the registrable domain (eTLD+1, such as example.com), and ports do not count:
| Request from | Request to | Same-origin? | Same-site? |
|---|---|---|---|
https://app.example.com |
https://api.example.com |
No — host differs | Yes — both on example.com
|
http://localhost:3000 |
http://localhost:4000 |
No — port differs | Yes — ports do not count |
https://shop.vercel.app |
https://shop-api.vercel.app |
No | No — vercel.app is a public suffix |
Why does my fetch trigger a preflight OPTIONS request?
The browser sends an OPTIONS preflight before any cross-origin request that is not "simple". A simple request uses GET, HEAD, or POST, sets only CORS-safelisted headers, and sends a Content-Type of text/plain, multipart/form-data, or application/x-www-form-urlencoded. A JSON body, an Authorization header, a custom header such as Idempotency-Key, or a PUT, PATCH, or DELETE method each force a preflight, so almost every real API call gets one:
await fetch('https://api.example.com/api/orders', {
method: 'POST',
credentials: 'include', // send and store cookies cross-origin
headers: { 'Content-Type': 'application/json' }, // not simple → preflight
body: JSON.stringify(order),
});
The preflight announces the method and headers in Access-Control-Request-Method and Access-Control-Request-Headers. The server must answer with a 2xx status plus Access-Control-Allow-Origin, Access-Control-Allow-Methods, and Access-Control-Allow-Headers values that cover them. Preflight requests never carry cookies or an Authorization header. My first failure came from exactly that rule: an auth middleware registered with app.use() above app.enableCors() answered every preflight with 401, and the browser reported it as a CORS error.
Access-Control-Max-Age sets how long the browser caches a preflight result. Without the header, the Fetch spec default is 5 seconds; Chromium caps the value at 7200 seconds and Firefox at 86400 seconds.
Why can't I use Access-Control-Allow-Origin: * with cookies?
A credentialed request — fetch(url, { credentials: 'include' }) or XMLHttpRequest.withCredentials = true — is readable only when the response sends Access-Control-Allow-Credentials: true and an Access-Control-Allow-Origin equal to the requesting origin. Chrome rejects the wildcard with: "The value of the 'Access-Control-Allow-Origin' header in the response must not be the wildcard '' when the request's credentials mode is 'include'." For credentialed requests, a ` in Access-Control-Allow-Headers, Access-Control-Allow-Methods, or Access-Control-Expose-Headers` is treated as a literal name, not a wildcard.
The tempting fix is to reflect whatever Origin arrives — origin: true in the cors package that NestJS uses with the Express adapter. Combined with credentials: true, reflection lets any website read authenticated responses for a logged-in user. I use an exact allowlist from an environment variable instead:
// main.ts
import { NestFactory } from '@nestjs/core';
import { AppModule } from './app.module';
const allowedOrigins = new Set(
(process.env.CORS_ORIGIN ?? '').split(',').map((o) => o.trim()).filter(Boolean),
);
async function bootstrap() {
const app = await NestFactory.create(AppModule);
app.enableCors({
origin: (origin, callback) => {
// No Origin header: curl, server-to-server calls — CORS does not apply
if (!origin || allowedOrigins.has(origin)) return callback(null, true);
callback(null, false); // omit CORS headers; the browser blocks the read
},
credentials: true, // Access-Control-Allow-Credentials: true
methods: ['GET', 'POST', 'PUT', 'PATCH', 'DELETE'],
allowedHeaders: ['Content-Type', 'Authorization', 'Idempotency-Key'],
exposedHeaders: ['ETag', 'X-Request-Id'],
maxAge: 7200, // Chromium's cap for preflight caching
});
await app.listen(process.env.PORT ?? 3000);
}
void bootstrap();
The details in that config that matter:
-
callback(null, false), not anError. Returningfalseomits the CORS headers and lets the browser block the read; passing anErrorturns the request into a 500 under Express. -
Exact strings only. A suffix regex like
/example\.com$/also matcheshttps://evil-example.com, and allowlistingnulladmits every sandboxed iframe andfile://page, because those sendOrigin: null. -
Vary: Originon every reflected response. Thecorspackage adds it automatically; a hand-written middleware must add it too, or a CDN can serve one origin'sAccess-Control-Allow-Originto another. -
Response headers are opt-in. JavaScript can read only CORS-safelisted response headers such as
Content-Type;ETagandX-Request-Idstay invisible until listed inAccess-Control-Expose-Headers.
Why are my cookies not sent on cross-origin requests?
A cookie crosses origins only when three layers agree: the request opts in, the cookie's SameSite attribute allows the context, and the browser's third-party cookie policy allows it. fetch() defaults to credentials: 'same-origin', so a cross-origin call needs credentials: 'include' before the browser sends any cookie or stores any Set-Cookie from the response.
When the frontend and API share a site — app.example.com and api.example.com — the request is same-site, and SameSite=Lax cookies are sent. Chrome treats a cookie with no SameSite attribute as Lax. A cookie set by api.example.com without a Domain attribute is host-only, so Next.js middleware on app.example.com cannot read it; Domain=example.com shares it with both hosts.
When they are different sites — such as two *.vercel.app deployments, because vercel.app is on the Public Suffix List — the session cookie becomes a third-party cookie. It needs SameSite=None; Secure, and even then Safari blocks third-party cookies by default and Chrome blocks them in Incognito. I stopped shipping cross-site cookie auth: either the API moves to a subdomain of the frontend's site, or the frontend proxies it.
When should I proxy API calls through a Next.js rewrite instead of enabling CORS?
Proxy through a Next.js rewrite when one frontend owns the API; keep CORS when several origins, a mobile app, or third parties call the API directly. A rewrite lets the browser call /api/... on its own origin while the Next.js server forwards the request to the backend, so there is no preflight, no CORS header, and every cookie is first-party:
// next.config.ts
import type { NextConfig } from 'next';
const nextConfig: NextConfig = {
async rewrites() {
return [
{
source: '/api/:path*',
destination: `${process.env.API_URL}/api/:path*`,
},
];
},
};
export default nextConfig;
The browser now calls fetch('/api/me') with the default credentials: 'same-origin'. A rewrites array runs after Next.js checks its own routes, so a local app/api route handler with the same path still wins. Two backend changes came with the switch: session cookies must be host-only, because the browser rejects Domain=api.example.com on the frontend's host; and rate limiting or logging must read the client IP from X-Forwarded-For instead of the socket address.
| Direct CORS | Next.js rewrite proxy | |
|---|---|---|
| Preflight | On every non-simple request, cached up to Access-Control-Max-Age
|
None — requests are same-origin |
| Cookies | Need credentials: 'include'; cross-site needs SameSite=None; Secure and fails under third-party cookie blocking |
First-party; SameSite=Lax works |
| Network path | Browser → API | Browser → Next.js → API (one extra hop) |
| Configuration | Origin allowlist on the API for every environment | One API_URL variable on the frontend |
Why does a 500 error show up as a CORS error?
A failed response without Access-Control-Allow-Origin is reported as a CORS error, which hides the real status code. JavaScript receives only a generic TypeError — "Failed to fetch" in Chrome — with no status. The usual causes are an error handler or gateway that responds before the CORS middleware runs, and nginx: add_header applies only to 2xx and 3xx responses unless the directive ends with always.
When a CORS error appears, I check the Network tab for the real status first, then replay the preflight with curl:
# Replay the preflight a browser would send
curl -i -X OPTIONS https://api.example.com/api/orders \
-H 'Origin: https://app.example.com' \
-H 'Access-Control-Request-Method: POST' \
-H 'Access-Control-Request-Headers: content-type'
A correct response returns 204 with Access-Control-Allow-Origin: https://app.example.com, Access-Control-Allow-Credentials: true, and an Access-Control-Allow-Headers value that includes content-type. If those headers are missing, the fix belongs on the server or the proxy, not in the frontend fetch() call.
FAQ
Q: Why does my API work in Postman or curl but fail in the browser?
A: CORS is enforced only by browsers. curl and Postman never send preflights or check Access-Control-* headers, so a missing or wrong CORS configuration shows up only when page JavaScript calls the API.
Q: Does mode: 'no-cors' fix a CORS error?
A: No. mode: 'no-cors' returns an opaque response with status 0 and an unreadable body, and it allows only simple requests. It silences the error by hiding the data.
Q: Is CORS a CSRF protection?
A: No. Simple cross-origin requests, such as an HTML form POST, still reach the server with cookies attached; CORS only stops the attacker's page from reading the response. Use SameSite cookies, CSRF tokens, or an Origin header check against CSRF.
Originally published on devya.dev. Also on eng-ahmed.com. Built by Devya Solutions.
Originally published by Dev.to Security. Aggregated on AIWithGhost for educational purposes — full credit and traffic to the original publisher.