Firebase Security Rules / Writing Firebase Security Rules

Getting started with Firestore Security Rules

This tutorial will guide you through the process of writing Firestore Security Rules. We will cover everything from basic rules to more complex rules for securing your Firestore d…

Tutorial 2 of 5 5 resources in this section

Section overview

5 resources

Learn how to write and structure Firebase Security Rules.

Getting Started with Firestore Security Rules

1. Introduction

This tutorial aims to provide you with the necessary knowledge to write Firestore Security Rules. Security rules are essential in safeguarding your Firestore database by determining who has read and write access to your database.

By the end of this tutorial, you will:

  • Understand Firestore Security Rules.
  • Be able to write basic and complex security rules.
  • Gain insights into best practices.

Prerequisites:

  • Basic understanding of Firestore and its data model.
  • Familiarity with JavaScript or similar programming languages.

2. Step-by-Step Guide

Firestore Security Rules use a syntax that resembles JavaScript, with some differences. The rules are composed of service blocks that specify the service, match statements that specify document paths, and allow expressions that grant access.

Basic Rule

Here is a basic example:

service cloud.firestore {
  match /databases/{database}/documents {
    match /{document=**} {
      allow read, write: if false;
    }
  }
}

In the code above, {document=**} matches request to any document in the database, and allow read, write: if false; denies all read and write operations.

Rules are not Filters

One key concept to understand is that security rules are not filters. Firestore does not filter data on the server. Rather, it checks each query against its potential result set.

Rules Evaluation

Rules are evaluated in the order they are defined, but only the first matching allow expression is evaluated.

3. Code Examples

Example 1: User-Based Access

This rule allows a user to read and write their own documents.

service cloud.firestore {
  match /databases/{database}/documents {
    match /users/{userId} {
      allow read, write: if request.auth.uid == userId;
    }
  }
}

In the code above, request.auth.uid represents the ID of the user making the request, and userId is the ID of the user document being accessed.

Example 2: Role-Based Access

This rule allows only users with the role 'admin' to write data.

service cloud.firestore {
  match /databases/{database}/documents {
    match /{document=**} {
      allow write: if get(/databases/$(database)/documents/users/$(request.auth.uid)).data.role == 'admin';
      allow read: if true;
    }
  }
}

This rule retrieves the role field of the user document and checks if it's 'admin'.

4. Summary

We've covered how to write basic and more complex Firestore Security Rules. We've also looked at how rules are not filters and their evaluation order.

Next, try to write rules for your own Firestore database. Remember to always test your rules thoroughly before deploying.

5. Practice Exercises

  1. Write a rule that allows a user to update their document only if the email field stays the same.
  2. Write a rule that allows read access to a document only if the published field is true.

Solutions

service cloud.firestore {
  match /databases/{database}/documents {
    match /users/{userId} {
      allow update: if request.auth.uid == userId && request.resource.data.email == resource.data.email;
    }
  }
}

This rule checks if the email field in the new data (request.resource.data.email) is the same as the email field in the existing document (resource.data.email).

service cloud.firestore {
  match /databases/{database}/documents {
    match /articles/{articleId} {
      allow read: if resource.data.published == true;
    }
  }
}

This rule allows reading an article document only if the published field is true. It doesn't check who the user is, so it applies to all users.

Keep practicing by writing rules for different scenarios and testing them out.

Need Help Implementing This?

We build custom systems, plugins, and scalable infrastructure.

Discuss Your Project

Related topics

Keep learning with adjacent tracks.

View category

HTML

Learn the fundamental building blocks of the web using HTML.

Explore

CSS

Master CSS to style and format web pages effectively.

Explore

JavaScript

Learn JavaScript to add interactivity and dynamic behavior to web pages.

Explore

Python

Explore Python for web development, data analysis, and automation.

Explore

SQL

Learn SQL to manage and query relational databases.

Explore

PHP

Master PHP to build dynamic and secure web applications.

Explore

Popular tools

Helpful utilities for quick tasks.

Browse tools

Lorem Ipsum Generator

Generate placeholder text for web design and mockups.

Use tool

Watermark Generator

Add watermarks to images easily.

Use tool

WHOIS Lookup Tool

Get domain and IP details with WHOIS lookup.

Use tool

HTML Minifier & Formatter

Minify or beautify HTML code.

Use tool

Random Password Generator

Create secure, complex passwords with custom length and character options.

Use tool

Latest articles

Fresh insights from the CodiWiki team.

Visit blog

AI in Drug Discovery: Accelerating Medical Breakthroughs

In the rapidly evolving landscape of healthcare and pharmaceuticals, Artificial Intelligence (AI) in drug dis…

Read article

AI in Retail: Personalized Shopping and Inventory Management

In the rapidly evolving retail landscape, the integration of Artificial Intelligence (AI) is revolutionizing …

Read article

AI in Public Safety: Predictive Policing and Crime Prevention

In the realm of public safety, the integration of Artificial Intelligence (AI) stands as a beacon of innovati…

Read article

AI in Mental Health: Assisting with Therapy and Diagnostics

In the realm of mental health, the integration of Artificial Intelligence (AI) stands as a beacon of hope and…

Read article

AI in Legal Compliance: Ensuring Regulatory Adherence

In an era where technology continually reshapes the boundaries of industries, Artificial Intelligence (AI) in…

Read article

Need help implementing this?

Get senior engineering support to ship it cleanly and on time.

Get Implementation Help