What is Cross-Origin Resource Sharing?
Ever hit a mysterious CORS error while fetching data from another website? Let's break down what CORS is and how it works.
CORS is a browser security feature that controls how web pages request resources from different domains, protocols, or ports.
For example, say your JavaScript on https://mohammadshehadeh.com tries to fetch data from https://api.another-service.com. Without proper CORS configuration, the browser blocks this request.
Understanding Origin
An origin has three parts:
- Protocol (e.g.,
http://orhttps://) - Domain name (e.g.,
mohammadshehadeh.com) - Port number (e.g.,
80or443)
Let's look at some 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 applies to several types of requests:
fetch()API callsXMLHttpRequestrequests- 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 certain 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
To include cookies or authentication headers with your requests, you need extra 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: