title: Firebase cloud function security using triggers without resulting in infinite loop?
body: <p>I'm trying to implement some security checks to my cloud function triggers, but as I discovered my current set up results in an infinite loop from the onCreate and onDelete triggers when doc is not valid. How would I go about using onCreate and onDelete triggers for security without resulting in an infinite loop or is there another way that can achieve this without using firestore security rules?</p>
  <pre><code>  export const createEventTrigger = functions.firestore.document(&quot;events/{id}&quot;).onCreate(async (snapshot, context) =&gt; {
  
      const event = snapshot.data() as Event;
  
      const isValid = await isEventDocumentCreateValid(context, event);
  
      if (!isValid) {
        // Delete the document if it’s invalid
        console.log(
          `Deleting invalid document for user ${getInvokerUid(context)}`
        );
        await snapshot.ref.delete();
      }
    });
  </code></pre>
  <pre><code>  export const deleteEventTrigger = functions.firestore.document(&quot;events/{id}&quot;).onDelete(async (snapshot, context) =&gt; {
      // Contents of the document as a JavaScript object
      const event = snapshot.data() as Event;
  
      const isValid = await isEventDocumentDeleteValid(context, event);
  
      if (!isValid) {
        // Add back the document if it’s invalid
        console.log(
          `Adding back doc after invalid document delete for user ${getInvokerUid(
            context
          )}`
        );
        await snapshot.ref.set(event);
      }
    });
  </code></pre>