Search code examples
firebasefirebase-realtime-databasefirebase-security

Firebase realtime database rules to edit only existing fields


My database:

enter image description here

I want to set firebase rules where user can update existing tags value but not create new tagsenter image description here


Solution

  • If you only want the user to be able to update existing properties, and not create any new properties, that'd be:

    {
      "rules": {
        "$uid": {
          ".write": "auth.uid === $uid"
          "$property": {
            ".validate": "data.exists()"
          }
        }
      }
    }
    

    So this rule validates that a property can only be written if there's already data for that property in the database.


    If you only want the user to be able to write a name and address, and not any other properties, that'd be:

    {
      "rules": {
        "$uid": {
          ".write": "auth.uid === $uid"
          "name": {
            ".validate": true
          },
          "address": {
            ".validate": true
          },
          "$other": {
            ".validate": false
          }
        }
      }
    }
    

    In the above rules we allow writing the named name and address properties, and reject any other properties with a wildcard capture rule.