Credentials and CORS
What you'll learn: How to send cookies and authentication with cross-origin requests and what headers must be set on both sides.
By default, fetch() doesn't include cookies, HTTP authentication, or TLS client certificates when making cross-origin requests — even if you'd normally send them to that domain. This is a security feature.
Why Credentials Are Excluded
Imagine a malicious site trying to make requests to your bank on your behalf. If credentials were automatically included, it could access your logged-in session. CORS prevents this by requiring explicit opt-in from both the client and the server.
Sending Credentials from the Client
To include credentials in a cross-origin request, set credentials: 'include':
fetch('https://api.example.com/user', {
credentials: 'include' // Include cookies and auth
})
Server Requirements
The server must respond with two headers:
Access-Control-Allow-Credentials: true— explicitly allows credentialsAccess-Control-Allow-Origin— must specify the exact origin (wildcards*are forbidden when credentials are involved)
Access-Control-Allow-Credentials: true
Access-Control-Allow-Origin: https://yoursite.com
The Security Model
Think of it like a two-key safe: you (the client) must turn your key by setting credentials: 'include', and the server must turn its key by sending Access-Control-Allow-Credentials: true. Both are required, or the browser blocks the response.
Without this mutual agreement, cross-origin authenticated requests fail, protecting users from malicious sites exploiting their logged-in sessions elsewhere.
Key Takeaway: Use credentials: 'include' to send cookies/auth across origins, but the server must respond with Access-Control-Allow-Credentials: true and a specific origin — wildcards aren't allowed with credentials.