Enabling CORS Middleware In Firebase Cloud Functions

Firebase Cloud Functions are great, but there might come a time where you need CORS support. This can be enabled easily by using the CORS middleware.

The documentation does detail part of the process, but it doesn’t mention you need to install the cors package and also specify origin: true as a configuration option. If you’re new to Node.js, this might catch you off guard.

Go into your functions directory in your application and in your terminal: npm install cors --save this will add the CORS middleware package to your package.json.

Open up your index.js file in the functions directory and add in the following:

const cors = require('cors')({
  origin: true
});

exports.helloWorld = functions.https.onRequest((req, res) => {
    cors(req, res, () => {
        res.send("Hello from Firebase!");
    });
});

Notice how we use the CORS middleware function inside of our request handler? You’ve just added in CORS. Essentially what is happening here is, you’re taking the actual response and then running it through the cors middleware which then makes it a cross-origin request.

It is possible to set the headers manually on your request without the cors package, but the easiest and cleanest solution is using the cors middleware instead.