Enabling CORS in Cloud Functions for Firebase


firebase cloud cors

In this post, we will learn how to enable CORS in Cloud Functions for Firebase.

How does CORS look like?

Suppose, we have the following function:

const functions = require('firebase-functions')

exports.addMessage = functions.https.onRequest(async (req, res) => {
  res.json({ status: 'ok' })
})

And we are trying to call it from the browser using the fetch method.

Request from browser

You will see an error about the CORS policy. There is a lot of information about what is CORS, so, let’s go to the solutions.

Running with CORS library

You can enable CORS by installing the cors library in your functions folder:

npm i cors --save

Here is an example of usage:

const functions = require('firebase-functions');
const cors = require('cors');

exports.addMessage = functions.https.onRequest((req, res) => {
  cors()(req, res, () => {
    return res.json({status: 'ok'});
  });
});

If you make a request again, the access-control-allow-origin header will appear and it means that CORS enabled:

access-control-allow-origin in Headers

Also, you can pass additional properties into cors function and configure CORS in your way:

const functions = require('firebase-functions');
const cors = require('cors');

exports.addMessage = functions.https.onRequest((req, res) => {
  const options = {
    origin: 'http://example.com'
  }
  cors(options)(req, res, () => {
    return res.json({status: 'ok'});
  });
});

access-control-allow-origin header as example.com

Running without CORS library

You can set CORS headers without any library

const functions = require('firebase-functions');

exports.addMessage = functions.https.onRequest(async (req, res) => {
  res.set('Access-Control-Allow-Origin', '*');

  if (req.method === 'OPTIONS') {
    res.set('Access-Control-Allow-Methods', 'GET');
    res.set('Access-Control-Max-Age', '3600');
    res.status(204).send('');
  } else {
    res.json({status: 'ok'});
  }
});

Conclusion

Enabling CORS in Cloud Functions for Firebase is the same as for Express, Hapi, Koa, NestJs.

If CORS was enabled in your function the result for the fetch method will be the following:

Request with enabled CORS

comments powered by Disqus