How to Set Firebase Storage Rules for Secure Access
To set
Firebase Storage rules, write rules in the Firebase Console under the Storage section using the rules language. These rules control who can read or write files by defining conditions on request.auth and file paths. After writing, click Publish to apply the rules.Syntax
Firebase Storage rules use a simple language to define access control. The main parts are:
- service: Defines the storage service.
- match: Specifies file path patterns to apply rules.
- allow: Sets read/write permissions with conditions.
Conditions often check if a user is authenticated (request.auth != null) or if the file path matches certain patterns.
firebase
service firebase.storage {
match /b/{bucket}/o {
match /{allPaths=**} {
allow read, write: if <condition>;
}
}
}Example
This example allows only authenticated users to read and write any file in storage. It demonstrates a basic secure rule.
firebase
service firebase.storage {
match /b/{bucket}/o {
match /{allPaths=**} {
allow read, write: if request.auth != null;
}
}
}Output
Rules published successfully. Authenticated users can read and write all files.
Common Pitfalls
Common mistakes when setting Firebase Storage rules include:
- Leaving rules open with
allow read, write: if true;which makes files public. - Forgetting to check
request.auth, allowing unauthenticated access. - Using incorrect path patterns that block access unintentionally.
- Not publishing rules after editing, so changes don't apply.
Always test your rules with the Firebase Emulator or Console before deploying.
firebase
service firebase.storage {
match /b/{bucket}/o {
match /{allPaths=**} {
// Wrong: public access
allow read, write: if true;
// Right: restrict to authenticated users
// allow read, write: if request.auth != null;
}
}
}Quick Reference
| Rule Part | Description | Example |
|---|---|---|
| service | Defines the Firebase Storage service | service firebase.storage { ... } |
| match | Specifies file path pattern | match /b/{bucket}/o { ... } |
| allow | Grants read/write with condition | allow read, write: if request.auth != null; |
| request.auth | User authentication info | request.auth != null means user signed in |
| {allPaths=**} | Wildcard for all file paths | match /{allPaths=**} { ... } |
Key Takeaways
Always write Firebase Storage rules in the Firebase Console under Storage > Rules.
Use
request.auth != null to restrict access to signed-in users.Match file paths carefully to control access to specific folders or files.
Never leave rules open with
if true unless public access is intended.Publish and test your rules to ensure they work as expected.