How rules are put together
Firestore security rules are written in a small language of their own. A match block names a path,
allow names the methods it covers, and the condition after if decides. Everything in this
cheat sheet is something you can use in those conditions:
rules_version = '2';
service cloud.firestore {
match /databases/{database}/documents {
function signedIn() {
return request.auth != null;
}
match /posts/{postId} {
allow get, list: if true;
allow create: if signedIn()
&& request.resource.data.authorId == request.auth.uid;
}
}
}
rules_version = '2' goes at the top of every new rules file. Collection group queries need it, and
so do recursive wildcards that match zero path segments and let inside functions. The methods are
get, list, create, update and delete;
read is short for the first two and write for the last three.
The request and resource variables
request.auth- The signed-in user, or
nullfor a visitor. Check it before reading anything inside it. request.auth.uid- The user’s Firebase user ID.
request.auth.token-
The ID token’s claims:
email,email_verified,phone_number,name,sub,firebase.sign_in_provider,firebase.identities,firebase.tenant, and any custom claims your server set, such asrole. request.method- One of
get,list,create,updateordelete. request.path- The path of the document being read or written.
request.query- For queries:
limit,offsetandorderBy, when the query sets them. request.resource.data- On writes, the document as it will be if the write succeeds: the whole document, not just the fields sent.
request.time- When the request arrived, as a timestamp. A field written with
serverTimestamp()equals it. resource.data- The stored document, before this request. There’s none on create.
resource.id,resource.__name__- The document’s ID, and its full path.
database- The database name, captured by the top
match. Use it to build paths forget().
Two checks on the token that come up often:
// Keep anonymous accounts out
allow create: if request.auth != null
&& request.auth.token.firebase.sign_in_provider != 'anonymous';
// Trust an email address only once it's verified
allow read: if request.auth.token.email_verified == true
&& request.auth.token.email.matches('.*@example[.]com');
And request.query lets you cap the size of a query. Rules check queries as a whole: a query that might
return a document the user can’t read is refused outright rather than filtered.
// Refuse queries that ask for more than 50 documents
allow list: if request.query.limit <= 50;
get(), exists(), getAfter() and existsAfter()
These four read other documents from inside a rule. Each takes a full path to one document:
get(path)- The stored document, with its fields under
.data, ornullif it doesn’t exist. exists(path)trueif the document exists.getAfter(path)- The document as it will be if the current request succeeds. For batched writes and transactions that write several documents together.
existsAfter(path)trueif the document will exist after the request.
Paths start with /databases/$(database)/documents/, and variables go inside $( ). A role kept
in a members document is the usual use:
function memberRole(orgId) {
return get(/databases/$(database)/documents/orgs/$(orgId)/members/$(request.auth.uid)).data.role;
}
match /orgs/{orgId}/projects/{projectId} {
allow read: if exists(/databases/$(database)/documents/orgs/$(orgId)/members/$(request.auth.uid));
allow delete: if memberRole(orgId) == 'admin';
}
getAfter() checks that two writes in one batch agree, such as claiming a unique username and setting it
on the profile together:
// Claiming a username: the batch must also set it on the user's profile
match /usernames/{name} {
allow create: if request.auth != null
&& getAfter(/databases/$(database)/documents/users/$(request.auth.uid)).data.username == name;
}
Each call is billed as a document read, even when the rules then refuse the request. A request may make 10 of these calls for a single document or a query, and 20 for transactions and batched writes; past that, it’s refused. Some calls are cached and don’t count. Roles in custom claims cost no reads at all.
Custom functions and let
A function takes up to seven arguments and holds a single return, optionally after up to ten
let lines. Functions can call other functions but can’t call themselves, and there are no loops. Declare
them inside the match block whose variables they use, or pass the variables in.
function canEdit(orgId) {
let member = get(/databases/$(database)/documents/orgs/$(orgId)/members/$(request.auth.uid));
let roles = ['admin', 'editor'];
return member != null && member.data.role in roles;
}
String methods
| Method | Returns | Notes |
|---|---|---|
size() | int | Length in characters |
lower(), upper() | string | Change case before comparing |
trim() | string | Removes leading and trailing spaces |
matches(re) | bool | Matches the whole string, in RE2 syntax, so no anchors are needed |
replace(re, sub) | string | Replaces every match of the regular expression |
split(re) | list | Splits on a regular expression |
toUtf8() | bytes | For limits in bytes rather than characters |
// data is request.resource.data, set with let in a function
data.title.size() <= 200 // length in characters
data.name.trim().size() > 0 // not just spaces
data.slug.matches('[a-z0-9-]{3,40}') // the whole string must match
data.email.lower().matches('.*@example[.]com')
data.email.split('@')[1] == 'example.com'
'banana'.replace('a', 'o') == 'bonono' // replaces every match
data.body.toUtf8().size() <= 10000 // size in bytes, not characters
matches, replace and split all take regular expressions, so escape a dot as
[.] or \\. when you mean a literal one.
Type checks and conversions
is checks a value’s type. The types are bool, int, float,
number (int or float), string, list, map,
timestamp, duration, path and latlng. int() and
float() convert strings and numbers; a string that isn’t a number makes the rule fail, which denies the
request.
// data is request.resource.data
data.title is string
data.count is int && data.count >= 0
data.price is number // int or float
data.tags is list
data.settings is map
data.createdAt is timestamp
int('42') == 42
float('2.5') == 2.5
Lists
size()- Number of items.
x in listtrueif the list holdsx.hasAll(list)- Every item given is in this list.
hasAny(list)- At least one item given is in this list.
hasOnly(list)- Every item in this list is one of those given, ignoring repeats.
concat(list),removeAll(list)- A new list with items added, or with every copy of the given items removed.
join(separator)- A string of the items.
toSet()- A set of the unique items.
list[i]- The item at position
i, counting from 0.
// data is request.resource.data
data.tags.size() <= 5
data.tags.hasOnly(['news', 'blog', 'docs']) // nothing outside this list
data.tags.toSet().size() == data.tags.size() // no duplicates
request.auth.token.get('roles', []).hasAny(['admin', 'editor'])
'admin' in request.auth.token.get('roles', [])
data.members[0] == request.auth.uid
Maps and diff()
Document data is a map, so these are the methods that check what a write contains. keys() and
values() return lists, get(key, default) reads a field that may be missing (a list of keys
reads a nested field), and key in map checks a field is there.
a.diff(b) compares two maps. On an update, compare the new document with the stored one:
addedKeys() are fields the write adds, removedKeys() fields it removes,
changedKeys() fields whose value changes, unchangedKeys() the rest, and
affectedKeys() everything added, removed or changed. Each returns a set.
// data is request.resource.data
// On create: required fields, and nothing else
data.keys().hasAll(['title', 'authorId', 'createdAt'])
data.keys().hasOnly(['title', 'body', 'authorId', 'createdAt'])
// Optional fields with a default
data.get('body', '') is string
data.get(['settings', 'theme'], 'light') in ['light', 'dark']
// On update: which fields changed
data.diff(resource.data).affectedKeys().hasOnly(['title', 'body'])
data.diff(resource.data).unchangedKeys().hasAll(['authorId', 'createdAt'])
The affectedKeys().hasOnly(…) line is the most useful check in Firestore rules: it lists the only fields an
update may touch, so users can’t change the author, the owner or a role on a document they’re allowed to edit.
Sets
Sets come from toSet() and from diff(). They have size(),
hasAll(), hasAny() and hasOnly(), which accept a set or a list, plus
union(), intersection() and difference().
Timestamps and durations
request.time- Now, as the server saw it.
timestamp.date(year, month, day)- A timestamp for that date.
timestamp.value(millis)- A timestamp from milliseconds since 1970.
duration.value(n, unit)- A length of time. Units are
w,d,h,m,s,msandns. duration.time(h, m, s, ns)- A duration from hours, minutes, seconds and nanoseconds.
- Timestamp methods
-
year(),month(),day(),hours(),minutes(),seconds(),nanos(),dayOfWeek()(1 to 7),dayOfYear(),date(),time()andtoMillis().
// Written with serverTimestamp(), so it equals the request time
request.resource.data.createdAt == request.time
// Edits allowed for one hour after creation
request.time < resource.data.createdAt + duration.value(1, 'h')
// Open until a date (how test mode rules work)
request.time < timestamp.date(2026, 12, 1)
// Only documents dated this year
request.resource.data.publishedAt.year() == request.time.year()
Math, hashing and the rest
- math:
math.abs,ceil,floor,round,sqrt,pow,isInfiniteandisNaN. - hashing:
hashing.sha256,md5,crc32andcrc32c, each taking a string or bytes. - latlng:
latlng.value(lat, lng)for geopoints. - path:
path('…')turns a string into a path; a path’sbind()fills in$( )variables from a map. - debug:
debug(value)logs a value tofirestore-debug.login the emulator, and does nothing in production.
Operators
Conditions combine with &&, || and !. && and
|| stop as soon as the answer is known, so put request.auth != null first and a
get() last: the read only happens when it’s needed. The ternary condition ? a : b works too,
as do ==, !=, <, <=, >, >=,
+, -, *, / and %.
When a condition hits an error, such as reading a field that isn’t there or calling .data on a missing
document, that condition is false and, unless another rule allows the request, it’s denied. That’s safe, but it makes
a typo look like a permissions problem.
Limits
- Rules file
- 256 KB of source, and 250 KB once compiled.
- Expressions per request
- 1,000.
- Document reads from rules
- 10 per single-document request or query, 20 per transaction or batched write.
- Function calls
- Nested up to 20 deep; no recursion.
- Function arguments, let lines
- 7 arguments, 10
letlines per function. - Nested match blocks
- 10 deep, with up to 20 path variables.
These come from the Firestore quotas page. One Firebase page gives the call depth as 10; the quotas table says 20.
Write and check rules faster
The free Firestore Rules Generator writes rules from a grid of who may do what, using the functions above for ownership, roles, field lists, types, sizes and server timestamps, plus a test file for the emulator. Its checker reads the rules you already have and flags open access, test mode dates, recursive wildcards that override stricter rules, and updates that let users change fields they shouldn’t. It runs in your browser.
If your roles live in custom claims, paste an ID token into the JWT
decoder to see exactly what request.auth.token will hold.