Skip to content Skip to sidebar Skip to footer

How To Solve Cors In Firebase Functions Enviroment?

I´m runnig into CORS issues. In my functions/index.js I have: const cors = require('cors')({ origin: true }); My endpoint is https://sis-t.redsys.es:25443/sis/realizarPago. I n

Solution 1:

For someone who will meet this issue in the future (or my future self):

If you've already configured CORS using cors package, and you think you configured it correctly, and still have CORS error in the browser console, check this article:

https://haha.world/firebase-cors/

Basically, it's a misleading error returns from Google Cloud Functions, when actually the error is inside your code logic (which is totally not related to CORS at all)

So the first step to fix this bug is to check Google Cloud Functions logs (or Firebase Cloud Functions logs) to see if your function crashed because of any error in your code. Then fix it.


Note: For someone that doesn't have the issue that I described above, you can see other answers, or check these resources:

  1. https://expressjs.com/en/resources/middleware/cors.html
  2. https://firebase.google.com/docs/functions/http-events#using_existing_express_apps

Solution 2:

Within your Firebase Function response header you could explicitly allow all origins:

exports.handler = ((req, res) => {
    res.set({ 'Access-Control-Allow-Origin': '*' }).sendStatus(200)
})

Or you could modify this to allow only specific origins. This is generally how I have worked around CORS issues with Firebase funcitons in the past.

Solution 3:

Check out https://cloud.google.com/functions/docs/writing/http#handling_cors_requests . From that document -

exports.corsEnabledFunction = (req, res) => {
  // Set CORS headers// e.g. allow GETs from any origin with the Content-Type header// and cache preflight response for an 3600s
  res.set("Access-Control-Allow-Origin", "*");
  res.set("Access-Control-Allow-Methods", "GET");
  res.set("Access-Control-Allow-Headers", "Content-Type");
  res.set("Access-Control-Max-Age", "3600");
  // Send response to OPTIONS requests and terminate the function executionif (req.method == 'OPTIONS') {
    res.status(204).send('');
  }
  // Continue with function code
  ...
}

Post a Comment for "How To Solve Cors In Firebase Functions Enviroment?"