1
votes

I am trying to call my Firebase cloud functions from my React client.

  1. I am able to successfully call these functions using HTTP requests (as described here). This requires setting up a full Express app in the cloud function.

  2. Now I am trying to call the cloud functions directly from my client using httpsCallable() (as described here). It appears that this method has a couple of advantages over calling over HTTP requests. However using this approach I am getting the following CORS error:

Access to fetch at 'https://us-central1-myapp.cloudfunctions.net/helloWorld' from origin 'http://localhost:3000' has been blocked by CORS policy

How do I make this work? Is it worth the trouble? Is it really the preferred way?

Here's my cloud function:

import * as functions from 'firebase-functions';

export const helloWorld = functions.https.onRequest((request, response) => {
    response.send('Hello from Firebase!');
});

Here's how I am calling it from my client:

const sayHello = async (): Promise<string> => {
    const helloWorld = firebase.functions().httpsCallable('helloWorld');
    const result = await helloWorld();
    return result.data;
};
1

1 Answers

3
votes

By doing

const helloWorld = firebase.functions().httpsCallable('helloWorld');
const result = await helloWorld();

you are indeed calling a Callable Cloud Function, but by defining the called Function as follows

functions.https.onRequest((request, response) => {})

you are defining an HTTPS Cloud Function which is different.

You should define your Cloud Function as a Callable one, as follows:

export const helloWorld =  = functions.https.onCall((data, context) => {
  return { response: 'Hello from Firebase!' };
});