Prevent a Permission Denied Error in Firebase from blocking a site

Assume that you have the following rule on a Firebase Realtime Database:

terminal
{
  "rules": {
    "concurrent": {
      ".read": true,
      ".write": true,
      "$uid": {
        "connected": {
          ".validate": "newData.val().matches(/^foo/)"
        }
      }
    }
  }
}

If users try to write new data that doesn't start with foo, they'll get a permission error on data validation:

terminal
Error: PERMISSION_DENIED: Permission denied...

For example, assume that a user is pushing the following data:

javascript
push(ref(db, 'concurrent'), { connected: 'bar' })

If you don't handle the error, you'll get a permission error on data validation. To prevent it, you could use then() and catch() methods because the push() function returns a Promise:

javascript
push(ref(db, 'concurrent'), { connected: 'bar' })
    .then(val  => { console.log('No errors') })
    .catch(err => { console.log('Writing permission was denied') })

On functions that don't return a Promise, such as onValue(), you can handle the error using the cancel callback function:

javascript
onValue(ref(db, 'concurrent'), snapshot => {
          
    console.log('No errors')  
            
}, error => {

    console.log('Writing permission was denied')

}) 

Hi, I'm Erik, an engineer from Barcelona. If you like the post or have any comments, say hi.