|

What is CORS ? How to configure CORS in Strapi ?

What is CORS ?

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 :

Image : developer.mozilla.org

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.

How to setup CORS in Strapi ?

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 :

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 :

  1. Your app’s client side
  2. 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 dev.to : https://dev.to/kevinadhiguna/what-is-cors-how-to-configure-cors-in-strapi-461b

Reference :

  1. Mozilla. ‘Cross-Origin Resource Sharing (CORS)’. https://developer.mozilla.org/en-US/docs/Web/HTTP/CORS.
  2. Strapi Middleware Configuration. https://strapi.io/documentation/developer-docs/latest/setup-deployment-guides/configurations.html#middlewares 

Similar Posts