QBoard » Supporting Tech Stack » Cloud » Enabling CORS in Cloud Functions for Firebase

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

      October 21, 2021 2:46 PM IST
    0
  • 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
    });
      December 31, 2021 12:25 PM IST
    0
  • One additional piece of info, just for the sake of those googling this after some time: If you are using firebase hosting, you can also set up rewrites, so that for example a url like (firebase_hosting_host)/api/myfunction redirects to the (firebase_cloudfunctions_host)/doStuff function. That way, since the redirection is transparent and server-side, you don't have to deal with cors.

    You can set that up with a rewrites section in firebase.json:

    "rewrites": [
            { "source": "/api/myFunction", "function": "doStuff" }
    ]
      February 3, 2022 4:06 PM IST
    0