Add auto created_by and create_at fields in firestore

Viewed 24

I wanna add properties such as "created_by" and "created_at" to each and every object in pretty much every collection in firestore.

The only approaches I can think of so far are.

  1. Add them in the client-side code but verify them on the server side using Security Rules.

or better:

  1. Add them automatically on the server side using Cloud Firestore function triggers onCreate and onWrite events.

However, both approaches sounds like workarounds for a very common task for which I would expect an out-of-the-box solution.

Does anybody know any out-of-the-box approach for that?

1 Answers

There's no built-in solution for this. Cloud Functions sounds redundant as security rules can ensure the values are correct:

allow create: if request.resource.data.created_at == request.time && request.data.created_by == request.auth.uid;

You can use serverTimestamp() for created_at when adding the document so the rules will return true as mentioned in the documentation.

For Firestore write operations that include server-side timestamps, this time (request.time) will be equal to the server timestamp.


You can use withConverter() so you don't have to repeat the same code to add those common fields. Instead, declare the converter once and use it for any read/write operations as required:

const addDefaultFields = {
  toFirestore: (docData: any) => {
    // TODO: Add created_at and other fields 
    return {
      created_at: serverTimestamp(),
      ...docData,
    }
  },
  fromFirestore: (snapshot: any, options: any) => {
    const data = snapshot.data(options)
    return {
      id: snapshot.id,
      ...data,
    }
  },
}

const docRef = doc(db, 'col', 'alovelace').withConverter(addDefaultFields)
Related