Skip to content

Instantly share code, notes, and snippets.

@mediavrog
Last active April 14, 2023 08:56
Show Gist options
  • Star 33 You must be signed in to star a gist
  • Fork 5 You must be signed in to fork a gist
  • Save mediavrog/49c4f809dffea4e00738a7f5e3bbfa59 to your computer and use it in GitHub Desktop.
Save mediavrog/49c4f809dffea4e00738a7f5e3bbfa59 to your computer and use it in GitHub Desktop.
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.');
});
});
@RubinaSapra
Copy link

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

// 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

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

@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.

@jimbits
Copy link

jimbits commented Dec 21, 2022

@jpfong I want to thank you for your post I have been spending the last 4 hours trying to get cors working. So random why would they not put an example in the docs. Thank you so much

@rgbskills
Copy link

Hello, Im getting the cors error and I can figure out why, here is may code:

import express from "express";
import cors from "cors";

const expressApp = express();
expressApp.use(cors({origin: true}));

expressApp.get("/Hello", (req, res) => {
  res.send("Hello!");
});

Can anyone help me out?

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