Skip to content

Understanding Firebase Storage Security Rules

The storage security rules are extremely similar to that of Firestore’s; almost identical, I dare say. We’ll first cover the basics, then go through the 20% of it that will cover 80% that you need to know.

If you want to check out Firestore’s rules for yourself, you can check out my article on it or the official docs.

The Basics: ‘Match’ and ‘Allow’

match /images/profilePhoto.png {
  allow write: if <condition>;
}

match /images {
  match /croppedProfilePhoto.png {
    allow read, write: if true;
  }
}

Match is used to point to a file path. You can’t match the directories themselves, at least not without using another match statement within their brackets to eventually point to a file path.

Allow sets the actual rule. It’s used in conjunction with read and/or write, and then a condition. The condition can be as simple as true or false, or you can use more dynamic conditions like request.auth != null (more on this later).

Wildcards match all files under a path

match /images/{image} {
   allow read, write: if true;
}

You won’t always know the specific file names of every image under some directories, or perhaps you just want a quicker way to match all files under a directory. Using the wildcard {thisnamecouldbeanything} allows you to do just that. However, this won’t match other directories under the specified directory. Well, we have something else for that.

Recursive Wildcard Syntax

match /{allPaths=**} {
  allow read, write: if true;
}

Fancy name, yes. Useful enough to justify having that name? Oh yes indeed. Using this special wildcard matches everything under that directory.

More complex conditions

There are so much special conditions you can utilise. In fact, here’s a list from the official docs.

We won’t cover them all. Instead, we’ll cover the 2 most important ones you’ll be using 80% of the time.

request.auth

match /{allPaths=**} {
  allow read, write: if request.auth != null;
}

You use this to check whether the user is authenticated. If they’re not, it returns null. This rule is used commonly to give access only to authenticated users.

request.resource.size

match /images/profilePhoto.png {
  allow write: if request.auth != null && request.resource.size < 5 * 1024 * 1024;
}

Pretty self-explanatory. You use this to check the size of the file being uploaded. This rule is commonly used to deny uploads that are too large as storage space can be limited.

It’s also noteworthy that all these conditions can use logic and arithmetic operations.

Conclusion

Downright similar, these rules and Firestore’s. That’s a good thing. It’s much easier to remember. All of this knowledge including most of the code snippets were taken from the official docs. We love simplifying things down here at ericthecoder.com.