Cross-Origin Requests
This article contains AI generated content verified by a human.
Background
Modern browsers implement the Same Origin Policy to protect users.
An origin is defined by the combination of protocol, domain, and port. If any of these differ between a web page and the resource it requests, the request is considered cross‑origin.
Examples:
http://example.comvshttps://example.com→ different protocol, different originhttp://localhost:3000vshttp://localhost:3010→ different port, different originhttps://app.example.comvshttps://api.example.com→ different subdomain, different origin
When a frontend application tries to call an API hosted on a different origin, the browser blocks the response unless the server explicitly allows it.
[ Browser loads page ]
|
v
Page Origin = (protocol + domain + port)
Example: https://app.example.com:443
|
v
Page makes request to API
Target Origin = (protocol + domain + port)
Example: https://api.example.com:443
|
v
[ Browser compares origins ]
- Same protocol?
- Same domain?
- Same port?
|
v
If ALL match → Same Origin → Allowed directly
If ANY differ → Cross Origin → Trigger CORS check
|
v
[ Preflight Request (OPTIONS) ]
Browser asks server: "Do you allow this origin?"
|
v
Server Response Headers:
Access-Control-Allow-Origin: https://app.example.com
Access-Control-Allow-Methods: GET, POST, OPTIONS
Access-Control-Allow-Headers: Content-Type, Authorization
|
v
If headers match → Browser allows request
If headers missing/invalid → Browser blocks request
Without it, any website you visit could secretly make requests to other sites where you’re logged in (like your bank, email, or social media) and read the responses. That would expose sensitive data such as account balances, private messages, or authentication tokens.
- Example:
You’re logged into your bank athttps://mybank.com.
You then visit a malicious sitehttps://evil.com.
If browsers didn’t enforce Same Origin Policy,evil.comcould run JavaScript that callshttps://mybank.com/accountand read your balance or transfer money — all without your knowledge.
Implication for web development
The browser's safety intervention leads to errors such as:
Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource- Status code
(null)with failed preflight requests
These errors occur because the backend server are not configured with the required CORS headers.
Failed Approaches
❌ Ignoring Protocol Differences
Running the frontend on http:// and the backend on https:// without CORS headers will always fail.
❌ Using Wildcard with Credentials
Access-Control-Allow-Origin: *
Access-Control-Allow-Credentials: true
This combination is invalid — browsers reject it.
❌ Forgetting Preflight Responses
Not handling OPTIONS requests properly means the browser blocks subsequent GET or POST calls.
✅ Working Solution: Configure CORS Headers
The server must respond with explicit headers that match the frontend origin:
Access-Control-Allow-Origin: https://app.example.com
Access-Control-Allow-Methods: GET, POST, OPTIONS
Access-Control-Allow-Headers: Content-Type, Authorization
Access-Control-Allow-Credentials: true
Example: Nginx Configuration
location /api/ {
proxy_pass http://backend:3010;
add_header Access-Control-Allow-Origin "https://app.example.com" always;
add_header Access-Control-Allow-Methods "GET, POST, OPTIONS" always;
add_header Access-Control-Allow-Headers "Content-Type, Authorization" always;
add_header Access-Control-Allow-Credentials "true" always;
}
Key Principles
- Origin matters: protocol, domain, and port must match.
- Server decides trust: only the backend can allow cross‑origin access.
- Preflight is mandatory: handle
OPTIONSrequests correctly. - Credentials require explicit origins: never use
*with cookies or sessions.
Benefits of Proper CORS
- Protects sensitive user data from malicious sites.
- Enables legitimate cross‑origin apps (frontend ↔ API).
- Provides fine‑grained control over which origins are trusted.
Conclusion
CORS is not a nuisance but a security safeguard. By understanding how origins are defined and configuring headers correctly, developers can build secure applications that allow trusted cross‑origin communication while blocking malicious attempts.
Copyleft Statement
Renoncé du droit d'auteur
Much of our content is freely available under the Creative Commons BY-NC-ND 4.0 licence, which allows free distribution and republishing of our content for non-commercial purposes, as long as Ronzz.org is appropriately credited and the content is not being modified materially to express a different meaning than it is originally intended for. It must be noted that some images on Ronzz.org are the intellectual property of third parties. Our permission to use those images may not cover your reproduction. This does not affect your statutory rights.
Nous mettons la plupart de nos contenus disponibles gratuitement sous la licence Creative Commons By-NC-ND 4.0, qui permet une distribution et une republication gratuites de notre contenu à des fins non commerciales, tant que Ronzz.org est correctement crédité et que le contenu n'est pas modifié matériellement pour exprimer un sens différent que prévu à l'origine.Il faut noter que certaines images sur Ronzz.org sont des propriétés intellectuelles de tiers. Notre autorisation d'utiliser ces images peut ne pas couvrir votre reproduction. Cela n'affecte pas vos droits statutaires.
Member discussion