Why does Firebase trigger a child_added event for an update operation?

Viewed 108

I'm wondering about the behaviour of the Firebase Realtime database in the following situation. (Note: Since my production version has too many rules and code I've created a minimal version where I can reproduce the behaviour in case you are wondering about my strange security rules)

SDK: Firebase JavaScript SDK: 7.19.1

Code:
Stays the same for both versions

const database = firebase.database();
const allUsersRef = database.ref("users");
const myUserRef = database.ref("users/1");

allUsersRef.on("child_added", (data) => {
  console.log("child_added", data.val());
});

allUsersRef.on("child_changed", (data) => {
  console.log("child_changed", data.val());
});

allUsersRef.on("child_removed", (data) => {
  console.log("child_removed", data.val());
});

myUserRef
  .update({
    name: "John",
  })
  .then(() => {
    console.log("update success");
  })
  .catch((error) => {
    console.log("update error", error);
  });

Version 1

Security rules:

{
  "rules": {
    ".write": false,
    "users": {
      ".read": "auth !== null",
      "$userId": {
        ".write": false,
      }
    }
  }
}

Console output Console output - Version 1


Version 2

Security rules:

{
  "rules": {
    ".write": false,
    ".read": false
  }
}

Console output Console output - Version 2


In both version nothing is ever written to the Firebase database because the security rules will not allow this.

Two things I don't understand here:

  1. I know from this article that the Firebase Realtime database operations are optimistic which explains why child_added is displayed in the console even though it's never written to the database. But what I don't understand is why a child_added event is triggered and not a child_changed event because it's an update operation and not a set operation.

  2. Why is the behaviour different based on my security rules even though the Firebase operations are optimistic and in both versions nothing is written to the database? I would have expected the same console output.

1 Answers

Why does Firebase trigger a child_added event for an update operation?

From the flow in your first screenshot it looks like /users/1 doesn't exist yet, which means that node is created optimistically client-side. This happens regardless on the type of write operation you perform in your code: the behavior is based on the transformation on the database, and not on the API call.

Related