DEV Community

Cover image for What is CORS ? How to configure CORS in Strapi ?
kevinadhiguna
kevinadhiguna

Posted on • Updated on

What is CORS ? How to configure CORS in Strapi ?

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 :
Alt Text

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 :
./config/middleware.js
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 :
Alt Text

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 :
Alt Text

(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/

Reference :

Top comments (2)

Collapse
 
cucheng profile image
Trương Đình Chiến

Hi author, it working at localhost but when i deploy to server (DigitalOcean) then get Cors error like this:

Alt text of image

My url Frontend app (react): abc.com
My url backend app (strapi): api.abc.com

So, how do i config it?

Collapse
 
sasicodes profile image
Sasidharan

Really useful