What is Cross-Origin Resource Sharing?
Have you ever encountered mysterious CORS
errors while trying to fetch data from another website? You're not alone! Let's break down what CORS is and how it works.
CORS is a crucial security feature built into web browsers that controls how web pages can request resources from different domains, protocols, or ports.
For example, imagine your JavaScript code running on https://mohammadshehadeh.com
tries to fetch data from https://api.another-service.com
. Without proper CORS configuration, this request would be blocked by the browser.
Understanding Origin
An origin consists of three key components:
- Protocol (e.g.,
http://
orhttps://
) - Domain name (e.g.,
mohammadshehadeh.com
) - Port number (e.g.,
80
or443
)
Let's look at some practical examples:
Same Origin Examples
These URLs share the same origin:
Even these are considered same origin (port 80 is implicit for HTTP):
Different Origin Examples
These URLs have different origins:
Different protocols:
Different domains:
Different ports:
When Does CORS Apply?
CORS comes into play for various types of requests:
fetch()
API callsXMLHttpRequest
requests- Web Fonts (using
@font-face
) - WebGL textures (images or pixel data applied to 3D objects to enhance their appearance)
- Images/video frames drawn to a canvas using
drawImage()
Understanding Preflight Requests
Before making certain types of requests, browsers automatically send a "preflight" request using the OPTIONS
HTTP method. Think of it as a permission slip that checks if the actual request is allowed.
Key Preflight Headers
Request Headers:
Server Response Headers:
Working with Credentials
When you need to include cookies or authentication headers with your requests, you'll need special CORS configuration:
Required Server Headers:
When using credentials, Access-Control-Allow-Origin
cannot be set to *
and must specify the exact origin.
Best Practices
Only allow trusted websites in your CORS config:
References
Let's work together
I build exceptional and accessible digital experiences for the web
WRITE AN EMAILor reach out directly at hello@mohammadshehadeh.com