If you ever ran into this error :
Access to fetch at ‘IMAGE-URL-FROM-FIREBASE-CLOUD -STORAGE’ from origin ‘http://localhost:3000’ has been blocked by CORS policy: No ‘Access-Control-Allow-Origin’ header is present on the requested resource. If an opaque response serves your needs, set the request’s mode to ‘no-cors’ to fetch the resource with CORS disabled.
Then you are in the good place to find a solution !
First of all, what is CORS (Cross-origin resource sharing) ? It’s a protocol that avoid a call to an external domain. For example, https://domain-a.com uses XMLHttpRequest to make a request for https://domain-b.com/data.json.
If the server in domain-b does not specify CORS, the request will be blocked by the browser.
Here for Firebase or Google Cloud Storage, this error is triggered because our cloud bucket does not accept external address for fetching data inside the Google Cloud Storage Bucket !
To solve this issue, we will change the CORS rules of our Google Cloud Storage (Firebase) Bucket.
First we’ll need to access Google Cloud Console. Choose the project you want to change, then click on the console icon top right of the Google Cloud dashboard :
A terminal window should appear at the bottom of the screen.
First we will create a JSON where we will write the new rules for our Google Cloud Storage bucket. To do that type in the Google Cloud Console :
$ nano cors.json
A VIM editor will appear in the Google Cloud Console, add this code into it :
[ { "origin": ["*"], "method": ["GET"], "maxAgeSeconds": 3600 } ]
The origin can contain multiples URLs of website allowed to query the Google Cloud Storage Bucket.
*
means that all website are accepted, it’s not good for security, but for testing it’s ok. Be careful to only put there trusted domains when deploying on production.
In method you can put other type like
POST
. Here we only want to get some data not modify it, soGET
is perfect.
When done with the content simply press CTRL + X
followed by y
.
Our Google Cloud Storage Bucket rules are now defined in this cors.json
. We need to apply them to the bucket now :
$ gsutil cors set cors.json gs://YOUR-BUCKET-PROJECT-URL
Your Google Cloud Storage bucket URL that is the Firebase storage bucket is the one in the storage page that end with appspot.com
, most of the time it’s projectId.appspot.com
:
If you followed everything you should see :
myName@cloudshell:~ (PROJECT-ID)$ gsutil cors set cors.json gs://YOUR-BUCKET-PROJECT-URL Setting CORS on gs://YOUR-BUCKET-PROJECT-URL/... myName@cloudshell:~ (PROJECT-ID)$
Congratulations! You changed the CORS policy for a specified bucket in Google Cloud Storage! Head back to your website running on localhost
and it should now have access to the file in your Google Cloud Storage Bucket.