Request Credentials and Mode
What you'll learn: How to control whether cookies and authentication data are sent with your fetch requests using credentials and mode options.
When you make a fetch request, you need to decide whether to include sensitive data like cookies or authentication tokens. The credentials option controls this behavior, working hand-in-hand with the mode option you learned about earlier.
Understanding credentials
The credentials property has three possible values:
"omit" – Never send cookies or authentication headers, even if the server expects them. Think of this as going incognito: no credentials attached.
"same-origin" (default) – Send cookies only when requesting resources from your own domain. It's like showing your ID card only when entering your own building.
"include" – Always send cookies, even for cross-origin requests. This is like carrying your ID everywhere, even when visiting other domains.
How It Works
// No credentials sent at all
fetch('https://api.example.com/data', {
credentials: 'omit'
});
// Send cookies only to same origin
fetch('/api/profile', {
credentials: 'same-origin'
});
// Send cookies even cross-origin
fetch('https://partner-api.com/data', {
credentials: 'include',
mode: 'cors'
});
The mode Connection
Remember that credentials: 'include' requires mode: 'cors' for cross-origin requests. The server must also explicitly allow credentials with CORS headers—otherwise the browser blocks the request for security.
Common Pattern
const request = new Request('/api/user', {
method: 'GET',
credentials: 'same-origin',
mode: 'same-origin'
});
fetch(request);
Key Takeaway: Use credentials to control cookie and authentication sharing—'omit' for none, 'same-origin' for your domain only (default), and 'include' for all requests, always considering security implications.