Cross Origin Resource Sharing (CORS)đź”»
During your web development journey, you've probably come across the term CORS, or maybe faced an issue due to CORS. Let’s chat a little about it.
Also, don’t forget to pray for our people in Palestine, Syria, Sudan, Yemen, Lebanon, and all countries around the world. 🔻
What is CORS?
CORS stands for Cross-Origin Resource Sharing.
đź“Ś But first, what is Origin?
The "Origin" refers to the domain where your website or server is hosted. It's composed of the protocol (like HTTP or HTTPS) + the domain name (like example.com) + the port (if it's not the default 80 for HTTP or 443 for HTTPS).
⚡ So, where's the issue?
If you're working on a website and want it to request data or resources (like JSON files) from another server, that server must be from the same origin as your site — meaning it should have the same domain, protocol, and port.
This is known as the Same-Origin Policy, which is put in place to protect users from malicious requests from untrusted websites.
However, in some cases, as a developer, you might need to make requests to servers that are not from the same origin, like when you have a frontend running on one domain and an API or backend running on another domain or port.
This is where CORS comes in 👇
Cross-Origin Resource Sharing (CORS) is the solution that allows websites to safely and securely request data or files from servers with different origins. It enables bypassing the Same-Origin Policy, allowing requests to be made to other servers, provided that the server is willing to interact with your site.
đź“Ś How does CORS work?
When your website requests data from a server with a different origin, the server hosting the resource decides whether or not to allow the request.
The server responds with specific headers included in the response.
One of the most important headers is: Access-Control-Allow-Origin
This header specifies the origins that are allowed to request data from the server. If your website's origin is included in this header’s value, the server will permit the request and send back the response. If not, the request will be blocked, and you’ll get a CORS error in your browser.
đź“Ť Other important headers include:
- Access-Control-Allow-Methods: Specifies which HTTP methods (GET, POST, PUT, DELETE, etc.) are allowed.
- Access-Control-Allow-Headers: Specifies which headers you’re allowed to send in your requests.
- Access-Control-Allow-Credentials: If the request requires sending cookies or specific data, this header must be present and set to true.
What are some common problems with CORS? 🤔
Sometimes, CORS can be frustrating, and you’ll encounter "CORS error" messages in the browser if the server doesn't support requests from your origin.
The solution is to ensure that the server you’re requesting from has its CORS settings properly configured.