DEV Community

pizzacat83
pizzacat83

Posted on • Edited on

4 4

A Useful Custom Function to Debug Firestore Security Rules

Firestore security rules provide a function debug, which logs the given value to firestore-debug.log (only when using the Firestore Emulator; it's no-op in production). But it just prints the value, with no information on its context. When your security rule doesn't work as expected, you might wrap every suspicious expression with debug and then struggle to figure out the correspondence between each log entires and the plenty calls to debug.

What if there's a function to log custom messages that explain why the request is denied? Like:


allow get: if
  // logs "not admin" if the user's role is not admin
  assert(request.auth.role == "admin", "not admin") &&
  // logs "email is not verified" if email_verified is false
  assert(request.auth.email_verified, "email is not verified");
Enter fullscreen mode Exit fullscreen mode

Actually, you can implement this assert function! The definition is:

function assert(condition, message) {
  return condition || debug(message) && false;
}
Enter fullscreen mode Exit fullscreen mode

When condition is truthy, it just returns condition. Otherwise, it logs message to firestore-debug.log and returns false.

I hope this function helps you debug your security rules!

Sentry image

Hands-on debugging session: instrument, monitor, and fix

Join Lazar for a hands-on session where you’ll build it, break it, debug it, and fix it. You’ll set up Sentry, track errors, use Session Replay and Tracing, and leverage some good ol’ AI to find and fix issues fast.

RSVP here →

Top comments (0)

Sentry image

See why 4M developers consider Sentry, “not bad.”

Fixing code doesn’t have to be the worst part of your day. Learn how Sentry can help.

Learn more

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay