In this post, we will learn how to enable CORS in Cloud Functions for Firebase.
Suppose, we have the following function:
const functions = require('firebase-functions')
exports.addMessage = functions.https.onRequest(async (req, res) => {
res.json({ status: 'ok' })
})
And we are trying to call it from the browser using the fetch
method.
You will see an error about the CORS policy. There is a lot of information about what is CORS, so, let’s go to the solutions.
You can enable CORS by installing the cors
library in your functions
folder:
npm i cors --save
Here is an example of usage:
const functions = require('firebase-functions');
const cors = require('cors');
exports.addMessage = functions.https.onRequest((req, res) => {
cors()(req, res, () => {
return res.json({status: 'ok'});
});
});
If you make a request again, the access-control-allow-origin
header will appear and it means that CORS enabled:
Also, you can pass additional properties into cors
function and configure CORS in your way:
const functions = require('firebase-functions');
const cors = require('cors');
exports.addMessage = functions.https.onRequest((req, res) => {
const options = {
origin: 'http://example.com'
}
cors(options)(req, res, () => {
return res.json({status: 'ok'});
});
});
You can set CORS
headers without any library
const functions = require('firebase-functions');
exports.addMessage = functions.https.onRequest(async (req, res) => {
res.set('Access-Control-Allow-Origin', '*');
if (req.method === 'OPTIONS') {
res.set('Access-Control-Allow-Methods', 'GET');
res.set('Access-Control-Max-Age', '3600');
res.status(204).send('');
} else {
res.json({status: 'ok'});
}
});
Enabling CORS in Cloud Functions for Firebase is the same as for Express, Hapi, Koa, NestJs.
If CORS was enabled in your function the result for the fetch
method will be the following: