Search code examples
node.jsreactjsfirebasegoogle-cloud-firestorefirebase-admin

How can you use firestore's onSnapshot listener when the firestore method is being called from node.js?


I have an admin site that has a react frontend, using redux actions, with a node.js app as the server which uses firebase-admin to do the work.

I want to use firestore's onsnapshot listener. but im not sure how this works within the HTTP protocol?

I can't use the firebase-admin from my frontend app, and i cant create realtime DB functionality from the backend within HTTP protocol.

The goal: to set snapshot listeners on my collections from rreact frontend without having to go through multiple authentication processes, considering ive got a separate auth system for admins with my express api.

Is there a solution for this?

EDIT: my client app is currently initialized with firebase web app config data, but because im authenticating admins with my own express server, the firebase web SDK hasnt authenticated with firebase, so i dont have permission for the data i need. im not sure if i need a service account, or a web app config with extra setup or what


Solution

  • My recommendation is to integrate the Firebase JS SDK into your client app using signInWithCustomToken(). It's not too complicated to do. Though I suppose that depends a lot on how your current auth setup works.

    The general idea is this: Send auth request to your auth service.
    Process the request like normal.
    Evaluate if the user should have access to Firebase.
    If they should, use firebase-admin to create a custom token and send it back to the user.
    Use the token on the client to authenticate with Firebase.auth

    You should make sure to have Firestore rules to allow admin users to access the data you need.

    As an alternative that doesn't use the Firebase client SDK, you could have a long-running node process that opens an onSnapshot. Your react app could receive data from it using either Server-Sent Events or through a WebSocket