If you ever ran into this error :
Access to XMLHttpRequest at ’https://us-central1-appId.cloudfunctions.net/yourFunction’ from origin ’https://appId.firebaseapp.com’ has been blocked by CORS policy: No ‘Access-Control-Allow-Origin’ header is present on the requested resource.
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, this error is triggered because cloud function run on a different domain than than the one where your webapp is hosted.
There is two solution to solve this problems :
Into the declaration of your cloud functions, add those lines :
exports.hello = functions.https.onRequest((request, response) => { response.set('Access-Control-Allow-Origin', '*'); // you can set IP whitelist here, this line is mandatory, the rest are optional response.set('Access-Control-Allow-Credentials', 'true'); // Alow credentials to be readable on the response response.set('Access-Control-Allow-Methods', 'GET, POST'); // Allow acces to only those methods response.status(204).send('ok');
Now your function is callable from a different domain than the one of Cloud Functions. But this trick is not ideal because it break the security of CORS.
A second solution provided by Firebase is too make the cloud Functions callable from your website host (be careful, this solution is better for security but your functions will not be callable when you dev locally).
To do so, go to your firebase.json
file and use rewrites :
"hosting": { // ... // Add the "rewrites" attribute within "hosting" "rewrites": [ { "source": "/functionA", "function": "functionA" } ] }
Now if you want to trigger from your website, your cloud function is accessible here :
So any call on '/functionA'
from your webapp domain will redirect to your cloud function without harming the security of your website !
To know more about it, see the official Firebase documentation
Be careful, this last solution is better for security but your functions will not be callable when you dev locally (from localhost domain).