4

I am migrating a 1st generation Cloud Firestore Trigger to the second generation.

However, I cannot figure out how to access Google's Secret Manager from within the second generation Cloud Trigger.

Documentation exists for accessing secrets within second generation cloud functions by making use of a defineSecret utility which is passed into the function's dependency array. However, this approach does not work with the second generation cloud trigger as there is no options parameter to pass the dependency array.

To explain with a snippet what I am trying to do:

import { onDocumentCreated } from 'firebase-functions/v2/firestore';
import { defineSecret } from 'firebase-functions/params';

const apiKey = defineSecret('API_KEY');

const onUserCreated = onDocumentCreated(
  'users/{userId}',
  async (event) => {
    // 👉 access apiKey secret 👈
  }
);

Any help would be greatly appreciated. Thank you.

1 Answer 1

8

You can pass a DocumentOptions object as the first parameter, which is basically an extension of EventHandlerOptions to set the secrets with the below code:

import * as admin from "firebase-admin";
admin.initializeApp();
import { onDocumentWritten } from "firebase-functions/v2/firestore";
import { defineSecret } from "firebase-functions/params";

const discordApiKey = defineSecret("DISCORD_API_KEY");

export const writetofirestore = onDocumentWritten({
  document: "users/{userId}",
  secrets: [discordApiKey] // you can provide secrets like this 
}, (event) => { 
  const apiKey = discordApiKey.value(); // use secret like this
});

Reference : firestore.onDocumentWritten()

1

Not the answer you're looking for? Browse other questions tagged or ask your own question.