CORS not working on specific domains in firebase cloud functions

Viewed 508
const whitelist = ["http://mywebsite.com", "http://localhost:5000"]

const corsOptions = {
    origin: function (origin, callback) {
      if (whitelist.indexOf(origin) !== -1) {
        callback(null, true)
      } else {
        callback(new Error('Not allowed by CORS'))
      }
    }
  }

const cors = require('cors')(corsOptions);

exports.getUserProfile = functions.https.onRequest((req, res) => {
    cors(req, res, () => {
        try {
            //... here we fetch the user profile and send it in response
        } catch (err) {
            res.json({
                status: "error",
                message: err
            })
        }
    });
});

I'm using CORS in this way so I could only let my own website and localhost:5000 to make requests to the cloud functions that I'm using. localhost:5000 is for me so I could test stuff locally before I deploy the files.

  1. Making a request from reqbin.com to my cloud function is working, why? Shouldn't it NOT work, since I've specified the domain to be either from mywebsite.com or localhost:5000?
  2. Is there any other way to test stuff locally without having to include localhost:5000 in the whitelist? I'm using firebase serve to test, but I'm assuming this won't work since the requests won't be treated from mywebsite.com
1 Answers

This will help you by using origin from cors library directly.

const cors = require('cors')

const corsHandler = cors({
    origin:["http://mywebsite.com", "http://localhost:5000"]
});

exports.getUserProfile = functions.https.onRequest((req, res) => {
    corsHandler(req, res, async () => {
        try {
            //... here we fetch the user profile and send it in response
        } catch (err) {
            res.json({
                status: "error",
                message: err
            })
        }
    });
});
Related