Search code examples
javascriptfirebasegoogle-cloud-platformcorsgoogle-cloud-functions

Enabling CORS in Cloud Functions for Firebase


I'm currently learning how to use new Cloud Functions for Firebase and the problem I'm having is that I can't access the function I wrote through an AJAX request. I get the "No 'Access-Control-Allow-Origin'" error. Here's an example of the function I wrote:

exports.test = functions.https.onRequest((request, response) => {
  response.status(500).send({test: 'Testing functions'});
})

The function sits in this url: https://us-central1-fba-shipper-140ae.cloudfunctions.net/test

Firebase docs suggests to add CORS middleware inside the function, I've tried it but it's not working for me: https://firebase.google.com/docs/functions/http-events

This is how I did it:

var cors = require('cors');    

exports.test = functions.https.onRequest((request, response) => {
   cors(request, response, () => {
     response.status(500).send({test: 'Testing functions'});
   })
})

What am I doing wrong? I would appreciate any help with this.

UPDATE:

Doug Stevenson's answer helped. Adding ({origin: true}) fixed the issue, I also had to change response.status(500) to response.status(200) which I completely missed at first.


Solution

  • For Cloud Functions v2:

    You can simply define the function to accept CORS requests as shown in the documentation:

    const { onRequest } = require("firebase-functions/v2/https");
    
    exports.sayHello = onRequest(
      { cors: true },
      (req, res) => {
        res.status(200).send("Hello world!");
      }
    );
    

    For Cloud Functions v1:

    There are two sample functions provided by the Firebase team that demonstrate the use of CORS:

    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
        })
    });