CORS stands for Cross-Origin Resource Sharing. According to developer.mozilla.org, Cross-Origin Resource Sharing (CORS) is a mechanism that uses additional HTTP headers to tell browsers to give a web application running at one origin, access to selected resources from a different origin. Simply, it is a web application security feature in a browser.
Image below shows how CORS is implemented :
We can see that domain-a.com contains an image from domain-b.com. However, of course the image from domain-b.com is not stored in the web server of domain-a.com which means the image is fetched from domain-b.com.
So, domain-a.com sends a GET request of image.png to the web server of domain-b.com. This request is called a cross-origin request and it is controlled by CORS in the web server of domain-b.com. In other words, The web server of domain-b.com must allow cross-origin requests from domain-a.com. So that domain-a.com can retrieve the image or whatever it requests.
In Strapi, CORS is controlled in this path :
Then you would like to specify allowed CORS origin which can be only one, or two, even more than three URLs.
Here is an example, if you have multiple URLs as allowed CORS origin :
The theory is that you must set enabled to true then put URLs of allowed CORS origin in your environment variable, in .env file. What .env file contains :
(Please note that of course you are also able to put a single URL as allowed CORS origin)
However, if you do not specify certain URLs in your environment variable, Strapi will recognize a string beside ‘CORS_ORIGIN’ as allowed CORS origin. Split function that comes after is to split the URLs if you have more than a single URL as allowed CORS origin. Otherwise, you do not have to split it. Usually the reason why it has more at least than one URL is :
- Your app’s client side
- Your Strapi admin panel (still considered as an external source)
Thank you for reading this article! See you in another Strapi post and have a nice day ~
Connect with me :
LinkedIn - kevinadhiguna
Github - kevinadhiguna
Read in Blog : https://about.lovia.life/how-to-configure-cors-in-strapi/
- Mozilla. ‘Cross-Origin Resource Sharing (CORS)’. https://developer.mozilla.org/en-US/docs/Web/HTTP/CORS.
- Strapi Middleware Configuration. https://strapi.io/documentation/developer-docs/latest/setup-deployment-guides/configurations.html#middlewares
Top comments (2)
Hi author, it working at localhost but when i deploy to server (DigitalOcean) then get Cors error like this:
My url Frontend app (react): abc.com
My url backend app (strapi): api.abc.com
So, how do i config it?