Firebase provides a set of Security Rules to secure your data in Firestore, Firebase Storage, and Firebase Realtime Database. These rules allow you to control who has access to your data and what they can do with it.
By the end of this tutorial, you will have learnt:
This tutorial assumes you have a basic understanding of Firebase. Knowledge about Firestore, Firebase Storage, or Realtime Database will be beneficial.
Firebase Security Rules use a custom, JSON-like language. A rules file consists of service blocks, match blocks, and access control expressions.
Service Blocks: Defines which Firebase service the rules will apply to. Each service block contains one or more match blocks.
service cloud.firestore {
// Match blocks go here
}
Match Blocks: Specifies the database paths that the rules will apply to. They can be nested to specify more specific paths.
match /databases/{database}/documents {
// Access control expressions go here
}
Access Control Expressions: Determines who has read or write access to the matching path.
allow read, write: if request.auth != null;
Example 1: Allow all users to read, but only authenticated users to write.
service cloud.firestore {
match /databases/{database}/documents {
// Matches any document in the database
match /{document=**} {
allow read; // Everyone can read
allow write: if request.auth != null; // Only authenticated users can write
}
}
}
In this example, the **
wildcard matches any document in any collection in the database. The request.auth != null
condition checks if the user is authenticated.
Example 2: Allow users to read and write their own data.
service cloud.firestore {
match /databases/{database}/documents {
match /users/{userId} {
allow read, write: if request.auth != null && request.auth.uid == userId;
}
}
}
Here, the {userId}
wildcard matches any document in the users
collection. The condition checks if the user is authenticated and if the authenticated user's ID matches the document ID.
In this tutorial, we've covered:
To continue your learning, try writing more complex rules and test them in the Firebase console. The Firebase documentation is a great resource for further reading.
Write a rule that allows users to read all documents, but only write to documents in a posts
collection if the document's authorId
field matches their user ID.
Write a rule that allows users to read a document in a privateMessages
collection only if the document's recipientId
field matches their user ID.
Solutions:
service cloud.firestore {
match /databases/{database}/documents {
match /{document=**} {
allow read;
match /posts/{postId} {
allow write: if request.auth != null && request.resource.data.authorId == request.auth.uid;
}
}
}
}
service cloud.firestore {
match /databases/{database}/documents {
match /privateMessages/{messageId} {
allow read: if request.auth != null && resource.data.recipientId == request.auth.uid;
}
}
}
Keep practicing! Writing effective security rules is a key skill in Firebase development.