CORS with Cookies and Authentication
Configure CORS to support cross-origin cookies and authentication headers. Covers SameSite attributes, Secure flag, and the three-way handshake for credentials.
Credentials
Detailed Explanation
The Credentials Triple Requirement
For cookies to travel cross-origin, three things must all be configured correctly. Miss any one and cookies will be silently dropped.
1. Server: Allow-Credentials Header
Access-Control-Allow-Origin: https://app.example.com
Access-Control-Allow-Credentials: true
The origin must not be * when credentials are enabled.
2. Client: Credentials Flag
// Fetch API
fetch("https://api.example.com/data", {
credentials: "include",
});
// Axios
axios.get("https://api.example.com/data", {
withCredentials: true,
});
3. Cookie: SameSite and Secure Attributes
Set-Cookie: session=abc123; SameSite=None; Secure; HttpOnly; Path=/
SameSite=Noneis required for cross-origin cookies (since Chrome 80+).Secureis mandatory whenSameSite=None.HttpOnlyprevents JavaScript from reading the cookie (recommended for session tokens).
Common Failure Modes
| Symptom | Cause |
|---|---|
| Cookie not sent | Client missing credentials: "include" |
| Cookie sent but response blocked | Server missing Allow-Credentials: true |
| Cookie not set at all | SameSite not set to None, or missing Secure flag |
| Opaque response | Origin is * with credentials — browser rejects silently |
Debugging Steps
- Check the Network tab for the
Set-Cookieresponse header. - Open Application > Cookies to see if the cookie was stored.
- Verify the next request includes the
Cookieheader. - Confirm the CORS response includes both
Allow-Origin(specific) andAllow-Credentials: true.
Use Case
A single-page application at app.example.com needs to authenticate users via a session cookie stored by the API at api.example.com. Without the correct CORS and cookie configuration, the login endpoint returns a Set-Cookie header that the browser refuses to store.