Shiven Shiven - 2 months ago 19
JSON Question

Firebase Make Existing Data Unmodifiable but can write and read new data

I am starting to use Firebase for my new Project which takes in a lot of data. How do I set the rules so that:


  • Program can read all data

  • Program can write new data

  • Program cannot modify or delete existing data



This is what I have:

{
"rules": {
"users":{
".read": true,
".write": "!data.exists() && newData.exists()",
}
}
}


My data is structured like:

(name of project) -> users -> (user ID) -> data


The problem I have right now is that every single write is blocked, regardless if the new data exists or not. What do I need to change to fix this?

Answer

You forgot to add the user id in your rules. Right now nobody will be able to write after the first user has added his data. To fix this simply add a wildcard path for the user id in your rules like this:

{
  "rules": {
    "users":{
      ".read": true,
      "$userid":{
        ".write": "!data.exists() && newData.exists()"
      }
    }
  }
}