How I Troubleshot Firebase Firestore Permission Denied Errors in React Native
By Jainil Pandya — Co-Founder & Lead Developer, IAMISHAAN LLC
Firebase provides a powerful backend platform for mobile application development. Its authentication, cloud database and serverless functions allow developers to build scalable applications without maintaining traditional backend infrastructure.
However, configuring database security becomes increasingly important as an application grows.
While developing iTTMM, a shared expense management application for iOS and Android, I encountered several Firebase Firestore permission-denied errors involving group expenses, balance calculations, real-time listeners, user presence and administrative functionality.
This article shares my development experience, explains common causes of Firestore permission errors and provides practical examples for troubleshooting them securely.
1. My Application Development Environment
iTTMM uses the following technologies:
TechnologyPurposeReact NativeCross-platform mobile developmentExpoApplication development and build infrastructureTypeScriptApplication logicFirebase AuthenticationUser authenticationCloud FirestoreCloud databaseFirebase Cloud FunctionsBackend operationsFirebase Security RulesDatabase access controlRevenueCatSubscription management
The application manages shared expenses, friends, groups, settlements and user-related information.
Because this information can contain sensitive financial and personal records, database security is an essential part of the application architecture.
2. Understanding the Permission Denied Error
One of the most common Firestore errors encountered during development is:
FirebaseError: [code=permission-denied]:
Missing or insufficient permissions.This error generally indicates that Firestore rejected a requested operation because the applicable security requirements were not satisfied.
The rejected operation could involve:
Reading a document.
Querying a collection.
Creating a document.
Updating existing information.
Deleting a document.
Establishing a real-time listener.
A permission-denied error does not necessarily indicate that Firebase is incorrectly configured.
In many cases, Firestore is correctly protecting information that the requesting user is not authorized to access.
The developer's responsibility is to determine whether the requested operation should be permitted and, if so, configure the application and security rules appropriately.
3. Understanding the iTTMM Database Structure
As iTTMM developed, its database included collections and subcollections for different application features.
A simplified representation of relevant paths is:
Firestore
│
├── users
│ └── {userId}
│ ├── blocked
│ │ └── {blockedUserId}
│ └── meta
│ └── ai_memory
│
├── groups
│ └── {groupId}
│ ├── members
│ ├── expenses
│ ├── balances
│ ├── messages
│ └── presence
│
├── friends
├── friendRequests
├── reports
├── notifications
└── plansEach collection serves a different purpose and may require different access permissions.
For example, a user should generally be able to access their own profile, but that does not mean they should have unrestricted access to every other user's private information.
Similarly, membership in one expense group should not automatically provide access to unrelated groups.
The database structure above is simplified for educational purposes.
4. Check Firebase Authentication First
Before modifying Firestore security rules, confirm that the application has an authenticated user.
For example:
import { getAuth } from "firebase/auth";
const auth = getAuth();
const user = auth.currentUser;
if (!user) {
console.log("No authenticated user");
} else {
console.log("Authenticated user available");
}A common Firestore security condition is:
request.auth != nullIf the application attempts to access protected information before Firebase Authentication has finished initializing, Firestore may reject the request.
This can happen when:
The application starts.
A user signs in.
A user signs out.
The application restores an existing session.
A component creates a listener before authentication is ready.
Developers should distinguish between authentication initialization and a genuinely signed-out state.
Avoid assuming that auth.currentUser will always be immediately available during application startup.
5. Understanding Firestore Security Rules
Firestore security rules define which client requests are allowed.
A basic example is:
rules_version = '2';
service cloud.firestore {
match /databases/{database}/documents {
function isSignedIn() {
return request.auth != null;
}
match /users/{userId} {
allow get: if isSignedIn()
&& request.auth.uid == userId;
}
}
}This example permits an authenticated user to retrieve their own user document.
It does not permit unrestricted access to other user documents or authorize writes.
The example is intentionally limited. A complete application may require additional permissions for profile updates, friend discovery and other features.
Those permissions should be designed according to the application's actual requirements.
6. Real Development Issue: Collection Group Queries
During iTTMM development in March 2026, I encountered permission errors while retrieving expense and balance information.
The application logs included:
BALANCE QUERY permission-denied
Missing or insufficient permissions.The application also used collection group queries to retrieve information from subcollections across multiple groups.
For example:
import {
collectionGroup,
query,
where
} from "firebase/firestore";
const balanceQuery = query(
collectionGroup(db, "balances"),
where("uid", "==", user.uid)
);A collection group query searches collections with the same name across different document paths.
This is useful when an application needs to display a user's balances from multiple groups on a single dashboard.
However, collection group queries require compatible Firestore security rules.
A rule that permits access to one specific group path may not be sufficient for a query across every collection with the same name.
Example collection group rule
match /{path=**}/balances/{balanceId} {
allow read: if request.auth != null
&& resource.data.uid == request.auth.uid;
}This example permits users to read balance documents associated with their own authenticated user ID.
The corresponding client query must constrain results appropriately:
where("uid", "==", user.uid)This example assumes that every matching balance document has a trusted uid field and that the application prevents unauthorized changes to that field.
Because a recursive wildcard can match collections at multiple locations, review every matching collection before deploying such a rule.
7. Firestore Security Rules Are Not Filters
One of the most important lessons when working with Firestore is that security rules do not automatically filter unauthorized documents from query results.
Consider a collection containing expense documents belonging to different users.
An unrestricted query may look like this:
const expensesQuery = query(
collectionGroup(db, "expenses")
);If the security rules permit users to access only expenses in which they participate, Firestore may reject the entire query.
A more appropriate query for that access model could be:
const expensesQuery = query(
collectionGroup(db, "expenses"),
where(
"participants",
"array-contains",
user.uid
)
);An illustrative matching rule is:
match /{path=**}/expenses/{expenseId} {
allow read: if request.auth != null
&& request.auth.uid
in resource.data.participants;
}The query and security rules must work together.
This example assumes that the participants array is maintained securely and that participant-based access is appropriate for the application.
Applications that also require active group membership must enforce that requirement through their authorization design.
Never weaken security rules simply because a broad query is being rejected.
8. Permission Errors Versus Missing Indexes
Another issue encountered during iTTMM development involved Firestore indexes.
After investigating expense queries, the application reported a different error:
failed-preconditionThe error indicated that a collection group index was required for an expense query involving the participants field.
This is different from a permission-denied error.
Error codeTypical meaningpermission-deniedThe requested operation is not authorizedfailed-preconditionA required condition, such as an index, is missingunauthenticatedValid authentication credentials are missingunavailableThe service is temporarily unavailablenot-foundThe requested resource does not exist
When Firestore reports that a query requires an index, the error message often provides a link for creating the required index in the Firebase Console.
Review the requested collection, fields and index scope before creating it.
Wait until the index becomes available before testing the query again.
Creating an index does not grant database permissions. Security rules must still authorize the operation.
9. Real Development Issue: Incorrect Document Fields
Another issue investigated during iTTMM development involved direct expense groups.
The application used a security helper to determine whether a user was authorized to access a group.
The helper expected participant information under a particular field name, while the stored group document used a different field name.
This type of mismatch can cause an authorized user to be rejected because the security rule evaluates a field that does not contain the expected information.
For example, consider the following illustrative group document:
{
"name": "Weekend Trip",
"membersArray": [
"user-a",
"user-b"
]
}If a security rule checks a field named participants instead of membersArray, the authorization condition will not behave as intended.
Developers should verify:
The actual Firestore document structure.
Field names and capitalization.
Whether values are strings, arrays or maps.
Whether membership is stored in a document or subcollection.
Whether older documents follow the same schema.
Security rules and application data models must remain consistent.
When changing the database schema, consider existing documents and migration requirements.
10. Implementing Group Membership Permissions
Group-based applications often need to restrict information to authorized members.
An illustrative membership-based rule is:
function isSignedIn() {
return request.auth != null;
}
function isGroupMember(groupId) {
return isSignedIn()
&& exists(
/databases/$(database)/documents/groups/$(groupId)/members/$(request.auth.uid)
);
}
match /groups/{groupId} {
allow get: if isGroupMember(groupId);
match /expenses/{expenseId} {
allow read: if isGroupMember(groupId);
}
}This example checks whether a membership document exists for the authenticated user.
It assumes that membership documents are created and maintained through trusted operations.
If the application retains archived or inactive membership documents, checking document existence alone is insufficient.
An application may also need to verify membership status:
function isActiveGroupMember(groupId) {
return isGroupMember(groupId)
&& get(
/databases/$(database)/documents/groups/$(groupId)/members/$(request.auth.uid)
).data.active == true;
}The correct rule depends on the application's membership data model.
For iTTMM, group ownership, administrator roles, active membership and archived members are important considerations when designing access permissions.
11. Implementing Administrator Permissions
As iTTMM expanded, administrative features became necessary for managing reported content and blocked users.
Administrator permissions require particular care because they may provide access to information that ordinary users should not be able to retrieve.
A role-based approach can use a trusted role field in the user's profile.
For example:
function isAdmin() {
return request.auth != null
&& get(
/databases/$(database)/documents/users/$(request.auth.uid)
).data.role == "admin";
}This helper checks whether the authenticated user's profile contains the administrator role.
However, the approach is secure only if ordinary users cannot assign or modify their own administrator role.
An alternative approach uses Firebase Authentication custom claims:
function isAdmin() {
return request.auth != null
&& request.auth.token.admin == true;
}Custom claims should be assigned through a trusted backend using the Firebase Admin SDK.
The two approaches represent different authorization designs. Developers should select and consistently implement the model appropriate for their application.
12. Protecting User Profile Fields
Applications often allow users to update their display names, profile pictures and preferences.
However, sensitive fields such as administrator roles, subscription plans and verified account status should not be freely editable by the client.
An illustrative rule using an explicit field allowlist is:
match /users/{userId} {
allow get: if request.auth != null
&& request.auth.uid == userId;
allow update: if request.auth != null
&& request.auth.uid == userId
&& request.resource.data
.diff(resource.data)
.affectedKeys()
.hasOnly([
"name",
"avatar",
"currency"
]);
}This example permits changes only to the listed profile fields.
It does not permit the user to modify fields such as:
role
plan
subscriptionActive
phoneVerified
Production implementations should also validate field types, lengths and permitted values.
Profile creation and other necessary operations require their own carefully designed permissions.
13. Managing Blocked Users Securely
User blocking is an important feature in applications that support communication and social interactions.
A possible blocked-user database structure is:
users/{userId}/blocked/{blockedUserId}An illustrative access rule is:
match /users/{userId}/blocked/{blockedUserId} {
allow read: if request.auth != null
&& (
request.auth.uid == userId
|| isAdmin()
);
allow create, delete:
if request.auth != null
&& request.auth.uid == userId;
}This example allows users to manage their own blocked-user records and permits authorized administrators to review them.
It does not grant administrators unrestricted write access.
A production implementation should additionally validate new records and restrict access according to the application's privacy and moderation requirements.
Blocking records alone do not automatically prevent messaging or friend requests. The corresponding application and backend operations must enforce the blocking relationship.
14. Managing Reported Messages and Users
Applications with user-generated content may provide reporting functionality for inappropriate messages or user behavior.
A simplified report document could look like this:
{
"type": "message",
"reason": "Inappropriate content",
"reporterUid": "user-a",
"reportedUid": "user-b",
"status": "pending"
}An illustrative rule for report submission and administrative review is:
match /reports/{reportId} {
allow create: if request.auth != null
&& request.resource.data.keys().hasAll([
"type",
"reason",
"reporterUid",
"reportedUid",
"status"
])
&& request.resource.data.keys().hasOnly([
"type",
"reason",
"reporterUid",
"reportedUid",
"status"
])
&& request.resource.data.reporterUid
== request.auth.uid
&& request.resource.data.type
in ["message", "user"]
&& request.resource.data.reason is string
&& request.resource.data.reason.size() > 0
&& request.resource.data.reason.size() <= 1000
&& request.resource.data.reportedUid is string
&& request.resource.data.status == "pending";
allow read: if isAdmin();
allow update: if isAdmin()
&& request.resource.data
.diff(resource.data)
.affectedKeys()
.hasOnly(["status"])
&& request.resource.data.status
in ["pending", "reviewed", "resolved"];
}This example restricts report creation to authenticated users, prevents users from submitting reports under another person's identity and limits administrative updates to the report status.
The example does not verify that the reported message or user exists. A complete implementation should validate referenced content, consider rate limiting, maintain moderation audit records and enforce appropriate data retention policies.
These rules are educational examples rather than a reproduction of iTTMM's complete production security configuration.
15. Real Development Issue: Permission Errors During Logout
During iTTMM development, I also encountered permission-denied errors after signing out of the application.
One observed error involved an active AI memory listener:
AI MEMORY ERROR permission-denied
Missing or insufficient permissions.Other investigations involved expense, balance and presence listeners.
Firestore real-time listeners continue receiving updates until they are unsubscribed or otherwise terminated.
If Firebase Authentication signs out the user while a protected listener remains active, subsequent requests may no longer satisfy the security rules.
This can produce permission-denied errors even when the database rules are correctly configured.
Example listener cleanup
import { useEffect } from "react";
import {
doc,
onSnapshot
} from "firebase/firestore";
useEffect(() => {
if (!user?.uid) {
return;
}
let active = true;
const reference = doc(
db,
"users",
user.uid
);
const unsubscribe = onSnapshot(
reference,
(snapshot) => {
if (!active) return;
setProfile(snapshot.data());
},
(error) => {
if (!active) return;
if (
error.code === "permission-denied"
&& !auth.currentUser
) {
return;
}
console.error(
"Profile listener error:",
error.code
);
}
);
return () => {
active = false;
unsubscribe();
};
}, [user?.uid]);This example creates a listener only when a user ID is available and unsubscribes when the component is removed or the authenticated user changes.
The authentication check in the error callback handles an expected logout-related race condition.
It should not be used to suppress genuine authorization failures while a user is signed in.
16. Cleaning Up Listeners Before Signing Out
For applications with multiple shared listeners, a centralized cleanup mechanism can help prevent authentication-related errors.
An illustrative logout workflow is:
async function logout() {
cleanupExpenseListeners();
cleanupBalanceListeners();
cleanupPresenceListeners();
cleanupAIMemory();
await signOut(auth);
clearLocalUserState();
}The cleanup functions represent application-specific implementations that unsubscribe existing listeners.
If the application needs to perform a final authenticated operation, such as updating an online presence record, that operation should be attempted before authentication is removed.
Logout handling should also clear user-specific cached state so that information from the previous account is not displayed after another user signs in.
The exact sequence depends on the application's authentication and state-management architecture.
17. Firebase Cloud Functions and Security Rules
iTTMM uses Firebase Cloud Functions for backend operations.
An important distinction is that Firestore requests made through the Firebase Admin SDK are not evaluated against client Firestore security rules.
This means that backend operations must implement their own authentication and authorization checks.
For example:
import {
onCall,
HttpsError
} from "firebase-functions/v2/https";
export const protectedOperation = onCall(
async (request) => {
if (!request.auth) {
throw new HttpsError(
"unauthenticated",
"Authentication required."
);
}
if (
request.auth.token.admin !== true
) {
throw new HttpsError(
"permission-denied",
"Administrator access required."
);
}
// Validate input.
// Perform authorized backend work.
return {
success: true
};
}
);This example uses administrator custom claims.
For applications using a database-based role system, the backend should securely retrieve and validate the appropriate role instead.
A callable function should never assume that a request is authorized simply because it was initiated by the application's user interface.
18. Avoid Dangerous Security Rule Shortcuts
When troubleshooting permission errors, it may be tempting to temporarily allow unrestricted access.
For example:
allow read, write: if true;This rule can expose information to unauthorized users and should not be deployed to a production database.
Another potentially dangerous shortcut is:
allow read, write:
if request.auth != null;Although this requires authentication, it may still allow every authenticated user to access information belonging to other users.
Authentication establishes identity. Authorization determines what that identity is permitted to access.
Also remember that overlapping Firestore rules can grant access if any matching allow condition evaluates to true.
A restrictive rule does not cancel a broader permissive rule that matches the same operation.
The appropriate solution is to identify the exact operation and implement the minimum necessary permissions.
19. Testing Firestore Security Rules
Security rules should be tested before deploying changes to a production application.
The Firebase Local Emulator Suite provides a development environment for testing Firebase services.
To initialize emulator configuration:
firebase init emulatorsTo start the Firestore emulator:
firebase emulators:start --only firestoreFor automated security rule tests, developers can use the Firebase Rules Unit Testing library.
A useful testing matrix includes:
Test scenarioExpected resultUser reads own profileAllowedUser reads another private profileDeniedUser updates permitted profile fieldsAllowedUser changes own administrator roleDeniedUser changes own verified subscription statusDeniedActive member reads group expensesAllowedNonmember reads protected group expensesDeniedArchived member reads active-only group dataDeniedUser creates a valid reportAllowedUser submits a report using another identityDeniedOrdinary user reads administrative reportsDeniedAuthorized administrator reviews reportsAllowedSigned-out user reads private informationDenied
The expected results should reflect the application's actual security policy.
Both successful and rejected operations should be tested.
A rejected unauthorized operation is a successful security test.
20. Deploying Updated Firestore Rules
After reviewing and testing the security rules, they can be deployed using the Firebase CLI.
First, verify the intended Firebase project:
firebase useReview the local rules file and the Firestore configuration in firebase.json.
To deploy Firestore security rules:
firebase deploy --only firestore:rulesFor a specific project, an explicit project argument can be used:
firebase deploy \
--only firestore:rules \
--project YOUR_PROJECT_IDReplace the placeholder with the intended Firebase project identifier.
Keep security rules under version control and review changes before deploying them.
After deployment, test the relevant operations using ordinary user accounts as well as authorized administrator accounts.
21. My Firestore Troubleshooting Checklist
Based on my iTTMM development experience, the following sequence provides a useful starting point:
Identify the exact Firestore error code.
Determine whether the failing operation is a read, write or listener.
Confirm Firebase Authentication has initialized.
Verify the authenticated user identity.
Identify the exact collection or document path.
Inspect the actual Firestore document fields.
Review applicable security rules.
Check whether the query satisfies the authorization conditions.
Investigate missing indexes separately.
Review group membership and administrator roles.
Check listener cleanup during logout.
Test the proposed changes in a development environment.
Deploy only the necessary security changes.
Perform regression testing with different user roles.
This approach helps narrow down the problem without unnecessarily weakening database security.
22. Frequently Asked Questions
Why does Firestore return missing or insufficient permissions?
The requested operation may not satisfy the applicable security rules. Possible causes include missing authentication, incorrect document paths, mismatched query constraints or insufficient user privileges.
Why does Firestore work for an administrator but not a regular user?
The administrator may have additional permissions. Review whether the regular user's requested operation should be authorized under the application's security policy.
Does signing in automatically grant Firestore access?
No. Authentication establishes the user's identity, but Firestore security rules determine which operations that user can perform.
Why do I receive permission errors after logout?
An active Firestore listener or pending operation may still be accessing protected information after authentication has been removed. Review listener cleanup and logout sequencing.
Can I fix permission errors by making the database public?
Making the database public may remove certain permission errors, but it can expose sensitive information. It is not an appropriate production troubleshooting strategy.
Does creating a Firestore index fix permission-denied errors?
No. Indexes support query execution, while security rules control authorization. Both requirements must be satisfied independently.
Do Firebase Cloud Functions bypass Firestore security rules?
Firestore operations performed through the Firebase Admin SDK bypass client security rules. Backend functions must therefore enforce their own authentication, authorization and input validation.
Can users assign their own administrator roles?
They should not be permitted to do so. Administrator roles and other sensitive access-control fields must be managed through trusted backend operations.
Official Developer Resources
Conclusion
Firebase Firestore permission-denied errors can initially appear difficult to diagnose, particularly in applications that use real-time listeners, multiple user roles and complex database structures.
My experience developing iTTMM demonstrated the importance of investigating authentication, database paths, query constraints, document fields and listener lifecycles before modifying security rules.
The objective is not simply to eliminate permission errors. It is to ensure that legitimate operations succeed while unauthorized operations remain blocked.
A carefully designed authorization model helps protect application users, maintain reliable functionality and support future development.
I hope these examples help other React Native and Firebase developers troubleshoot similar challenges.
About the Author
Jainil Pandya is the Co-Founder and Lead Developer of IAMISHAAN LLC and develops mobile applications including iTTMM and iDET.
The IAMISHAAN Developer Corner shares practical technical experiences, development challenges and lessons learned while building digital products.
Learn more about iTTMM and IAMISHAAN.
IAMISHAAN LLC — Solution for Every Problem.
Editorial note: This article is based on actual iTTMM development investigations conducted during 2026. Error messages have been shortened where appropriate. Security rules, database structures and code examples have been simplified for educational purposes and do not represent the complete production implementation. Test and adapt all examples before deployment.

