Enabling CORS in Cloud Functions for Firebase
Solution 1:
There are two sample functions provided by the Firebase team that demonstrate the use of CORS:
- Time server with date formatting
- HTTPS endpoint requiring Authentication
The second sample uses a different way of working with cors than you're currently using.
Consider importing like this, as shown in the samples:
const cors = require('cors')({origin: true});
And the general form of your function will be like this:
exports.fn = functions.https.onRequest((req, res) => {
cors(req, res, () => {
// your function body here - use the provided req and res from cors
})
});
Solution 2:
You can set the CORS in the cloud function like this
response.set('Access-Control-Allow-Origin', '*');
No need to import the cors
package
Solution 3:
For anyone trying to do this in Typescript this is the code:
import * as cors from 'cors';
const corsHandler = cors({origin: true});
export const exampleFunction= functions.https.onRequest(async (request, response) => {
corsHandler(request, response, () => {});
//Your code here
});