Request Credentials: Cookies and Authentication
What You'll Learn
You'll learn how to control whether cookies and authentication data are sent with your fetch() requests using the credentials option.
Why Credentials Matter
By default, browsers protect your privacy by limiting when cookies and HTTP authentication are sent with requests. When you use fetch(), you need to explicitly tell the browser your intention regarding credentials—this prevents accidental data leakage.
Think of credentials like your ID card at different security checkpoints: sometimes you show it automatically (at your own building), sometimes never (at a public park), and sometimes even at other people's buildings (if you have special permission).
The Three Credentials Options
When making a fetch() request, use the credentials property with one of three values:
credentials: 'omit'
Never send cookies or authentication, even to your own site. Use this for completely public requests where you want no user identification.
fetch('https://api.example.com/data', {
credentials: 'omit'
});
credentials: 'same-origin' (default)
Only send credentials to your own domain. This is the default behavior—cookies travel to yoursite.com but not to api.otherdomain.com.
fetch('/api/profile', {
credentials: 'same-origin' // Sends cookies to same domain
});
credentials: 'include'
Send credentials everywhere, even to different domains (if CORS allows it). Necessary for authenticated cross-origin requests.
fetch('https://api.partner.com/data', {
credentials: 'include' // Sends cookies cross-origin
});
When to Use Each
Use 'same-origin' for most authenticated requests on your own site. Use 'include' only when working with trusted third-party APIs that require your authentication. Use 'omit' for anonymous public data fetching.
Key Takeaway: The credentials option controls cookie transmission: 'omit' sends nothing, 'same-origin' (default) sends to your domain only, and 'include' sends everywhere CORS permits.