Home > front end >  How to call Firebase cloud function from React stream chat app
How to call Firebase cloud function from React stream chat app

Time:09-13

Long story short, I'm knew to Firebase and I need to call this cloud function: "ext-auth-chat-getStreamUserToken" . The trigger is a HTTPS request to: https://europe-west2-FIREBASE-USER-INFO/ext-auth-chat-getStreamUserToken

Context: I've built a messaging app using Stream.io, with hard-coded user data and a placeholder token. Here's the key bit of code:

  useEffect(() => {
    async function init() {
      const chatClient = StreamChat.getInstance(apiKey)

      await chatClient.connectUser(user, chatClient.devToken(user.id))

      const channel = chatClient.channel("messaging", "war-chat", {
        image:
          "https://i.picsum.photos/id/1006/200/200.jpg?hmac=yv53p45TOMz8bY4ZXUVRMFMO0_6d5vGuoWtE2hJhxlc",
        name: "Oli",
        members: [user.id],
        //chat description
      })

      await channel.watch()

      setClient(chatClient)
    }

    init()
    if (client) return () => client.disconnectUser()
  }, [])


I have installed the 'authenticate with stream chat' extension on Firebase. This creates various cloud functions, include one which creates a new user on Stream when a new user is created on firebase.

The only thing I need to do is modify this bit of code, to integrate firebase with stream chat:

await chatClient.connectUser(user, chatClient.devToken(user.id))

I can sort the user object. but how do I call the cloud function to get the token?

CodePudding user response:

Per the source code of the getStreamUserToken Cloud Function (linked on the extension's product page), it is a Callable Cloud Function.

export const getStreamUserToken = functions.handler.https.onCall((data, context) => { /* ... */ });

Calling the Cloud Function can be done using the Firebase Client SDKs as documented with examples here in the docs. Because your cloud function resides in the europe-west2 region (and not the default us-central1 region), you will need to specify it when getting an instance of the Functions builder class:

import { getFunctions, httpsCallable } from "firebase/functions";

const functions = getFunctions(undefined, "europe-west2") // undefined is passed in so that the default app is used

const getStreamUserToken = functions.callable("ext-auth-chat-getStreamUserToken");

const streamUserToken = await getStreamUserToken();

The revoke function is called in the same way.

const revokeStreamUserToken = functions.callable("ext-auth-chat-revokeStreamUserToken");

await revokeStreamUserToken();
  • Related