Fire Beast

Avoid using onWrite trigger unless necessary

Sometimes you need to react to a Firestore document write, for example, run a Firebase Function that subscribes to Mailchimp newsletter when a user updates their notifications settings. It's tempting to use onWrite and check for the event type in the function.

I myself noticed that I had been preferring using onWrite for almost every time. Why create extra functions if you can do all with a single one, right?

Wrong! I realized that I had onWrite attached to a frequently updated collection, while in fact, I was using it only to handle initial document creation. So, I had wasted tons of resources because I thought I might need to handle other events in the future. And when I do, it will be easy to change the code—typical premature optimization mistake.

Check your code. You might have a few such functions yourself!

What to do instead?

Now, I never use onWrite unless I handle creating, writing, and removing events, which happens extremely rarely.

When I have similar code in handlers, I use a shared function instead:

import * as functions from "firebase-functions";

exports.onSettingsCreate = functions.firestore
  .document("settings/{userId}")
  .onCreate((settings) => syncWithMailchimp(settings));

exports.onSettingsUpdate = functions.firestore
  .document("settings/{userId}")
  .onUpdate((settingsChange) => syncWithMailchimp(settingsChange.after));

function syncWithMailchimp(settings) {
  // Do the thing
}

It will save your money and make code clearer and help to understand what triggers active the most — create, write on remove.