Search code examples
react-nativefirebase-realtime-databaseexpofirebase-security

Firebase Realtime DB: How to setup rule to only write to DB if value being passed to be written is not already stored in DB


I am looking for syntax to setup a rule in my Firebase Realtime DB to confirm that the value being passed from my app does not already exist in that particular location before writing another duplicate entry. I am passing an "ExponentPushToken" value for push notifications. This happens anonymously. That is, the write is happening without any user authentication, the DB is simply storing a list of "ExponentPushToken" like so:

{
  "users" : {
    "push_token" : {
      "auto-generated key" : "ExponentPushToken-value"
    }
  }
}

I attempted to use the following, but it still will allow the "duplicate" value to be written. I am wondering if this has anything to do with random 'auto-generated key' that is generated for each instance a value written to the DB, or if i am not thinking through this properly.

{
  "rules": {
    ".read": "false",
    ".write": "true && newData.val() !== data.child('push_token').val()",
  }
}

For context, each ExponentPushToken is a unique value for a given device that is used to open my app. The ExponentPushToken is a unique ID that is assigned to that device indefinitely and won't change ever in any case that particular device is accessing the app. The ExponentPushToken is assigned to the device indefinitely, and is written to the DB. Each time the app is opened, there is a push/set command to write that token to the DB within my app's code. I would like to setup a rule for Firebase Realtime DB to confirm the value being passed from the app to the DB does NOT get written if that value already exists. I am stuck and am finding myself having to manually parse the db to remove duplicate value to keep the DB clean and not send more than one Push Notification to app users.

Any help or direction you can provide would be greatly appreciated!

Thanks!


Solution

  • This cannot be done using firebase security rules, as they cannot search for values (that wouldn't scale). The query to check for existing values in a particular location in the database would have to be done in the app that is performing the push/writing of the value into the database.

    The app would need to query the database for values and have a condition in place to prevent the writing of duplicate values.

    An example of working code that can be implemented within the app can be found here that accomplishes the desired outcome for this specific ask/desired outcome.

    Expo and Firebase Realtime DB - Read values and confirm a particular value does not exist before writing to database