35 Macros and Advanced Expressions

This chapter introduces macros and advanced expression constructs that allow developers to reference external documents, evaluate existence conditions, and build dynamic, multi-layered access rules. These features are essential for writing scalable and intelligent security policies in Oracle Backend for Firebase.

35.1 What are Macros?

Macros are built-in functions that allow security rules to interact with other documents in the database. They enable cross-document validation, existence checks, and conditional logic based on external data.

Oracle Backend for Firebase supports two powerful macros:

  • exists(path)

  • get(path)

35.2 exists(path) Macro

This macro checks whether a document exists at the specified path.

Syntax

exists(/collection/documentId)

Use Case

You can restrict access or creation based on the presence of a related document.

Example 35-1 Validate User Existence

This rule allows project creation only if the referenced ownerId exists in the users collection.

match /projects/{projectId} {
  allow create: if request.auth != null && exists(/users/$(request.resource.data.ownerId));
}

Example 35-2 Manager Validation

This rule ensures that an employee document can be read only if the associated manager exists.

match /employees/{employeeId} {
  allow read: if exists(/managers/$(resource.data.managerId));
}

Best Practices

  • Use exists() for lightweight existence checks

  • Always validate paths and field names to prevent runtime errors

35.3 get(path) Macro

The get(path) macro retrieves a document object from the specified path and allows access to its fields.

Syntax

get(/collection/documentId).data.fieldName

Use Case

You can enforce rules based on the value of a field in another document.

Example 35-3 Active Project Check

This rule allows reading a project only if its status is "active".

match /projects/{projectId} {
  allow get: if get(/projects/$(projectId)).data.status == "active";
}

Best Practices

  • Use get() when you need to inspect fields in another document

  • Avoid chaining multiple get() calls for performance

  • Always validate paths and field names to prevent runtime errors

35.4 Dynamic Path Construction

Both exists(path) and get(path) macros support dynamic path construction using $(...) interpolation.

The following checks if a user document exists for the currently authenticated user.

exists(/users/$(request.auth.uid))