Request Mode and CORS
You'll learn how to control cross-origin behavior with request modes and understand how browsers handle cross-origin requests.
What is Request Mode?
When you create a fetch() request, the mode option tells the browser how strictly to enforce cross-origin rules. Think of it like security checkpoints at borders—different modes grant different levels of access to resources from other domains.
The Three Request Modes
cors (default)
The browser enforces full CORS (Cross-Origin Resource Sharing) rules. The server must explicitly allow your origin with proper headers like Access-Control-Allow-Origin. You can read the response if the server cooperates.
fetch('https://api.example.com/data', {
mode: 'cors' // default, can be omitted
})
no-cors
A restricted mode for cross-origin requests. The request succeeds, but you cannot read the response body or headers—it's "opaque." Useful when you just need to trigger an action (like tracking pixels) without reading results.
fetch('https://other-domain.com/track', {
mode: 'no-cors'
})
// Response is opaque—status will be 0, body unreadable
same-origin
The request will fail entirely if made to a different origin. It's like a safety lock ensuring you only fetch from your own domain.
fetch('/api/users', {
mode: 'same-origin'
})
// Throws if URL is cross-origin
Practical Impact
Use cors when you need data from APIs that support CORS. Use no-cors only when you don't need to read the response (rare cases). Use same-origin to strictly prevent accidental cross-origin requests.
Key Takeaway: Request mode controls how browsers handle cross-origin requests—cors enforces CORS rules with readable responses, no-cors allows requests but blocks response reading, and same-origin rejects cross-origin requests entirely.