Chris
Chris

Reputation: 7

Why am I not able to write to my firebase database?

I am using firebase and I am getting a permission denied error when I try to write to my database. This is what I have as my rules:

{
  "rules": {
    "foo": {
      ".read": true,
      ".write": true
    }
  }
}

This is the code to write to the database:

function writeUserData(userId, name, email, imageUrl) {
  firebase.database().ref('users/' + userId).set({
    username: name,
    email: email,
    profile_picture : imageUrl
  });
} 

Why am I not able to write to my database?

Upvotes: 0

Views: 629

Answers (1)

André Kool
André Kool

Reputation: 4968

In your current rules you allow writing to the "foo" node of your database but you are trying to write to "users". Because you haven't set a rule for "users", firebase falls back on the default rule which is false.

If you want to be able to write to users you will have to change your rules to this:

{
  "rules": {
    "users": {
      ".read": true,
      ".write": true
    }
  }
}

Just remember this allows everyone (even unauthenticated users) to read/write to that location. For a more secure option you could limit it so users can only read/write their own data:

{
  "rules": {
    "users": {
      "$user_id": {
        // grants write access to the owner of this user account
        // whose uid must exactly match the key ($user_id)
        ".write": "$user_id === auth.uid",
        ".read": "$user_id === auth.uid"
      }
    }
  }
}

Example from the firebase docs.

Upvotes: 2

Related Questions