Firebase database rules: Parameters

Eduardo Elias Saleh
2 min readApr 3, 2020

--

When writing an app in firebase, the main security relies on the database rules but those are not always clear. Here I’ll dig into some data available when evaluating those rules.

Introduction

I’m assuming that you already read the doc about security and know the basics of a .rules file. You should understand what those instructions means:

// Allow read/write access on all documents to any user signed in to the application
service cloud.firestore {
match /databases/{database}/documents {
match /{document=**} {
allow read, write: if request.auth.uid != null;
}
}
}

Parameters available

What I didn’t know is that there are some data available when evaluating those rules and I’ll describe those parameters.

The first one and most common is the request. It holds the request data like authentication but, in the read, when an Id is provided, it is also on a match inside the path like the example:

match /users/{userId}/pics/{picId} {
...
allow list: if request.auth.uid == userId;
...
}

When executing an UPDATE, the new record can be accessed in the request.resource property, holding its data inside the request.resource.data, like this:

match /ids/{idId} {
...
allow create: if request.resource.data.userId == request.auth.uid;
allow update: if request.auth.uid == request.resource.data.userId;
...
}

When executing a DELETE, the deleted record can be accessed inside the resource property. NOTE: It’s not inside request.resource but a ‘root’ property resource, like this:

match /ids/{idId} {     
...
allow delete: if request.auth.uid == resource.data.userId;
...
}

This way, when creating, there won’t be a resource property, as the new record is coming from the request, the resource is inside the request property. When updating you have inside the request the new record and the root resource as the old values. When deleting you have only the old resource outside the request.

That’s it, a simple explanation where to find the resource data when writing firebase database rules.

--

--

Eduardo Elias Saleh

Brazilian, 80’s kid, Lily’s father. In love with JS, PHP, C# and Baby Yoda. Dev since 97'. Board gamer always up for an Eclipse match. We created and killed God