In Firestore Security Rules for a classroom app, when should a teacher check read a custom claim from request.auth.token rather than call get() on a roles document?
answer
- token data versus a database read
- freshness against cost
- ten and twenty per request
- billed even when denied
- per-class membership
basics
~20 sUse a custom claim for a coarse, slow-changing role such as teacher: it costs no read but stays stale until a new ID token. Use get() or exists() for live per-class membership, paying a billed read and a capped lookup count.
solid answer
~50 sA custom claim travels inside the ID token, so `request.auth.token.teacher == true` is free: no document read, no billing, nothing counted against lookup limits. Its cost is freshness, because a changed claim reaches rules only when the client gets a new ID token, by signing in again, by the hourly refresh, or by a forced refresh. A `get()` or `exists()` on something like `/classes/$(classId)/teachers/$(request.auth.uid)` is always current and can express relationships a token cannot hold, such as which of many classes this teacher teaches. Each lookup is a billed document read, even when the rule then denies, and lookups are capped: 10 per single-document request or query, 20 per batched write, transaction or multi-document read, with 10 still applying to each operation. Exceeding a cap is a permission denial. So: claims for coarse roles, lookups for fine-grained or fast-changing access.
go deeper
Know both options exist: a custom claim read from request.auth.token, and get() or exists() reading another document by a full path.
Explain the trade: claims are free but only as fresh as the ID token, lookups are current but billed and limited to 10 or 20 per request.
Diagnose a batch that fails with PERMISSION_DENIED from lookup limits, order checks for short-circuiting, and pick claims or lookups per access rule.
Set the team's convention for where roles live, weighing revocation speed, read cost at scale and how much authorization the rules should carry.
## Two places a rule can learn who someone is A teacher-only rule needs a fact the request path does not carry: *is this user a teacher, and of which class?* Firestore Security Rules can get that fact from two places. - **The ID token.** `request.auth.token` is a map of the signed-in user's ID token claims. Besides standard entries such as `email`, `email_verified` and `firebase.sign_in_provider`, it contains any **custom claims** your backend attached to the user, for example `teacher: true` or `role: 'admin'`. - **Another document.** `get(path)` returns a document so the rule can test its `data`; `exists(path)` returns whether one exists. Both take a **fully specified path**, with variables escaped through `$(...)`: `/databases/$(database)/documents/classes/$(classId)/teachers/$(request.auth.uid)`. How claims are set and refreshed belongs to Firebase Authentication; the question here is what each choice costs the rules. ## What a claim costs | | Custom claim | `get()` / `exists()` | |---|---|---| | Document read billed | no | yes, even when the rule denies | | Counts toward lookup limits | no | yes | | Freshness | as old as the client's ID token | current at evaluation time | | Fits | a few coarse roles per user | relationships, lists, fast-changing access | The claim's weakness is **staleness**. A changed claim reaches rules only when the client presents a new ID token: after signing in again, when the hour-long ID token is refreshed, or when the app forces a refresh with `getIdToken(true)`. A teacher whose role was removed keeps it in rules until then. Claims are also meant to be small and are for access control, not profile data, so "teacher of classes 7A, 7B and 9C" does not belong in one. ## What a lookup costs Every `get()`, `exists()` or `getAfter()` reads a document and is **billed as a read**, even when the rule ends up denying the request. Lookups are also capped per evaluation: 1. **10** for a single-document request or a query. 2. **20** for a multi-document read, a transaction or a batched write, and the cap of 10 still applies to **each** operation inside it. 3. Exceeding either cap fails the request with a **permission denied** error, the same error a false condition gives. 4. Some lookups may be cached, and cached ones do not count, but the documentation does not promise which, so design for the uncached count. The documentation's arithmetic: a batch of 3 writes whose rules make 2 lookups each uses 2 of each write's 10 and 6 of the batch's 20. ## A rule that uses both ```plaintext rules_version = '2'; service cloud.firestore { match /databases/{database}/documents { match /classes/{classId}/grades/{gradeId} { function isSchoolAdmin() { return request.auth.token.get('role', '') == 'admin'; } function teachesClass() { return exists(/databases/$(database)/documents/classes/$(classId)/teachers/$(request.auth.uid)); } allow write: if request.auth != null && (isSchoolAdmin() || teachesClass()); } } } ``` The order is deliberate. `&&` and `||` short-circuit, so the free claim check runs first and the billed `exists()` runs only when the user is not an admin. Writing the lookup into a `let` binding instead would evaluate it every time. The claim is read with `get('role', '')` because reading a claim the token does not have is an error, and an error denies. ## The production diagnosis A teacher records a whole class's results in one `WriteBatch`. Single grade writes succeed, but the batch fails with `PERMISSION_DENIED`. Suppose the write rule calls `teachesClass()` and also checks enrolment with `exists()` on each student's document, two lookups per write. Thirty writes ask for far more than the batch's 20 (minus whatever the cache absorbs), so the whole batch is denied although every write would pass alone. The fixes: - move the coarse check into a claim so it costs no lookup; - split the batch into chunks whose lookups fit under 20; - or move the bulk operation to server code, which bypasses rules. ## Lookups in Cloud Storage rules Storage rules can read Firestore with `firestore.get()` and `firestore.exists()`. They are tighter: **no more than two** Firestore documents per rules evaluation, only the **default** database when several exist, and the project must grant the permission the console or CLI prompts for when you first deploy such rules. Those reads count toward Firestore billing like any other. ## Choosing - Coarse, rarely changing roles (teacher, admin): claim. - Membership in one of many groups, or access that must vanish immediately: lookup. - Both at once: claim first, lookup second, short-circuited. - Large batches against lookup-heavy rules: redesign before they hit the cap in production.
- A school removes a teacher's role claim, but she can still write grades for a while; why?Rules read claims from the ID token the client presents. A changed claim appears only in a newly issued token, after sign-in, the hourly refresh, or a forced `getIdToken(true)`. Until then the old token still says teacher. If removal must take effect at once, check a document with `exists()` instead, or combine the claim with a lookup.
- Why might a rule that calls get() still cost a read when it denies the request?The lookup itself is a document read executed during evaluation, and Firestore bills it whether or not the final decision is allow. Putting cheap checks such as `request.auth != null` and claims before the lookup, joined with `&&` or `||`, lets short-circuiting skip the read when the answer is already known.
- How does getAfter() differ from get() in a write rule?`get()` reads a document as currently stored. `getAfter()` reads it as it would be after the current batch or transaction is applied but before it commits. That lets a rule require related writes to happen together, for example that updating a grade also updates the class summary in the same batch. It counts toward the same lookup limits.
- Custom claims update in rules the moment the backend changes them.
- A get() in a rule is free because rules run on Firebase's servers.
- Lookups that end in a denied request are not billed.
- A batch of many writes gets 10 lookups for every write with no overall cap.
- Binding a lookup to a let variable avoids its read when the result goes unused.