Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
CORS in Google Cloud Functions for Firebase
const cors = require('cors')({origin: true});
exports.sample = functions.https.onRequest((req, res) => {
cors(req, res, () => {
res.send('Passed.');
});
});
@HuddleHouse
Copy link

HuddleHouse commented Dec 1, 2017

Thanks!

@jpfong
Copy link

jpfong commented Apr 8, 2018

Thanks! Not so much documentation about that! By the way, if anyone had the equivalent in typeScript, it would be great!

@hermanfenderson
Copy link

hermanfenderson commented Apr 14, 2018

Maybe I am missing something...
Not working here..
No 'Access-Control-Allow-Origin' header is present on the requested...

@hermanfenderson
Copy link

hermanfenderson commented Apr 14, 2018

It worked...
My blame

@CoderTonyB
Copy link

CoderTonyB commented May 11, 2018

@jpfong - check here: https://4dev.at/google-cloud-functions-with-cors/

You have to wrap the whole darn thing in a cors function -

import * as cors from 'cors';
const corsHandler = cors({origin: true});

export const pingFunctionWithCorsAllowed = functions.https.onRequest((request, response) => {
  corsHandler(request, response, () => {
    response.send(`Ping from Firebase (with CORS handling)! ${new Date().toISOString()}`);
  });
});

@reviloera
Copy link

reviloera commented Jun 18, 2018

THANK YOU SO MUCH .... YOU SAVED MY DAY BRO

@bernieperez
Copy link

bernieperez commented Jul 16, 2018

Thanks @CoderTonyB! Thats exactly what I was looking for. I can't believe we have to wrap the whole function. If they are using some express type backend for Cloud Functions too bad we can use the middleware to apply it to all https requests.

@rodolfofranco
Copy link

rodolfofranco commented Oct 19, 2018

I can't seem to make this work, I'm following instructions provided

import * as cors from 'cors';
const corsHandler = cors({origin: true});
admin.initializeApp();

export const getPlatforms = functions.https.onRequest((req, res) => {
  return corsHandler(req, res, () => {
    axios.get('https://api-endpoint.igdb.com/platforms/?search='+req.body.query+'&fields=name&limit=50&filter[name][prefix]='+req.body.query,{headers:{ 'user-key':api_key,'Accept':'application/json'}})
    .then( response =>{
        console.log('PLATFORMS:',response.data)
        res.json(response.data);
        })
  });
});

@basquith16
Copy link

basquith16 commented May 9, 2019

This saved my life. THANK YOU

@abbrechen
Copy link

abbrechen commented May 19, 2019

Great idea, thanks !

@lnmendez
Copy link

lnmendez commented Jun 1, 2019

GRACIAS, ME SALVASTE LA VIDA!

@Hansanghyeon
Copy link

Hansanghyeon commented Aug 1, 2019

Thanks!

@RubinaSapra
Copy link

RubinaSapra commented Nov 5, 2019

The error here is "Modifiers cannot appear here." Help me out!

`import * as functions from 'firebase-functions';
import * as admin from 'firebase-admin';
import * as cors from 'cors';
const corsHandler = cors({origin: true}); //cors fix
admin.initializeApp(functions.config().firebase)

export const exampleFunction= functions.https.onRequest(async (request, response) => { //cors fix
corsHandler(request, response, () => {}); //cors fix

export const updateLikesCount = functions.https.onRequest((request, response) => {

console.log(request.body);
let body: any;
if (typeof (request.body) === 'string') {
  body = JSON.parse(request.body);
} else {
  body = request.body;
}
   const postId=body.postId;

const userId=body.userId;

const action=body.action;

admin.firestore().collection('posts').doc(postId).get()
  .then((data: any) => {
    let likesCount = data.data().likesCount || 0;
    const likes = data.data().likes || [];
    const updateData: { likesCount: number, likes: string[] } = { likesCount: likesCount, likes: likes };
    if (action === 'like') {
      updateData['likesCount'] = ++likesCount;
      updateData['likes'].push(userId);
    } else {
      updateData['likesCount'] = --likesCount;
      updateData['likes'].splice(updateData['likes'].indexOf(userId), 1);
    }
    admin.firestore().collection('posts').doc(postId).update(updateData)
      .then(() => {
        response.status(200).send('Done');
      })
      .catch(error => {
        response.status(error.code).send(error.message);
      })
  })
  .catch(error => {
    response.status(error.code).send(error.message);
  });

});
});`

@chrodin
Copy link

chrodin commented Feb 26, 2020

I followed the steps above but still got errors in regards to the 'import', my final implementation that worked for me was:

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

exports.pingFunctionWithCorsAllowed = functions.https.onRequest((request, response) => {
  corsHandler(request, response, () => {
    response.send(`Ping from Firebase (with CORS handling)! ${new Date().toISOString()}`);
  });
});

note that you have to install cors as well if you haven't done so
npm i -S cors

@vamshidhar11
Copy link

vamshidhar11 commented May 29, 2020

// Enable CORS using the cors express middleware.
return cors(req, res, () => {
// ...
});
It is there in documentations but not for callable functions, Firebase should have been more clear with the documentation.
Thanks you.

@jesster2k10
Copy link

jesster2k10 commented Aug 2, 2020

Here's my solution:

middleware.ts

import * as functions from 'firebase-functions';
import { corsMiddleware } from './cors';

export type FunctionHandler = (
  req: functions.https.Request,
  res: functions.Response<any>,
) => void | Promise<void>;

export const withMiddleware = (
  handler: FunctionHandler,
  regions = ['europe-west2', 'europe-west3'],
) =>
  functions.region(...regions).https.onRequest((req, res) => {
    return corsMiddleware(req, res, () => {
      handler(req, res);
    });
  });

and you can use it like so:

export const sendContactMessage = withMiddleware(async (req, res) => {
});

@mikemanders
Copy link

mikemanders commented Oct 31, 2020

@jesster2k10 Your answer seems great, but passing the regions with the spread operator gives an typescript error.
Argument of type 'string' is not assignable to parameter of type '"europe-west2" | "europe-west3" | "us-central1" | "us-east1" | "us-east4" | "europe-west1" | "asia-east2" | "asia-northeast1"'.ts(2345).
Do you know how to fix this? For now I'm sticking to one region to overcome this problem.

Thanks for the great answer.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment