Search code examples
firebasegoogle-cloud-firestorenext.jsfirebase-securityremix.run

Using Firebase Security Rules from a web server


Do any of the Firebase Node/JS SDKs support making calls to Firestore from a node server or cloud functions (e.g. nextjs, remix) on a users behalf, respecting security rules for the authenticated user and supporting sessions for multiple simultaneous users?


Use case:

I have a mobile application with Firebase Security rules set up. I want to serve the same data from a server side web application without reimplementing the Firebase security rules on the web server and keeping them in sync.

e.g. if a user requests a post by id, and Firebase rules prevents them from having access to that specific post, I want Firebase to tell me that and for the web server to forward the 403 status to the user.


More info:

I read this:

If you are developing a Web or Node.js application that accesses Cloud Firestore on behalf of end users, use the firebase Client SDK.

Which suggests this should be possible, however my understanding is that:

  • firebase-js-sdk can only have one user authenticated at a time so would not be safe if handling async calls from multiple users at once

  • firebase-admin can be run as a specific user, but this can only be done during initializeAdminApp and again would affect all requests that are currently using the firebase-admin import

Is that correct? Are there any other ways to act on behalf of the authenticated user from a web app?

The only thing I can think of would be the REST API… https://firebase.google.com/docs/firestore/use-rest-api


Solution

  • Do any of the Firebase Node/JS SDKs support making calls to Firestore from a node server or cloud functions (e.g. nextjs, remix) on a users behalf, respecting security rules for the authenticated user and supporting sessions for multiple simultaneous users?

    No, the backend SDKs always bypass security rules. Only the web and mobile SDKs that you use inside the client app make use of authentication tokens available from the user's prior sign-in.

    You could consider using the REST API instead since it allows you to pass through a client auth token. It will be up to you to manage the transfer of that token manually.