Get UID of current auth user in a onCreate trigger function

Viewed 17

I'm trying to get the UID of the auth user who created the new document in the cloud trigger function for the onCreate event.

I couldn't find on the documentation website how to do this. However, it's documented in the source code of the 'firebase-functions' JavaScript library that this should be context.auth.uid as in the code below. However, the code below reports in the logs that context.auth is undefined when a document is added by an authenticated user.

import * as functions from "firebase-functions";

export const mytriggerFunction = functions.firestore
  .document('someCollection/{documentId}')
  .onCreate((snapshot, context) => {
    console.log("Current auth:", context.auth);
    return true
  })
1 Answers

The context.auth is present in Callable Functions that are are called from client side and not in background functions such as Firestore triggers.


If you are trying to get UID of user who added the document in Firestore then you must add the same in the document while creating. You can then secure this by using the following security rules:

match /someCollection/{documentId} {
  allow create: if request.auth.uid == request.resource.data.userId;
}

Then you can read the contents of the created document using snapshot:

const data = snapshot.data();

console.log(`Document created by ${data.userId}`)
Related