Search code examples
firebase-realtime-databasefirebase-security

Firebase rules enable only for one node


I am using Firebase Realtime Database and would like to set a rule only for one node ("Devices/{number}"). For all other paths I would like for the rules to stay read, write: true.

This is what I tried:

{
  "rules": {
    "Devices": {
      ".write": "!data.exists()"
    },
  }
}

However this doesn't achieve what I want because it doesn't allow write/read on any other path. And if I try this:

{
  "rules": {
    ".read": true,
    ".write": true,
    "Devices": {
      ".write": "!data.exists()"
    },
  }
}

Then the rule under devices does nothing and you can delete data under devices.

How could I solve this?


Solution

  • You're looking for a wildcard rule, like this:

    {
      "rules": {
        "Devices": {
          ".write": "!data.exists()"
        },
        "$other": {
          ".read": true,
          ".write": true
        },
      }
    }
    

    This applies the !data.exists() rule to Devices and true to all other top-level nodes.


    If you want to allow users to only add a specific device under Devices, and not replace the entire node, you should use a wildcard for that too:

    {
      "rules": {
        "Devices": {
          "$deviceId": {
            ".write": "!data.exists()"
          }
        },
        "$other": {
          ".read": true,
          ".write": true
        },
      }
    }