पाठ 18 / 25
Scheduled Functions and Secrets
Cron jobs and keys.
onSchedule and defineSecret
onSchedule from firebase-functions/v2/scheduler runs a function on a cron-like schedule using Cloud Scheduler, for clean-ups, digests or reports. Third-party API keys must never be in client code or committed config; use defineSecret from firebase-functions/params, which stores values in Google Cloud Secret Manager, bind the secret to the functions that need it, and read it with .value() at runtime. Non-secret settings can use defineString and .env files. Set secrets with the CLI; secret storage and scheduler jobs have their own pricing, so check the docs.
A nightly job using a secret
TypeScript plus CLI commands (shown, not run).
import { onSchedule } from "firebase-functions/v2/scheduler";
import { defineSecret } from "firebase-functions/params";
import { getFirestore, Timestamp } from "firebase-admin/firestore";
const MAIL_API_KEY = defineSecret("MAIL_API_KEY");
export const nightlyCleanup = onSchedule(
{ schedule: "every day 02:00", timeZone: "Asia/Kolkata", secrets: [MAIL_API_KEY] },
async () => {
const cutoff = Timestamp.fromMillis(Date.now() - 30 * 24 * 60 * 60 * 1000);
const old = await getFirestore().collection("drafts")
.where("updatedAt", "<", cutoff).limit(400).get();
const batch = getFirestore().batch();
old.forEach((d) => batch.delete(d.ref));
await batch.commit();
await sendReport(MAIL_API_KEY.value(), old.size); // your own helper
},
);
// shell:
// firebase functions:secrets:set MAIL_API_KEY
// firebase deploy --only functionsBind secrets narrowly
List a secret only on the functions that use it, so other functions never receive it in their environment.
त्वरित जाँच: Where should a third-party API key used by a function be stored?
- In Secret Manager via defineSecret
- In the client web config
- In a public Firestore document
- Hard-coded in index.ts
Answer
In Secret Manager via defineSecret — Secrets stay server-side and out of source control.