CORS credentials misconfiguration on Next.js
Your API sends `Access-Control-Allow-Credentials: true` alongside a wildcard or overly permissive Allow-Origin. Modern browsers block this combination, but the intent is still dangerous — if a proxy or middleware rewrites the header, you end up with any site being able to make authenticated requests on behalf of logged-in users. Fix it by explicitly reflecting the Origin from an allowlist, and only setting Allow-Credentials when the origin matches.
The fix for Next.js
Next.js
Reflect only allowed origins. Do NOT blindly echo the Origin header.
const ALLOWED = ['https://app.example.com'];
function corsHeaders(origin: string | null): Headers {
const h = new Headers();
if (origin && ALLOWED.includes(origin)) {
h.set('Access-Control-Allow-Origin', origin);
h.set('Access-Control-Allow-Credentials', 'true');
h.set('Vary', 'Origin');
}
return h;
}Why it matters
CORS with credentials is how browsers enforce that cookies are only sent to trusted origins. A misconfiguration here means a user visiting `evil.com` while logged into your app could have their session used to fetch their data.
Confirm the fix worked
Scan your Next.js site to confirm this finding is gone.
AI prompt
Apply across your codebase
Paste this into Cursor, Lovable, Bolt, v0, or Claude Code.
My API has an Access-Control-Allow-Credentials: true header with an overly permissive Access-Control-Allow-Origin. Implement a strict allowlist of my known frontend origins. Only set Allow-Credentials when the Origin matches a known entry. Never reflect the Origin header without checking it.FAQ
Frequently asked questions
- I just want to test from localhost.
- Add `http://localhost:3000` to the allowlist for dev. Do not leave a wildcard in production.
Related fix guides
Fix these too
CORS allows all origins
An Access-Control-Allow-Origin: * policy lets any site call your API. Sometimes that is fine, often it is a mistake. Here is how to decide and fix it.
Read moreCookie missing SameSite
SameSite controls whether cookies are sent on cross-site requests — the main defense against CSRF. Here is how to set it.
Read moreConcepts
Glossary
Cross-Origin Resource Sharing
CORS is a browser mechanism that controls which websites can call your API. Misconfigurations can open your app to cross-site attacks.
Read moreCross-Site Request Forgery
CSRF tricks a logged-in user into performing actions on your site without realizing. SameSite cookies are the modern defense.
Read moreFree tools