Häufig benötigen Sie zusätzliche Konfigurationen für Ihre Funktionen, z. B. API-Schlüssel von Drittanbietern oder anpassbare Einstellungen. Das Firebase SDK for Cloud Functions bietet eine integrierte Umgebungskonfiguration, um das Speichern und Abrufen dieser Art von Daten für Ihr Projekt zu vereinfachen.
Sie können zwischen drei Optionen wählen:
- Parametrisierte Konfiguration (empfohlen für die meisten Szenarien). Dadurch wird eine stark typisierte Umgebungskonfiguration mit Parametern bereitgestellt, die zum Zeitpunkt der Bereitstellung validiert werden, was Fehler verhindert und das Debuggen vereinfacht.
- Dateibasierte Konfiguration von Umgebungsvariablen . Bei diesem Ansatz erstellen Sie manuell eine dotenv- Datei zum Laden von Umgebungsvariablen.
- Konfiguration der Laufzeitumgebung mit der Firebase-CLI und
functions.config
.
Für die meisten Anwendungsfälle wird eine parametrisierte Konfiguration empfohlen. Dieser Ansatz macht Konfigurationswerte sowohl zur Laufzeit als auch zur Bereitstellungszeit verfügbar, und die Bereitstellung wird blockiert, sofern nicht alle Parameter einen gültigen Wert aufweisen. Umgekehrt ist die Konfiguration mit Umgebungsvariablen zum Zeitpunkt der Bereitstellung nicht verfügbar.
Parametrisierte Konfiguration
Cloud Functions for Firebase bietet eine Schnittstelle zum deklarativen Definieren von Konfigurationsparametern in Ihrer Codebasis. Der Wert dieser Parameter ist sowohl während der Funktionsbereitstellung, beim Festlegen von Bereitstellungs- und Laufzeitoptionen als auch während der Ausführung verfügbar. Das bedeutet, dass die CLI die Bereitstellung blockiert, wenn nicht alle Parameter einen gültigen Wert haben.
Um Parameter in Ihrem Code zu definieren, folgen Sie diesem Modell:
const functions = require('firebase-functions');
const { defineInt, defineString } = require('firebase-functions/params');
// Define some parameters
const minInstancesConfig = defineInt('HELLO_WORLD_MININSTANCES');
const welcomeMessage = defineString('WELCOME_MESSAGE');
// To use configured parameters inside the config for a function, provide them
// directly. To use them at runtime, call .value() on them.
export const helloWorld = functions.runWith({ minInstances: minInstancesConfig}).https.onRequest(
(req, res) => {
res.send(`${welcomeMessage.value()}! I am a function.`);
}
);
Beim Bereitstellen einer Funktion mit parametrisierten Konfigurationsvariablen versucht die Firebase-CLI zunächst, ihre Werte aus lokalen .env-Dateien zu laden. Wenn sie in diesen Dateien nicht vorhanden sind und kein default
festgelegt ist, fordert die CLI während der Bereitstellung zur Eingabe der Werte auf und speichert ihre Werte dann automatisch in einer .env
Datei mit dem Namen .env.<project_ID>
in Ihrem Verzeichnis functions/
:
$ firebase deploy
i functions: preparing codebase default for deployment
? Enter a string value for ENVIRONMENT: prod
i functions: Writing new parameter values to disk: .env.projectId
…
$ firebase deploy
i functions: Loaded environment variables from .env.projectId
Abhängig von Ihrem Entwicklungsworkflow kann es sinnvoll sein, die generierte .env.<project_ID>
-Datei der Versionskontrolle hinzuzufügen.
Konfigurieren Sie das CLI-Verhalten
Parameter können mit einem Options
konfiguriert werden, das steuert, wie die CLI zur Eingabe von Werten auffordert. Im folgenden Beispiel werden Optionen festgelegt, um das Format einer Telefonnummer zu validieren, eine einfache Auswahloption bereitzustellen und eine Auswahloption automatisch aus dem Firebase-Projekt auszufüllen:
const { defineString } = require('firebase-functions/params');
const welcomeMessage = defineString('WELCOME_MESSAGE', {default: 'Hello World',
description: 'The greeting that is returned to the caller of this function'});
const onlyPhoneNumbers = defineString('PHONE_NUMBER', {input: {text:
{validationRegex: /\d{3}-\d{3}-\d{4}/, validationErrorMessage: "Please enter
a phone number in the format XXX-YYY-ZZZZ"}}});
const selectedOption = defineString('PARITY', {input: {select: {options:
[{value: "odd"}, {value: "even"}]}}})
const storageBucket = defineString('BUCKET', {input: {resource: {type:
"storage.googleapis.com/Bucket"}}, description: "This will automatically
populate the selector field with the deploying Cloud Project’s
storage buckets"})
Parametertypen
Die parametrisierte Konfiguration bietet eine starke Typisierung für Parameterwerte und unterstützt auch Geheimnisse von Cloud Secret Manager. Unterstützte Typen sind:
- Geheimnis
- Schnur
- Boolesch
- Ganze Zahl
- Schweben
Parameterwerte und Ausdrücke
Firebase wertet Ihre Parameter sowohl zum Zeitpunkt der Bereitstellung als auch während der Ausführung Ihrer Funktion aus. Aufgrund dieser dualen Umgebungen muss beim Vergleichen von Parameterwerten und bei deren Verwendung zum Festlegen von Laufzeitoptionen für Ihre Funktionen besondere Sorgfalt walten.
Um einen Parameter als Laufzeitoption an Ihre Funktion zu übergeben, übergeben Sie ihn direkt:
const functions = require('firebase-functions');
const { defineInt} = require('firebase-functions/params');
const minInstancesConfig = defineInt('HELLO\_WORLD\_MININSTANCES');
export const helloWorld = functions.runWith({ minInstances: minInstancesConfig}).https.onRequest(
(req, res) => {
//…
Wenn Sie außerdem mit einem Parameter vergleichen müssen, um zu wissen, welche Option Sie auswählen müssen, müssen Sie integrierte Komparatoren verwenden, anstatt den Wert zu überprüfen:
const functions = require('firebase-functions');
const { defineBool } = require('firebase-functions/params');
const environment = params.defineString(‘ENVIRONMENT’, {default: ‘dev’});
// use built-in comparators
const minInstancesConfig =environment.equals('PRODUCTION').thenElse(10, 1);
export const helloWorld = functions.runWith({ minInstances: minInstancesConfig}).https.onRequest(
(req, res) => {
//…
Auf Parameter und Parameterausdrücke, die nur zur Laufzeit verwendet werden, kann mit ihrer value
zugegriffen werden:
const functions = require('firebase-functions');
const { defineString } = require('firebase-functions/params');
const welcomeMessage = defineString('WELCOME_MESSAGE');
// To use configured parameters inside the config for a function, provide them
// directly. To use them at runtime, call .value() on them.
export const helloWorld = functions.https.onRequest(
(req, res) => {
res.send(`${welcomeMessage.value()}! I am a function.`);
}
);
Eingebaute Parameter
Das Cloud Functions SDK bietet drei vordefinierte Parameter, die im Unterpaket firebase-functions/params
verfügbar sind:
-
projectId
– das Cloud-Projekt, in dem die Funktion ausgeführt wird. -
databaseUrl
– die URL der Realtime Database-Instanz, die der Funktion zugeordnet ist (falls im Firebase-Projekt aktiviert). -
storageBucket
– der mit der Funktion verknüpfte Cloud Storage-Bucket (falls im Firebase-Projekt aktiviert).
Diese funktionieren in jeder Hinsicht wie benutzerdefinierte Zeichenfolgenparameter, außer dass, da ihre Werte der Firebase-CLI immer bekannt sind, ihre Werte bei der Bereitstellung niemals abgefragt oder in .env
Dateien gespeichert werden.
Geheime Parameter
Parameter des Typs Secret
, definiert mit defineSecret()
, stellen Zeichenfolgenparameter dar, die einen Wert haben, der in Cloud Secret Manager gespeichert ist. Anstatt gegen eine lokale .env
Datei zu prüfen und einen neuen Wert in die Datei zu schreiben, falls er fehlt, prüfen geheime Parameter, ob sie in Cloud Secret Manager vorhanden sind, und fordern während der Bereitstellung interaktiv den Wert eines neuen Geheimnisses an.
So definierte geheime Parameter müssen an einzelne Funktionen gebunden werden, die darauf Zugriff haben sollen:
const functions = require('firebase-functions');
const { defineSecret } = require('firebase-functions/params');
const discordApiKey = defineSecret('DISCORD_API_KEY');
export const postToDiscord = functions.runWith({ secrets: [discordApiKey] }).https.onRequest(
(req, res) => {
const apiKey = discordApiKey.value();
//…
Da die Werte von Geheimnissen bis zur Ausführung der Funktion verborgen sind, können Sie sie beim Konfigurieren Ihrer Funktion nicht verwenden.
Umgebungsvariablen
Cloud Functions for Firebase unterstützt das dotenv- Dateiformat zum Laden von Umgebungsvariablen, die in einer .env
Datei angegeben sind, in Ihre Anwendungslaufzeit. Nach der Bereitstellung können die Umgebungsvariablen über die Schnittstelle process.env
gelesen werden.
Um Ihre Umgebung auf diese Weise zu konfigurieren, erstellen Sie eine .env
Datei in Ihrem Projekt, fügen Sie die gewünschten Variablen hinzu und stellen Sie Folgendes bereit:
Erstellen Sie eine
.env
Datei in Ihremfunctions/
-Verzeichnis:# Directory layout: # my-project/ # firebase.json # functions/ # .env # package.json # index.js
Öffnen Sie die
.env
Datei zum Bearbeiten und fügen Sie die gewünschten Schlüssel hinzu. Zum Beispiel:PLANET=Earth AUDIENCE=Humans
Stellen Sie Funktionen bereit und überprüfen Sie, ob Umgebungsvariablen geladen wurden:
firebase deploy --only functions # ... # i functions: Loaded environment variables from .env. # ...
Sobald Ihre benutzerdefinierten Umgebungsvariablen bereitgestellt sind, kann Ihr Funktionscode mit der process.env
Syntax darauf zugreifen:
// Responds with "Hello Earth and Humans"
exports.hello = functions.https.onRequest((request, response) => {
response.send(`Hello ${process.env.PLANET} and ${process.env.AUDIENCE}`);
});
Bereitstellen mehrerer Sätze von Umgebungsvariablen
Wenn Sie einen alternativen Satz von Umgebungsvariablen für Ihre Firebase-Projekte benötigen (z. B. Staging vs. Produktion), erstellen Sie eine .env. <project or alias >
file und schreiben Sie dort Ihre projektspezifischen Umgebungsvariablen. Die Umgebungsvariablen aus .env
und projektspezifischen .env
Dateien (falls vorhanden) werden in alle bereitgestellten Funktionen eingeschlossen.
Ein Projekt könnte beispielsweise diese drei Dateien enthalten, die leicht unterschiedliche Werte für Entwicklung und Produktion enthalten:
.env | .env.dev | .env.prod |
PLANET=Erde PUBLIKUM=Menschen | PUBLIKUM=Entwicklermenschen | PUBLIKUM = Prod Menschen |
Angesichts der Werte in diesen separaten Dateien variiert der Satz von Umgebungsvariablen, die mit Ihren Funktionen bereitgestellt werden, je nach Zielprojekt:
$ firebase use dev
$ firebase deploy --only functions
i functions: Loaded environment variables from .env, .env.dev.
# Deploys functions with following user-defined environment variables:
# PLANET=Earth
# AUDIENCE=Dev Humans
$ firebase use prod
$ firebase deploy --only functions
i functions: Loaded environment variables from .env, .env.prod.
# Deploys functions with following user-defined environment variables:
# PLANET=Earth
# AUDIENCE=Prod Humans
Reservierte Umgebungsvariablen
Einige Umgebungsvariablenschlüssel sind für die interne Verwendung reserviert. Verwenden Sie keinen dieser Schlüssel in Ihren .env
Dateien:
- Alle Schlüssel beginnend mit X_GOOGLE_
- Alle Tasten ab EXT_
- Alle Schlüssel beginnend mit FIREBASE_
- Beliebiger Schlüssel aus der folgenden Liste:
- CLOUD_RUNTIME_CONFIG
- EINSTIEGSPUNKT
- GCP_PROJECT
- GCLOUD_PROJEKT
- GOOGLE_CLOUD_PROJECT
- FUNCTION_TRIGGER_TYPE
- FUNKTIONSNAME
- FUNCTION_MEMORY_MB
- FUNCTION_TIMEOUT_SEC
- FUNKTION_IDENTITÄT
- FUNCTION_REGION
- FUNCTION_TARGET
- FUNCTION_SIGNATURE_TYPE
- K_SERVICE
- K_REVISION
- HAFEN
- K_KONFIGURATION
Speichern Sie vertrauliche Konfigurationsinformationen und greifen Sie darauf zu
In .env
Dateien gespeicherte Umgebungsvariablen können für die Funktionskonfiguration verwendet werden, aber Sie sollten sie nicht als sichere Methode zum Speichern vertraulicher Informationen wie Datenbankanmeldeinformationen oder API-Schlüssel betrachten. Dies ist besonders wichtig, wenn Sie Ihre .env
Dateien in die Quellcodeverwaltung einchecken.
Damit Sie vertrauliche Konfigurationsinformationen speichern können, lässt sich Cloud Functions for Firebase in Google Cloud Secret Manager integrieren. Dieser verschlüsselte Dienst speichert Konfigurationswerte sicher und ermöglicht dennoch bei Bedarf einen einfachen Zugriff von Ihren Funktionen aus.
Erstellen und verwenden Sie ein Geheimnis
Verwenden Sie zum Erstellen eines Geheimnisses die Firebase-Befehlszeilenschnittstelle.
So erstellen und verwenden Sie ein Geheimnis:
Führen Sie im Stammverzeichnis Ihres lokalen Projektverzeichnisses den folgenden Befehl aus:
firebase functions:secrets:set SECRET_NAME
Geben Sie einen Wert für SECRET_NAME ein.
Die CLI gibt eine Erfolgsmeldung zurück und warnt Sie, dass Sie Funktionen bereitstellen müssen, damit die Änderung wirksam wird.
Stellen Sie vor der Bereitstellung sicher, dass Ihr Funktionscode der Funktion den Zugriff auf das Geheimnis mithilfe des Parameters
runWith
ermöglicht:exports.processPayment = functions // Make the secret available to this function .runWith({ secrets: ["SECRET_NAME"] }) .onCall((data, context) => { const myBillingService = initializeBillingService( // reference the secret value process.env.SECRET_NAME ); // Process the payment });
Cloud-Funktionen bereitstellen:
firebase deploy --only functions
Jetzt können Sie wie auf jede andere Umgebungsvariable darauf zugreifen. Wenn umgekehrt eine andere Funktion, die das Geheimnis nicht in runWith
angibt, versucht, auf das Geheimnis zuzugreifen, erhält sie einen undefinierten Wert:
exports.anotherEndpoint = functions.https.onRequest((request, response) => {
response.send(`The secret API key is ${process.env.SECRET_NAME}`);
// responds with "The secret API key is undefined" because the `runWith` parameter is missing
});
Sobald Ihre Funktion bereitgestellt ist, hat sie Zugriff auf den geheimen Wert. Nur Funktionen, die ausdrücklich ein Geheimnis in ihren runWith
Parameter aufnehmen, haben Zugriff auf dieses Geheimnis als Umgebungsvariable. Auf diese Weise können Sie sicherstellen, dass geheime Werte nur dort verfügbar sind, wo sie benötigt werden, und das Risiko verringern, versehentlich ein Geheimnis preiszugeben.
Geheimnisse verwalten
Verwenden Sie die Firebase CLI, um Ihre Geheimnisse zu verwalten. Denken Sie bei der Verwaltung von Geheimnissen auf diese Weise daran, dass einige CLI-Änderungen erfordern, dass Sie zugehörige Funktionen ändern und/oder erneut bereitstellen. Speziell:
- Immer wenn Sie einen neuen Wert für ein Geheimnis festlegen, müssen Sie alle Funktionen, die auf dieses Geheimnis verweisen, erneut bereitstellen, damit sie den neuesten Wert übernehmen.
- Wenn Sie ein Geheimnis löschen, stellen Sie sicher, dass keine Ihrer bereitgestellten Funktionen auf dieses Geheimnis verweist. Funktionen, die einen gelöschten geheimen Wert verwenden, schlagen unbemerkt fehl.
Hier ist eine Zusammenfassung der Firebase CLI-Befehle für die geheime Verwaltung:
# Change the value of an existing secret firebase functions:secrets:set SECRET_NAME # View the value of a secret functions:secrets:access SECRET_NAME # Destroy a secret functions:secrets:destroy SECRET_NAME # View all secret versions and their state functions:secrets:get SECRET_NAME # Automatically clean up all secrets that aren't referenced by any of your functions functions:secrets:prune
Für die access
und destroy
können Sie den optionalen Versionsparameter angeben, um eine bestimmte Version zu verwalten. Zum Beispiel:
functions:secrets:access SECRET_NAME[@VERSION]
Um weitere Informationen zu diesen Vorgängen zu erhalten, übergeben Sie -h
mit dem Befehl, um die CLI-Hilfe anzuzeigen.
Wie Geheimnisse abgerechnet werden
Secret Manager erlaubt 6 aktive Secret- Versionen kostenlos. Das bedeutet, dass Sie in einem Firebase-Projekt 6 Secrets pro Monat kostenlos haben können.
Standardmäßig versucht die Firebase-Befehlszeilenschnittstelle, ungenutzte Secret-Versionen gegebenenfalls automatisch zu löschen, z. B. wenn Sie Funktionen mit einer neuen Version des Secrets bereitstellen. Außerdem können Sie ungenutzte Geheimnisse mit functions:secrets:destroy
und functions:secrets:prune
aktiv bereinigen.
Secret Manager erlaubt 10.000 nicht abgerechnete monatliche Zugriffsvorgänge auf ein Geheimnis. Funktionsinstanzen lesen bei jedem Kaltstart nur die Geheimnisse, die in ihrem runWith
Parameter angegeben sind. Wenn Sie viele Funktionsinstanzen haben, die viele Geheimnisse lesen, kann Ihr Projekt diesen Freibetrag überschreiten, woraufhin Ihnen 0,03 USD pro 10.000 Zugriffsvorgänge in Rechnung gestellt werden.
Weitere Informationen finden Sie unter Preise für Secret Manager .
Emulator-Unterstützung
Die Umgebungskonfiguration mit dotenv ist darauf ausgelegt, mit einem lokalen Cloud Functions-Emulator zusammenzuarbeiten.
Wenn Sie einen lokalen Cloud Functions-Emulator verwenden, können Sie Umgebungsvariablen für Ihr Projekt überschreiben, indem Sie eine .env.local
Datei einrichten. Inhalte von .env.local
haben Vorrang vor .env
und der projektspezifischen .env
Datei.
Ein Projekt könnte beispielsweise diese drei Dateien enthalten, die leicht unterschiedliche Werte für Entwicklung und lokale Tests enthalten:
.env | .env.dev | .env.local |
PLANET=Erde PUBLIKUM=Menschen | PUBLIKUM=Entwicklermenschen | PUBLIKUM=Lokale Menschen |
Beim Start im lokalen Kontext lädt der Emulator die Umgebungsvariablen wie gezeigt:
$ firebase emulators:start
i emulators: Starting emulators: functions
# Starts emulator with following environment variables:
# PLANET=Earth
# AUDIENCE=Local Humans
Geheimnisse und Anmeldedaten im Cloud Functions-Emulator
Der Cloud Functions-Emulator unterstützt die Verwendung von Geheimnissen zum Speichern und Zugreifen auf vertrauliche Konfigurationsinformationen . Standardmäßig versucht der Emulator, mit den Standardanmeldeinformationen der Anwendung auf Ihre Produktionsgeheimnisse zuzugreifen. In bestimmten Situationen wie CI-Umgebungen kann der Emulator aufgrund von Berechtigungsbeschränkungen möglicherweise nicht auf geheime Werte zugreifen.
Ähnlich wie bei der Cloud Functions-Emulatorunterstützung für Umgebungsvariablen können Sie geheime Werte überschreiben, indem Sie eine .secret.local
Datei einrichten. Dies macht es Ihnen leicht, Ihre Funktionen lokal zu testen, insbesondere wenn Sie keinen Zugriff auf den geheimen Wert haben.
Migrieren von der Umgebungskonfiguration
Wenn Sie die Umgebungskonfiguration mit functions.config
verwendet haben, können Sie Ihre vorhandene Konfiguration als Umgebungsvariablen (im dotenv- Format) migrieren. Die Firebase-CLI stellt einen Exportbefehl bereit, der die Konfiguration jedes Alias oder Projekts, das in .firebaserc
Datei Ihres Verzeichnisses aufgeführt ist (im Beispiel unten local
, dev
und prod
), als .env
Dateien ausgibt.
Exportieren Sie zur Migration Ihre vorhandenen Umgebungskonfigurationen mit dem Befehl firebase functions:config:export
:
firebase functions:config:export i Importing configs from projects: [project-0, project-1] ⚠ The following configs keys could not be exported as environment variables: ⚠ project-0 (dev): 1foo.a => 1FOO\_A (Key 1FOO\_A must start with an uppercase ASCII letter or underscore, and then consist of uppercase ASCII letters, digits, and underscores.) Enter a PREFIX to rename invalid environment variable keys: CONFIG\_ ✔ Wrote functions/.env.prod ✔ Wrote functions/.env.dev ✔ Wrote functions/.env.local ✔ Wrote functions/.env
Beachten Sie, dass Sie in einigen Fällen aufgefordert werden, ein Präfix einzugeben, um exportierte Umgebungsvariablenschlüssel umzubenennen. Dies liegt daran, dass nicht alle Konfigurationen automatisch transformiert werden können, da sie möglicherweise ungültig sind oder eine reservierte Umgebungsvariable key sind.
Wir empfehlen, dass Sie den Inhalt der generierten .env
Dateien sorgfältig prüfen, bevor Sie Ihre Funktionen bereitstellen oder die .env
Dateien in die Quellcodeverwaltung einchecken. Wenn Werte vertraulich sind und nicht durchsickern sollen, entfernen Sie sie aus Ihren .env
Dateien und speichern Sie sie stattdessen sicher in Secret Manager .
Sie müssen auch Ihren Funktionscode aktualisieren. Alle Funktionen, die functions.config
verwenden, müssen jetzt stattdessen process.env
verwenden, wie in Umgebungsvariablen gezeigt.
Umgebungskonfiguration
Bevor die Unterstützung von Umgebungsvariablen in firebase-functions v3.18.0
veröffentlicht wurde, war die Verwendung functions.config()
der empfohlene Ansatz für die Umgebungskonfiguration. Dieser Ansatz wird weiterhin unterstützt, aber wir empfehlen allen neuen Projekten, stattdessen Umgebungsvariablen zu verwenden, da sie einfacher zu verwenden sind und die Portabilität Ihres Codes verbessern.
Legen Sie die Umgebungskonfiguration mit der CLI fest
Um Umgebungsdaten zu speichern, können Sie den Befehl firebase functions:config:set
in der Firebase-CLI verwenden. Jeder Schlüssel kann mit Punkten benannt werden, um zusammengehörige Konfigurationen zu gruppieren. Beachten Sie, dass in Schlüsseln nur Kleinbuchstaben akzeptiert werden ; Großbuchstaben sind nicht erlaubt.
Um beispielsweise die Client-ID und den API-Schlüssel für "Some Service" zu speichern, könnten Sie Folgendes ausführen:
firebase functions:config:set someservice.key="THE API KEY" someservice.id="THE CLIENT ID"
Rufen Sie die aktuelle Umgebungskonfiguration ab
Um zu überprüfen, was derzeit in der Umgebungskonfiguration für Ihr Projekt gespeichert ist, können Sie firebase functions:config:get
verwenden. Es wird JSON in etwa so ausgegeben:
{
"someservice": {
"key":"THE API KEY",
"id":"THE CLIENT ID"
}
}
Diese Funktionalität basiert auf der Google Cloud Runtime Configuration API .
Verwenden Sie functions.config
, um auf die Umgebungskonfiguration in einer Funktion zuzugreifen
Einige Konfigurationen werden automatisch unter dem reservierten firebase
Namespace bereitgestellt. Die Umgebungskonfiguration wird innerhalb Ihrer laufenden Funktion über functions.config()
verfügbar gemacht. Um die obige Konfiguration zu verwenden, könnte Ihr Code so aussehen:
const functions = require('firebase-functions');
const request = require('request-promise');
exports.userCreated = functions.database.ref('/users/{id}').onWrite(event => {
let email = event.data.child('email').val();
return request({
url: 'https://someservice.com/api/some/call',
headers: {
'X-Client-ID': functions.config().someservice.id,
'Authorization': `Bearer ${functions.config().someservice.key}`
},
body: {email: email}
});
});
Verwenden Sie die Umgebungskonfiguration, um ein Modul zu initialisieren
Einige Node-Module sind ohne Konfiguration bereit. Andere Module benötigen eine zusätzliche Konfiguration, um korrekt initialisiert zu werden. Wir empfehlen, diese Konfiguration in Umgebungskonfigurationsvariablen zu speichern, anstatt sie fest zu codieren. Dies hilft Ihnen, Ihren Code viel portabler zu halten, wodurch Sie Ihre Anwendung als Open Source öffnen oder einfach zwischen Produktions- und Staging-Versionen wechseln können.
Um beispielsweise das Slack Node SDK- Modul zu verwenden, könnten Sie Folgendes schreiben:
const functions = require('firebase-functions');
const IncomingWebhook = require('@slack/client').IncomingWebhook;
const webhook = new IncomingWebhook(functions.config().slack.url);
Legen Sie vor der Bereitstellung die Umgebungskonfigurationsvariable slack.url
fest:
firebase functions:config:set slack.url=https://hooks.slack.com/services/XXX
Zusätzliche Umgebungsbefehle
-
firebase functions:config:unset key1 key2
entfernt die angegebenen Schlüssel aus der config -
firebase functions:config:clone --from <fromProject>
klont die Umgebung eines anderen Projekts in das derzeit aktive Projekt.
Automatisch ausgefüllte Umgebungsvariablen
Es gibt Umgebungsvariablen, die automatisch in der Funktionslaufzeit und in lokal emulierten Funktionen ausgefüllt werden. Dazu gehören diejenigen, die von Google Cloud ausgefüllt werden , sowie eine Firebase-spezifische Umgebungsvariable:
process.env.FIREBASE_CONFIG
: Stellt die folgenden Firebase-Projektkonfigurationsinformationen bereit:
{
databaseURL: 'https://databaseName.firebaseio.com',
storageBucket: 'projectId.appspot.com',
projectId: 'projectId'
}
Diese Konfiguration wird automatisch angewendet, wenn Sie das Firebase Admin SDK ohne Argumente initialisieren. Wenn Sie Funktionen in JavaScript schreiben, initialisieren Sie wie folgt:
const admin = require('firebase-admin');
admin.initializeApp();
Wenn Sie Funktionen in TypeScript schreiben, initialisieren Sie wie folgt:
import * as functions from 'firebase-functions';
import * as admin from 'firebase-admin';
import 'firebase-functions';
admin.initializeApp();
Wenn Sie das Admin SDK mit der Standardprojektkonfiguration unter Verwendung der Dienstkonto-Anmeldeinformationen initialisieren müssen, können Sie die Anmeldeinformationen aus einer Datei laden und sie wie folgt zu FIREBASE_CONFIG
hinzufügen:
serviceAccount = require('./serviceAccount.json');
const adminConfig = JSON.parse(process.env.FIREBASE_CONFIG);
adminConfig.credential = admin.credential.cert(serviceAccount);
admin.initializeApp(adminConfig);
,Häufig benötigen Sie zusätzliche Konfigurationen für Ihre Funktionen, z. B. API-Schlüssel von Drittanbietern oder anpassbare Einstellungen. Das Firebase SDK for Cloud Functions bietet eine integrierte Umgebungskonfiguration, um das Speichern und Abrufen dieser Art von Daten für Ihr Projekt zu vereinfachen.
Sie können zwischen drei Optionen wählen:
- Parametrisierte Konfiguration (empfohlen für die meisten Szenarien). Dadurch wird eine stark typisierte Umgebungskonfiguration mit Parametern bereitgestellt, die zum Zeitpunkt der Bereitstellung validiert werden, was Fehler verhindert und das Debuggen vereinfacht.
- Dateibasierte Konfiguration von Umgebungsvariablen . Bei diesem Ansatz erstellen Sie manuell eine dotenv- Datei zum Laden von Umgebungsvariablen.
- Konfiguration der Laufzeitumgebung mit der Firebase-CLI und
functions.config
.
Für die meisten Anwendungsfälle wird eine parametrisierte Konfiguration empfohlen. Dieser Ansatz macht Konfigurationswerte sowohl zur Laufzeit als auch zur Bereitstellungszeit verfügbar, und die Bereitstellung wird blockiert, sofern nicht alle Parameter einen gültigen Wert aufweisen. Umgekehrt ist die Konfiguration mit Umgebungsvariablen zum Zeitpunkt der Bereitstellung nicht verfügbar.
Parametrisierte Konfiguration
Cloud Functions for Firebase bietet eine Schnittstelle zum deklarativen Definieren von Konfigurationsparametern in Ihrer Codebasis. Der Wert dieser Parameter ist sowohl während der Funktionsbereitstellung, beim Festlegen von Bereitstellungs- und Laufzeitoptionen als auch während der Ausführung verfügbar. Das bedeutet, dass die CLI die Bereitstellung blockiert, wenn nicht alle Parameter einen gültigen Wert haben.
Um Parameter in Ihrem Code zu definieren, folgen Sie diesem Modell:
const functions = require('firebase-functions');
const { defineInt, defineString } = require('firebase-functions/params');
// Define some parameters
const minInstancesConfig = defineInt('HELLO_WORLD_MININSTANCES');
const welcomeMessage = defineString('WELCOME_MESSAGE');
// To use configured parameters inside the config for a function, provide them
// directly. To use them at runtime, call .value() on them.
export const helloWorld = functions.runWith({ minInstances: minInstancesConfig}).https.onRequest(
(req, res) => {
res.send(`${welcomeMessage.value()}! I am a function.`);
}
);
Beim Bereitstellen einer Funktion mit parametrisierten Konfigurationsvariablen versucht die Firebase-CLI zunächst, ihre Werte aus lokalen .env-Dateien zu laden. Wenn sie in diesen Dateien nicht vorhanden sind und kein default
festgelegt ist, fordert die CLI während der Bereitstellung zur Eingabe der Werte auf und speichert ihre Werte dann automatisch in einer .env
Datei mit dem Namen .env.<project_ID>
in Ihrem Verzeichnis functions/
:
$ firebase deploy
i functions: preparing codebase default for deployment
? Enter a string value for ENVIRONMENT: prod
i functions: Writing new parameter values to disk: .env.projectId
…
$ firebase deploy
i functions: Loaded environment variables from .env.projectId
Abhängig von Ihrem Entwicklungsworkflow kann es sinnvoll sein, die generierte .env.<project_ID>
-Datei der Versionskontrolle hinzuzufügen.
Konfigurieren Sie das CLI-Verhalten
Parameter können mit einem Options
konfiguriert werden, das steuert, wie die CLI zur Eingabe von Werten auffordert. Im folgenden Beispiel werden Optionen festgelegt, um das Format einer Telefonnummer zu validieren, eine einfache Auswahloption bereitzustellen und eine Auswahloption automatisch aus dem Firebase-Projekt auszufüllen:
const { defineString } = require('firebase-functions/params');
const welcomeMessage = defineString('WELCOME_MESSAGE', {default: 'Hello World',
description: 'The greeting that is returned to the caller of this function'});
const onlyPhoneNumbers = defineString('PHONE_NUMBER', {input: {text:
{validationRegex: /\d{3}-\d{3}-\d{4}/, validationErrorMessage: "Please enter
a phone number in the format XXX-YYY-ZZZZ"}}});
const selectedOption = defineString('PARITY', {input: {select: {options:
[{value: "odd"}, {value: "even"}]}}})
const storageBucket = defineString('BUCKET', {input: {resource: {type:
"storage.googleapis.com/Bucket"}}, description: "This will automatically
populate the selector field with the deploying Cloud Project’s
storage buckets"})
Parametertypen
Die parametrisierte Konfiguration bietet eine starke Typisierung für Parameterwerte und unterstützt auch Geheimnisse von Cloud Secret Manager. Unterstützte Typen sind:
- Geheimnis
- Schnur
- Boolesch
- Ganze Zahl
- Schweben
Parameterwerte und Ausdrücke
Firebase wertet Ihre Parameter sowohl zum Zeitpunkt der Bereitstellung als auch während der Ausführung Ihrer Funktion aus. Aufgrund dieser dualen Umgebungen muss beim Vergleichen von Parameterwerten und bei deren Verwendung zum Festlegen von Laufzeitoptionen für Ihre Funktionen besondere Sorgfalt walten.
Um einen Parameter als Laufzeitoption an Ihre Funktion zu übergeben, übergeben Sie ihn direkt:
const functions = require('firebase-functions');
const { defineInt} = require('firebase-functions/params');
const minInstancesConfig = defineInt('HELLO\_WORLD\_MININSTANCES');
export const helloWorld = functions.runWith({ minInstances: minInstancesConfig}).https.onRequest(
(req, res) => {
//…
Wenn Sie außerdem mit einem Parameter vergleichen müssen, um zu wissen, welche Option Sie auswählen müssen, müssen Sie integrierte Komparatoren verwenden, anstatt den Wert zu überprüfen:
const functions = require('firebase-functions');
const { defineBool } = require('firebase-functions/params');
const environment = params.defineString(‘ENVIRONMENT’, {default: ‘dev’});
// use built-in comparators
const minInstancesConfig =environment.equals('PRODUCTION').thenElse(10, 1);
export const helloWorld = functions.runWith({ minInstances: minInstancesConfig}).https.onRequest(
(req, res) => {
//…
Auf Parameter und Parameterausdrücke, die nur zur Laufzeit verwendet werden, kann mit ihrer value
zugegriffen werden:
const functions = require('firebase-functions');
const { defineString } = require('firebase-functions/params');
const welcomeMessage = defineString('WELCOME_MESSAGE');
// To use configured parameters inside the config for a function, provide them
// directly. To use them at runtime, call .value() on them.
export const helloWorld = functions.https.onRequest(
(req, res) => {
res.send(`${welcomeMessage.value()}! I am a function.`);
}
);
Eingebaute Parameter
Das Cloud Functions SDK bietet drei vordefinierte Parameter, die im Unterpaket firebase-functions/params
verfügbar sind:
-
projectId
– das Cloud-Projekt, in dem die Funktion ausgeführt wird. -
databaseUrl
– die URL der Realtime Database-Instanz, die der Funktion zugeordnet ist (falls im Firebase-Projekt aktiviert). -
storageBucket
– der mit der Funktion verknüpfte Cloud Storage-Bucket (falls im Firebase-Projekt aktiviert).
Diese funktionieren in jeder Hinsicht wie benutzerdefinierte Zeichenfolgenparameter, außer dass, da ihre Werte der Firebase-CLI immer bekannt sind, ihre Werte bei der Bereitstellung niemals abgefragt oder in .env
Dateien gespeichert werden.
Geheime Parameter
Parameter des Typs Secret
, definiert mit defineSecret()
, stellen Zeichenfolgenparameter dar, die einen Wert haben, der in Cloud Secret Manager gespeichert ist. Anstatt gegen eine lokale .env
Datei zu prüfen und einen neuen Wert in die Datei zu schreiben, falls er fehlt, prüfen geheime Parameter, ob sie in Cloud Secret Manager vorhanden sind, und fordern während der Bereitstellung interaktiv den Wert eines neuen Geheimnisses an.
So definierte geheime Parameter müssen an einzelne Funktionen gebunden werden, die darauf Zugriff haben sollen:
const functions = require('firebase-functions');
const { defineSecret } = require('firebase-functions/params');
const discordApiKey = defineSecret('DISCORD_API_KEY');
export const postToDiscord = functions.runWith({ secrets: [discordApiKey] }).https.onRequest(
(req, res) => {
const apiKey = discordApiKey.value();
//…
Da die Werte von Geheimnissen bis zur Ausführung der Funktion verborgen sind, können Sie sie beim Konfigurieren Ihrer Funktion nicht verwenden.
Umgebungsvariablen
Cloud Functions for Firebase unterstützt das dotenv- Dateiformat zum Laden von Umgebungsvariablen, die in einer .env
Datei angegeben sind, in Ihre Anwendungslaufzeit. Nach der Bereitstellung können die Umgebungsvariablen über die Schnittstelle process.env
gelesen werden.
Um Ihre Umgebung auf diese Weise zu konfigurieren, erstellen Sie eine .env
Datei in Ihrem Projekt, fügen Sie die gewünschten Variablen hinzu und stellen Sie Folgendes bereit:
Erstellen Sie eine
.env
Datei in Ihremfunctions/
-Verzeichnis:# Directory layout: # my-project/ # firebase.json # functions/ # .env # package.json # index.js
Öffnen Sie die
.env
Datei zum Bearbeiten und fügen Sie die gewünschten Schlüssel hinzu. Zum Beispiel:PLANET=Earth AUDIENCE=Humans
Stellen Sie Funktionen bereit und überprüfen Sie, ob Umgebungsvariablen geladen wurden:
firebase deploy --only functions # ... # i functions: Loaded environment variables from .env. # ...
Sobald Ihre benutzerdefinierten Umgebungsvariablen bereitgestellt sind, kann Ihr Funktionscode mit der process.env
Syntax darauf zugreifen:
// Responds with "Hello Earth and Humans"
exports.hello = functions.https.onRequest((request, response) => {
response.send(`Hello ${process.env.PLANET} and ${process.env.AUDIENCE}`);
});
Bereitstellen mehrerer Sätze von Umgebungsvariablen
Wenn Sie einen alternativen Satz von Umgebungsvariablen für Ihre Firebase-Projekte benötigen (z. B. Staging vs. Produktion), erstellen Sie eine .env. <project or alias >
file und schreiben Sie dort Ihre projektspezifischen Umgebungsvariablen. Die Umgebungsvariablen aus .env
und projektspezifischen .env
Dateien (falls vorhanden) werden in alle bereitgestellten Funktionen eingeschlossen.
Ein Projekt könnte beispielsweise diese drei Dateien enthalten, die leicht unterschiedliche Werte für Entwicklung und Produktion enthalten:
.env | .env.dev | .env.prod |
PLANET=Erde PUBLIKUM=Menschen | PUBLIKUM=Entwicklermenschen | PUBLIKUM = Prod Menschen |
Angesichts der Werte in diesen separaten Dateien variiert der Satz von Umgebungsvariablen, die mit Ihren Funktionen bereitgestellt werden, je nach Zielprojekt:
$ firebase use dev
$ firebase deploy --only functions
i functions: Loaded environment variables from .env, .env.dev.
# Deploys functions with following user-defined environment variables:
# PLANET=Earth
# AUDIENCE=Dev Humans
$ firebase use prod
$ firebase deploy --only functions
i functions: Loaded environment variables from .env, .env.prod.
# Deploys functions with following user-defined environment variables:
# PLANET=Earth
# AUDIENCE=Prod Humans
Reservierte Umgebungsvariablen
Einige Umgebungsvariablenschlüssel sind für die interne Verwendung reserviert. Verwenden Sie keinen dieser Schlüssel in Ihren .env
Dateien:
- Alle Schlüssel beginnend mit X_GOOGLE_
- Alle Tasten ab EXT_
- Alle Schlüssel beginnend mit FIREBASE_
- Beliebiger Schlüssel aus der folgenden Liste:
- CLOUD_RUNTIME_CONFIG
- EINSTIEGSPUNKT
- GCP_PROJECT
- GCLOUD_PROJEKT
- GOOGLE_CLOUD_PROJECT
- FUNCTION_TRIGGER_TYPE
- FUNKTIONSNAME
- FUNCTION_MEMORY_MB
- FUNCTION_TIMEOUT_SEC
- FUNKTION_IDENTITÄT
- FUNCTION_REGION
- FUNCTION_TARGET
- FUNCTION_SIGNATURE_TYPE
- K_SERVICE
- K_REVISION
- HAFEN
- K_KONFIGURATION
Speichern Sie vertrauliche Konfigurationsinformationen und greifen Sie darauf zu
In .env
Dateien gespeicherte Umgebungsvariablen können für die Funktionskonfiguration verwendet werden, aber Sie sollten sie nicht als sichere Methode zum Speichern vertraulicher Informationen wie Datenbankanmeldeinformationen oder API-Schlüssel betrachten. Dies ist besonders wichtig, wenn Sie Ihre .env
Dateien in die Quellcodeverwaltung einchecken.
Damit Sie vertrauliche Konfigurationsinformationen speichern können, lässt sich Cloud Functions for Firebase in Google Cloud Secret Manager integrieren. Dieser verschlüsselte Dienst speichert Konfigurationswerte sicher und ermöglicht dennoch bei Bedarf einen einfachen Zugriff von Ihren Funktionen aus.
Erstellen und verwenden Sie ein Geheimnis
Verwenden Sie zum Erstellen eines Geheimnisses die Firebase-Befehlszeilenschnittstelle.
So erstellen und verwenden Sie ein Geheimnis:
Führen Sie im Stammverzeichnis Ihres lokalen Projektverzeichnisses den folgenden Befehl aus:
firebase functions:secrets:set SECRET_NAME
Geben Sie einen Wert für SECRET_NAME ein.
Die CLI gibt eine Erfolgsmeldung zurück und warnt Sie, dass Sie Funktionen bereitstellen müssen, damit die Änderung wirksam wird.
Stellen Sie vor der Bereitstellung sicher, dass Ihr Funktionscode der Funktion den Zugriff auf das Geheimnis mithilfe des Parameters
runWith
ermöglicht:exports.processPayment = functions // Make the secret available to this function .runWith({ secrets: ["SECRET_NAME"] }) .onCall((data, context) => { const myBillingService = initializeBillingService( // reference the secret value process.env.SECRET_NAME ); // Process the payment });
Cloud-Funktionen bereitstellen:
firebase deploy --only functions
Jetzt können Sie wie auf jede andere Umgebungsvariable darauf zugreifen. Wenn umgekehrt eine andere Funktion, die das Geheimnis nicht in runWith
angibt, versucht, auf das Geheimnis zuzugreifen, erhält sie einen undefinierten Wert:
exports.anotherEndpoint = functions.https.onRequest((request, response) => {
response.send(`The secret API key is ${process.env.SECRET_NAME}`);
// responds with "The secret API key is undefined" because the `runWith` parameter is missing
});
Sobald Ihre Funktion bereitgestellt ist, hat sie Zugriff auf den geheimen Wert. Nur Funktionen, die ausdrücklich ein Geheimnis in ihren runWith
Parameter aufnehmen, haben Zugriff auf dieses Geheimnis als Umgebungsvariable. Auf diese Weise können Sie sicherstellen, dass geheime Werte nur dort verfügbar sind, wo sie benötigt werden, und das Risiko verringern, versehentlich ein Geheimnis preiszugeben.
Geheimnisse verwalten
Verwenden Sie die Firebase CLI, um Ihre Geheimnisse zu verwalten. Denken Sie bei der Verwaltung von Geheimnissen auf diese Weise daran, dass einige CLI-Änderungen erfordern, dass Sie zugehörige Funktionen ändern und/oder erneut bereitstellen. Speziell:
- Immer wenn Sie einen neuen Wert für ein Geheimnis festlegen, müssen Sie alle Funktionen, die auf dieses Geheimnis verweisen, erneut bereitstellen, damit sie den neuesten Wert übernehmen.
- Wenn Sie ein Geheimnis löschen, stellen Sie sicher, dass keine Ihrer bereitgestellten Funktionen auf dieses Geheimnis verweist. Funktionen, die einen gelöschten geheimen Wert verwenden, schlagen unbemerkt fehl.
Hier ist eine Zusammenfassung der Firebase CLI-Befehle für die geheime Verwaltung:
# Change the value of an existing secret firebase functions:secrets:set SECRET_NAME # View the value of a secret functions:secrets:access SECRET_NAME # Destroy a secret functions:secrets:destroy SECRET_NAME # View all secret versions and their state functions:secrets:get SECRET_NAME # Automatically clean up all secrets that aren't referenced by any of your functions functions:secrets:prune
Für die access
und destroy
können Sie den optionalen Versionsparameter angeben, um eine bestimmte Version zu verwalten. Zum Beispiel:
functions:secrets:access SECRET_NAME[@VERSION]
Um weitere Informationen zu diesen Vorgängen zu erhalten, übergeben Sie -h
mit dem Befehl, um die CLI-Hilfe anzuzeigen.
Wie Geheimnisse abgerechnet werden
Secret Manager erlaubt 6 aktive Secret- Versionen kostenlos. Das bedeutet, dass Sie in einem Firebase-Projekt 6 Secrets pro Monat kostenlos haben können.
Standardmäßig versucht die Firebase-Befehlszeilenschnittstelle, ungenutzte Secret-Versionen gegebenenfalls automatisch zu löschen, z. B. wenn Sie Funktionen mit einer neuen Version des Secrets bereitstellen. Außerdem können Sie ungenutzte Geheimnisse mit functions:secrets:destroy
und functions:secrets:prune
aktiv bereinigen.
Secret Manager erlaubt 10.000 nicht abgerechnete monatliche Zugriffsvorgänge auf ein Geheimnis. Funktionsinstanzen lesen bei jedem Kaltstart nur die Geheimnisse, die in ihrem runWith
Parameter angegeben sind. Wenn Sie viele Funktionsinstanzen haben, die viele Geheimnisse lesen, kann Ihr Projekt diesen Freibetrag überschreiten, woraufhin Ihnen 0,03 USD pro 10.000 Zugriffsvorgänge in Rechnung gestellt werden.
Weitere Informationen finden Sie unter Preise für Secret Manager .
Emulator-Unterstützung
Die Umgebungskonfiguration mit dotenv ist darauf ausgelegt, mit einem lokalen Cloud Functions-Emulator zusammenzuarbeiten.
Wenn Sie einen lokalen Cloud Functions-Emulator verwenden, können Sie Umgebungsvariablen für Ihr Projekt überschreiben, indem Sie eine .env.local
Datei einrichten. Inhalte von .env.local
haben Vorrang vor .env
und der projektspezifischen .env
Datei.
Ein Projekt könnte beispielsweise diese drei Dateien enthalten, die leicht unterschiedliche Werte für Entwicklung und lokale Tests enthalten:
.env | .env.dev | .env.local |
PLANET=Erde PUBLIKUM=Menschen | PUBLIKUM=Entwicklermenschen | PUBLIKUM=Lokale Menschen |
Beim Start im lokalen Kontext lädt der Emulator die Umgebungsvariablen wie gezeigt:
$ firebase emulators:start
i emulators: Starting emulators: functions
# Starts emulator with following environment variables:
# PLANET=Earth
# AUDIENCE=Local Humans
Geheimnisse und Anmeldedaten im Cloud Functions-Emulator
Der Cloud Functions-Emulator unterstützt die Verwendung von Geheimnissen zum Speichern und Zugreifen auf vertrauliche Konfigurationsinformationen . Standardmäßig versucht der Emulator, mit den Standardanmeldeinformationen der Anwendung auf Ihre Produktionsgeheimnisse zuzugreifen. In bestimmten Situationen wie CI-Umgebungen kann der Emulator aufgrund von Berechtigungsbeschränkungen möglicherweise nicht auf geheime Werte zugreifen.
Ähnlich wie bei der Cloud Functions-Emulatorunterstützung für Umgebungsvariablen können Sie geheime Werte überschreiben, indem Sie eine .secret.local
Datei einrichten. Dies macht es Ihnen leicht, Ihre Funktionen lokal zu testen, insbesondere wenn Sie keinen Zugriff auf den geheimen Wert haben.
Migrieren von der Umgebungskonfiguration
Wenn Sie die Umgebungskonfiguration mit functions.config
verwendet haben, können Sie Ihre vorhandene Konfiguration als Umgebungsvariablen (im dotenv- Format) migrieren. Die Firebase-CLI stellt einen Exportbefehl bereit, der die Konfiguration jedes Alias oder Projekts, das in .firebaserc
Datei Ihres Verzeichnisses aufgeführt ist (im Beispiel unten local
, dev
und prod
), als .env
Dateien ausgibt.
Exportieren Sie zur Migration Ihre vorhandenen Umgebungskonfigurationen mit dem Befehl firebase functions:config:export
:
firebase functions:config:export i Importing configs from projects: [project-0, project-1] ⚠ The following configs keys could not be exported as environment variables: ⚠ project-0 (dev): 1foo.a => 1FOO\_A (Key 1FOO\_A must start with an uppercase ASCII letter or underscore, and then consist of uppercase ASCII letters, digits, and underscores.) Enter a PREFIX to rename invalid environment variable keys: CONFIG\_ ✔ Wrote functions/.env.prod ✔ Wrote functions/.env.dev ✔ Wrote functions/.env.local ✔ Wrote functions/.env
Beachten Sie, dass Sie in einigen Fällen aufgefordert werden, ein Präfix einzugeben, um exportierte Umgebungsvariablenschlüssel umzubenennen. Dies liegt daran, dass nicht alle Konfigurationen automatisch transformiert werden können, da sie möglicherweise ungültig sind oder eine reservierte Umgebungsvariable key sind.
Wir empfehlen, dass Sie den Inhalt der generierten .env
Dateien sorgfältig prüfen, bevor Sie Ihre Funktionen bereitstellen oder die .env
Dateien in die Quellcodeverwaltung einchecken. Wenn Werte vertraulich sind und nicht durchsickern sollen, entfernen Sie sie aus Ihren .env
Dateien und speichern Sie sie stattdessen sicher in Secret Manager .
Sie müssen auch Ihren Funktionscode aktualisieren. Alle Funktionen, die functions.config
verwenden, müssen jetzt stattdessen process.env
verwenden, wie in Umgebungsvariablen gezeigt.
Umgebungskonfiguration
Bevor die Unterstützung von Umgebungsvariablen in firebase-functions v3.18.0
veröffentlicht wurde, war die Verwendung functions.config()
der empfohlene Ansatz für die Umgebungskonfiguration. Dieser Ansatz wird weiterhin unterstützt, aber wir empfehlen allen neuen Projekten, stattdessen Umgebungsvariablen zu verwenden, da sie einfacher zu verwenden sind und die Portabilität Ihres Codes verbessern.
Legen Sie die Umgebungskonfiguration mit der CLI fest
Um Umgebungsdaten zu speichern, können Sie den Befehl firebase functions:config:set
in der Firebase-CLI verwenden. Jeder Schlüssel kann mit Punkten benannt werden, um zusammengehörige Konfigurationen zu gruppieren. Beachten Sie, dass in Schlüsseln nur Kleinbuchstaben akzeptiert werden ; Großbuchstaben sind nicht erlaubt.
Um beispielsweise die Client-ID und den API-Schlüssel für "Some Service" zu speichern, könnten Sie Folgendes ausführen:
firebase functions:config:set someservice.key="THE API KEY" someservice.id="THE CLIENT ID"
Rufen Sie die aktuelle Umgebungskonfiguration ab
Um zu überprüfen, was derzeit in der Umgebungskonfiguration für Ihr Projekt gespeichert ist, können Sie firebase functions:config:get
verwenden. Es wird JSON in etwa so ausgegeben:
{
"someservice": {
"key":"THE API KEY",
"id":"THE CLIENT ID"
}
}
Diese Funktionalität basiert auf der Google Cloud Runtime Configuration API .
Verwenden Sie functions.config
, um auf die Umgebungskonfiguration in einer Funktion zuzugreifen
Einige Konfigurationen werden automatisch unter dem reservierten firebase
Namespace bereitgestellt. Die Umgebungskonfiguration wird innerhalb Ihrer laufenden Funktion über functions.config()
verfügbar gemacht. Um die obige Konfiguration zu verwenden, könnte Ihr Code so aussehen:
const functions = require('firebase-functions');
const request = require('request-promise');
exports.userCreated = functions.database.ref('/users/{id}').onWrite(event => {
let email = event.data.child('email').val();
return request({
url: 'https://someservice.com/api/some/call',
headers: {
'X-Client-ID': functions.config().someservice.id,
'Authorization': `Bearer ${functions.config().someservice.key}`
},
body: {email: email}
});
});
Verwenden Sie die Umgebungskonfiguration, um ein Modul zu initialisieren
Einige Node-Module sind ohne Konfiguration bereit. Andere Module benötigen eine zusätzliche Konfiguration, um korrekt initialisiert zu werden. Wir empfehlen, diese Konfiguration in Umgebungskonfigurationsvariablen zu speichern, anstatt sie fest zu codieren. Dies hilft Ihnen, Ihren Code viel portabler zu halten, wodurch Sie Ihre Anwendung als Open Source verwenden oder einfach zwischen Produktions- und Staging-Versionen wechseln können.
Um beispielsweise das Slack Node SDK- Modul zu verwenden, könnten Sie Folgendes schreiben:
const functions = require('firebase-functions');
const IncomingWebhook = require('@slack/client').IncomingWebhook;
const webhook = new IncomingWebhook(functions.config().slack.url);
Legen Sie vor der Bereitstellung die Umgebungskonfigurationsvariable slack.url
fest:
firebase functions:config:set slack.url=https://hooks.slack.com/services/XXX
Zusätzliche Umgebungsbefehle
-
firebase functions:config:unset key1 key2
entfernt die angegebenen Schlüssel aus der config -
firebase functions:config:clone --from <fromProject>
klont die Umgebung eines anderen Projekts in das derzeit aktive Projekt.
Automatisch gefüllte Umgebungsvariablen
Es gibt Umgebungsvariablen, die automatisch in der Funktionslaufzeit und in lokal emulierten Funktionen ausgefüllt werden. Dazu gehören diejenigen, die von Google Cloud ausgefüllt werden , sowie eine Firebase-spezifische Umgebungsvariable:
process.env.FIREBASE_CONFIG
: Stellt die folgenden Firebase-Projektkonfigurationsinformationen bereit:
{
databaseURL: 'https://databaseName.firebaseio.com',
storageBucket: 'projectId.appspot.com',
projectId: 'projectId'
}
Diese Konfiguration wird automatisch angewendet, wenn Sie das Firebase Admin SDK ohne Argumente initialisieren. Wenn Sie Funktionen in JavaScript schreiben, initialisieren Sie wie folgt:
const admin = require('firebase-admin');
admin.initializeApp();
Wenn Sie Funktionen in TypeScript schreiben, initialisieren Sie wie folgt:
import * as functions from 'firebase-functions';
import * as admin from 'firebase-admin';
import 'firebase-functions';
admin.initializeApp();
If you need to initialize the Admin SDK with the default project configuration using service account credentials, you can load the credentials from a file and add them to FIREBASE_CONFIG
like this:
serviceAccount = require('./serviceAccount.json');
const adminConfig = JSON.parse(process.env.FIREBASE_CONFIG);
adminConfig.credential = admin.credential.cert(serviceAccount);
admin.initializeApp(adminConfig);
,Often you'll need additional configuration for your functions, such as third-party API keys or tuneable settings. The Firebase SDK for Cloud Functions offers built-in environment configuration to make it easy to store and retrieve this type of data for your project.
You can choose between three options:
- Parameterized configuration (recommended for most scenarios). This provides strongly-typed environment configuration with parameters that are validated at deploy time, which prevents errors and simplifies debugging.
- File-based configuration of environment variables . With this approach, you manually create a dotenv file for loading environment variables.
- Runtime environment configuration with the Firebase CLI and
functions.config
.
For most use cases, parameterized configuration is recommended. This approach makes configuration values available both at runtime and deploy time, and deployment is blocked unless all parameters have a valid value. Conversely, configuration with environment variables is not available at deploy time.
Parameterized configuration
Cloud Functions for Firebase provides an interface for defining configuration parameters declaratively inside your codebase. The value of these parameters is available both during function deployment, when setting deployment and runtime options, and during execution. This means that the CLI will block deployment unless all parameters have a valid value.
To define parameters in your code, follow this model:
const functions = require('firebase-functions');
const { defineInt, defineString } = require('firebase-functions/params');
// Define some parameters
const minInstancesConfig = defineInt('HELLO_WORLD_MININSTANCES');
const welcomeMessage = defineString('WELCOME_MESSAGE');
// To use configured parameters inside the config for a function, provide them
// directly. To use them at runtime, call .value() on them.
export const helloWorld = functions.runWith({ minInstances: minInstancesConfig}).https.onRequest(
(req, res) => {
res.send(`${welcomeMessage.value()}! I am a function.`);
}
);
When deploying a function with parameterized configuration variables, the Firebase CLI first attempts to load their values from local .env files. If they are not present in those files and no default
is set, the CLI will prompt for the values during deployment, and then automatically save their values to a .env
file named .env.<project_ID>
in your functions/
directory:
$ firebase deploy
i functions: preparing codebase default for deployment
? Enter a string value for ENVIRONMENT: prod
i functions: Writing new parameter values to disk: .env.projectId
…
$ firebase deploy
i functions: Loaded environment variables from .env.projectId
Depending on your development workflow, it may be useful to add the generated .env.<project_ID>
file to version control.
Configure CLI behavior
Parameters can be configured with an Options
object that controls how the CLI will prompt for values. The following example sets options to validate the format of a phone number, to provide a simple selection option, and to populate a selection option automatically from the Firebase project:
const { defineString } = require('firebase-functions/params');
const welcomeMessage = defineString('WELCOME_MESSAGE', {default: 'Hello World',
description: 'The greeting that is returned to the caller of this function'});
const onlyPhoneNumbers = defineString('PHONE_NUMBER', {input: {text:
{validationRegex: /\d{3}-\d{3}-\d{4}/, validationErrorMessage: "Please enter
a phone number in the format XXX-YYY-ZZZZ"}}});
const selectedOption = defineString('PARITY', {input: {select: {options:
[{value: "odd"}, {value: "even"}]}}})
const storageBucket = defineString('BUCKET', {input: {resource: {type:
"storage.googleapis.com/Bucket"}}, description: "This will automatically
populate the selector field with the deploying Cloud Project’s
storage buckets"})
Parameter types
Parameterized configuration provides strong typing for parameter values, and also support secrets from Cloud Secret Manager. Supported types are:
- Secret
- String
- Boolean
- Integer
- Float
Parameter values and expressions
Firebase evaluates your parameters both at deploy time and while your function is executing. Due to these dual environments, some extra care must be taken when comparing parameter values, and when using them to set runtime options for your functions.
To pass a parameter to your function as a runtime option, pass it directly:
const functions = require('firebase-functions');
const { defineInt} = require('firebase-functions/params');
const minInstancesConfig = defineInt('HELLO\_WORLD\_MININSTANCES');
export const helloWorld = functions.runWith({ minInstances: minInstancesConfig}).https.onRequest(
(req, res) => {
//…
Additionally, if you need to compare against a parameter in order to know what option to pick, you'll need to use built-in comparators instead of checking the value:
const functions = require('firebase-functions');
const { defineBool } = require('firebase-functions/params');
const environment = params.defineString(‘ENVIRONMENT’, {default: ‘dev’});
// use built-in comparators
const minInstancesConfig =environment.equals('PRODUCTION').thenElse(10, 1);
export const helloWorld = functions.runWith({ minInstances: minInstancesConfig}).https.onRequest(
(req, res) => {
//…
Parameters and parameter expressions that are only used at runtime can be accessed with their value
function:
const functions = require('firebase-functions');
const { defineString } = require('firebase-functions/params');
const welcomeMessage = defineString('WELCOME_MESSAGE');
// To use configured parameters inside the config for a function, provide them
// directly. To use them at runtime, call .value() on them.
export const helloWorld = functions.https.onRequest(
(req, res) => {
res.send(`${welcomeMessage.value()}! I am a function.`);
}
);
Built-in parameters
The Cloud Functions SDK offers three pre-defined parameters, available from the firebase-functions/params
subpackage:
-
projectId
— the Cloud project in which the function is running. -
databaseUrl
— the URL of the Realtime Database instance associated with the function (if enabled on the Firebase project). -
storageBucket
— the Cloud Storage bucket associated with the function (if enabled on the Firebase project).
These function like user-defined string parameters in all respects, except that, since their values are always known to the Firebase CLI, their values will never be prompted for on deployment nor saved to .env
files.
Secret parameters
Parameters of type Secret
, defined using defineSecret()
, represent string parameters which have a value stored in Cloud Secret Manager. Instead of checking against a local .env
file and writing a new value to the file if missing, secret parameters check against existence in Cloud Secret Manager, and interactively prompt for the value of a new secret during deployment.
Secret parameters defined in this way must be bound to individual functions that should have access to them:
const functions = require('firebase-functions');
const { defineSecret } = require('firebase-functions/params');
const discordApiKey = defineSecret('DISCORD_API_KEY');
export const postToDiscord = functions.runWith({ secrets: [discordApiKey] }).https.onRequest(
(req, res) => {
const apiKey = discordApiKey.value();
//…
Because the values of secrets are hidden until execution of the function, you cannot use them while configuring your function.
Environment variables
Cloud Functions for Firebase supports the dotenv file format for loading environment variables specified in a .env
file to your application runtime. Once deployed, the environment variables can be read via the process.env
interface.
To configure your environment this way, create a .env
file in your project, add the desired variables, and deploy:
Create a
.env
file in yourfunctions/
directory:# Directory layout: # my-project/ # firebase.json # functions/ # .env # package.json # index.js
Open the
.env
file for edit, and add the desired keys. Zum Beispiel:PLANET=Earth AUDIENCE=Humans
Deploy functions and verify that environment variables were loaded:
firebase deploy --only functions # ... # i functions: Loaded environment variables from .env. # ...
Once your your custom environment variables are deployed, your function code can access them with process.env
syntax:
// Responds with "Hello Earth and Humans"
exports.hello = functions.https.onRequest((request, response) => {
response.send(`Hello ${process.env.PLANET} and ${process.env.AUDIENCE}`);
});
Deploying multiple sets of environment variables
If you need an alternative set of environment variables for your Firebase projects (such as staging vs production), create a .env. <project or alias >
file and write your project-specific environment variables there. The environment variables from .env
and project-specific .env
files (if they exist) will be included in all deployed functions.
For example, a project could include these three files containing slightly different values for development and production:
.env | .env.dev | .env.prod |
PLANET=Earth AUDIENCE=Humans | AUDIENCE=Dev Humans | AUDIENCE=Prod Humans |
Given the values in those separate files, the set of environment variables deployed with your functions will vary depending on your target project:
$ firebase use dev
$ firebase deploy --only functions
i functions: Loaded environment variables from .env, .env.dev.
# Deploys functions with following user-defined environment variables:
# PLANET=Earth
# AUDIENCE=Dev Humans
$ firebase use prod
$ firebase deploy --only functions
i functions: Loaded environment variables from .env, .env.prod.
# Deploys functions with following user-defined environment variables:
# PLANET=Earth
# AUDIENCE=Prod Humans
Reserved environment variables
Some environment variable keys are reserved for internal use. Do not use any of these keys in your .env
files:
- All keys starting with X_GOOGLE_
- All keys starting EXT_
- All keys starting with FIREBASE_
- Any key from the following list:
- CLOUD_RUNTIME_CONFIG
- ENTRY_POINT
- GCP_PROJECT
- GCLOUD_PROJECT
- GOOGLE_CLOUD_PROJECT
- FUNCTION_TRIGGER_TYPE
- FUNCTION_NAME
- FUNCTION_MEMORY_MB
- FUNCTION_TIMEOUT_SEC
- FUNCTION_IDENTITY
- FUNCTION_REGION
- FUNCTION_TARGET
- FUNCTION_SIGNATURE_TYPE
- K_SERVICE
- K_REVISION
- PORT
- K_CONFIGURATION
Store and access sensitive configuration information
Environment variables stored in .env
files can be used for function configuration, but you should not consider them a secure way to store sensitive information such as database credentials or API keys. This is especially important if you check your .env
files into source control.
To help you store sensitive configuration information, Cloud Functions for Firebase integrates with Google Cloud Secret Manager . This encrypted service stores configuration values securely, while still allowing easy access from your functions when needed.
Create and use a secret
To create a secret, use the Firebase CLI.
To create and use a secret:
From the root of your local project directory, run the following command:
firebase functions:secrets:set SECRET_NAME
Enter a value for SECRET_NAME .
The CLI echoes a success message and warns that you must deploy functions for the change to take effect.
Before deploying, make sure your functions code allows the function to access the secret using the
runWith
parameter:exports.processPayment = functions // Make the secret available to this function .runWith({ secrets: ["SECRET_NAME"] }) .onCall((data, context) => { const myBillingService = initializeBillingService( // reference the secret value process.env.SECRET_NAME ); // Process the payment });
Deploy Cloud Functions:
firebase deploy --only functions
Now you'll be able to access it like any other environment variable. Conversely, if another function that does not specify the secret in runWith
tries to access the secret, it receives an undefined value:
exports.anotherEndpoint = functions.https.onRequest((request, response) => {
response.send(`The secret API key is ${process.env.SECRET_NAME}`);
// responds with "The secret API key is undefined" because the `runWith` parameter is missing
});
Once your function is deployed, it will have access to the secret value. Only functions that specifically include a secret in their runWith
parameter will have access to that secret as an environment variable. This helps you make sure that secret values are only available where they're needed, reducing the risk of accidentally leaking a secret.
Managing secrets
Use the Firebase CLI to manage your secrets. While managing secrets this way, keep in mind that some CLI changes require you to modify and/or redeploy associated functions. Specifically:
- Whenever you set a new value for a secret, you must redeploy all functions that reference that secret for them to pick up the latest value.
- If you delete a secret, make sure that none of your deployed functions references that secret. Functions that use a secret value that has been deleted will fail silently.
Here's a summary of the Firebase CLI commands for secret management:
# Change the value of an existing secret firebase functions:secrets:set SECRET_NAME # View the value of a secret functions:secrets:access SECRET_NAME # Destroy a secret functions:secrets:destroy SECRET_NAME # View all secret versions and their state functions:secrets:get SECRET_NAME # Automatically clean up all secrets that aren't referenced by any of your functions functions:secrets:prune
For the access
and destroy
commands, you can provide the optional version parameter to manage a particular version. Zum Beispiel:
functions:secrets:access SECRET_NAME[@VERSION]
For more information about these operations, pass -h
with the command to view CLI help.
How secrets are billed
Secret Manager allows 6 active secret versions at no cost. This means that you can have 6 secrets per month in a Firebase project at no cost.
By default, the Firebase CLI attempts to automatically destroy unused secret versions where appropriate, such as when you deploy functions with a new version of the secret. Also, you can actively clean up unused secrets using functions:secrets:destroy
and functions:secrets:prune
.
Secret Manager allows 10,000 unbilled monthly access operations on a secret. Function instances read only the secrets specified in their runWith
parameter every time they cold start. If you have a lot of function instances reading a lot of secrets, your project may exceed this allowance, at which point you'll be charged $0.03 per 10,000 access operations.
For more information, see Secret Manager Pricing .
Emulator support
Environment configuration with dotenv is designed to interoperate with a local Cloud Functions emulator .
When using a local Cloud Functions emulator, you can override environment variables for your project by setting up a .env.local
file. Contents of .env.local
take precedence over .env
and the project-specific .env
file.
For example, a project could include these three files containing slightly different values for development and local testing:
.env | .env.dev | .env.local |
PLANET=Earth AUDIENCE=Humans | AUDIENCE=Dev Humans | AUDIENCE=Local Humans |
When started in the local context, the emulator loads the environment variables as shown:
$ firebase emulators:start
i emulators: Starting emulators: functions
# Starts emulator with following environment variables:
# PLANET=Earth
# AUDIENCE=Local Humans
Secrets and credentials in the Cloud Functions emulator
The Cloud Functions emulator supports the use of secrets to store and access sensitive configuration information . By default, the emulator will try to access your production secrets using application default credentials . In certain situations like CI environments, the emulator may fail to access secret values due to permission restrictions.
Similar to Cloud Functions emulator support for environment variables, you can override secrets values by setting up a .secret.local
file. This makes it easy for you to test your functions locally, especially if you don't have access to the secret value.
Migrating from environment configuration
If you have been using environment configuration with functions.config
, you can migrate your existing configuration as environment variables (in dotenv format). The Firebase CLI provides an export command that outputs the configuration of each alias or project listed in your directory's .firebaserc
file (in the example below, local
, dev
, and prod
) as .env
files.
To migrate, export your existing environment configurations using the firebase functions:config:export
command:
firebase functions:config:export i Importing configs from projects: [project-0, project-1] ⚠ The following configs keys could not be exported as environment variables: ⚠ project-0 (dev): 1foo.a => 1FOO\_A (Key 1FOO\_A must start with an uppercase ASCII letter or underscore, and then consist of uppercase ASCII letters, digits, and underscores.) Enter a PREFIX to rename invalid environment variable keys: CONFIG\_ ✔ Wrote functions/.env.prod ✔ Wrote functions/.env.dev ✔ Wrote functions/.env.local ✔ Wrote functions/.env
Note that, in some cases, you will be prompted to enter a prefix to rename exported environment variable keys. This is because not all configurations can be automatically transformed since they may be invalid or may be a reserved environment variable key .
We recommend that you carefully review the contents of the generated .env
files before you deploy your functions or check the .env
files into source control. If any values are sensitive and should not be leaked, remove them from your .env
files and store them securely in Secret Manager instead.
You'll also need to update your functions code. Any functions that use functions.config
will now need to use process.env
instead, as shown in Environment variables .
Environment configuration
Before environment variable support was released in firebase-functions v3.18.0
, using functions.config()
was the recommended approach for environment configuration. This approach is still supported, but we recommend all new projects use environment variables instead, as they are simpler to use and improve the portability of your code.
Set environment configuration with the CLI
To store environment data, you can use the firebase functions:config:set
command in the Firebase CLI . Each key can be namespaced using periods to group related configuration together. Keep in mind that only lowercase characters are accepted in keys ; uppercase characters are not allowed.
For instance, to store the Client ID and API key for "Some Service", you might run:
firebase functions:config:set someservice.key="THE API KEY" someservice.id="THE CLIENT ID"
Retrieve current environment configuration
To inspect what's currently stored in environment config for your project, you can use firebase functions:config:get
. It will output JSON something like this:
{
"someservice": {
"key":"THE API KEY",
"id":"THE CLIENT ID"
}
}
This functionality is based on the Google Cloud Runtime Configuration API .
Use functions.config
to access environment configuration in a function
Some configuration is automatically provided under the reserved firebase
namespace. Environment configuration is made available inside your running function via functions.config()
. To use the configuration above, your code might look like this:
const functions = require('firebase-functions');
const request = require('request-promise');
exports.userCreated = functions.database.ref('/users/{id}').onWrite(event => {
let email = event.data.child('email').val();
return request({
url: 'https://someservice.com/api/some/call',
headers: {
'X-Client-ID': functions.config().someservice.id,
'Authorization': `Bearer ${functions.config().someservice.key}`
},
body: {email: email}
});
});
Use environment configuration to initialize a module
Some Node modules are ready without any configuration. Other modules need extra configuration to initialize correctly. We recommend you store this configuration in environment configuration variables rather than hard-coding it. This helps you keep your code much more portable, which lets you open source your application or easily switch between production and staging versions.
For example, to use the Slack Node SDK module, you might write this:
const functions = require('firebase-functions');
const IncomingWebhook = require('@slack/client').IncomingWebhook;
const webhook = new IncomingWebhook(functions.config().slack.url);
Prior to deploying, set the slack.url
environment config variable:
firebase functions:config:set slack.url=https://hooks.slack.com/services/XXX
Additional Environment Commands
-
firebase functions:config:unset key1 key2
removes the specified keys from the config -
firebase functions:config:clone --from <fromProject>
clones another project's environment into the currently active project.
Automatically populated environment variables
There are environment variables that are automatically populated in the functions runtime and in locally emulated functions. These include those populated by Google Cloud , as well as a Firebase-specific environment variable:
process.env.FIREBASE_CONFIG
: Provides the following Firebase project config info:
{
databaseURL: 'https://databaseName.firebaseio.com',
storageBucket: 'projectId.appspot.com',
projectId: 'projectId'
}
This configuration is applied automatically when you initialize the Firebase Admin SDK with no arguments. If you are writing functions in JavaScript, initialize like this:
const admin = require('firebase-admin');
admin.initializeApp();
If you are writing functions in TypeScript, initialize like this:
import * as functions from 'firebase-functions';
import * as admin from 'firebase-admin';
import 'firebase-functions';
admin.initializeApp();
If you need to initialize the Admin SDK with the default project configuration using service account credentials, you can load the credentials from a file and add them to FIREBASE_CONFIG
like this:
serviceAccount = require('./serviceAccount.json');
const adminConfig = JSON.parse(process.env.FIREBASE_CONFIG);
adminConfig.credential = admin.credential.cert(serviceAccount);
admin.initializeApp(adminConfig);
,Often you'll need additional configuration for your functions, such as third-party API keys or tuneable settings. The Firebase SDK for Cloud Functions offers built-in environment configuration to make it easy to store and retrieve this type of data for your project.
You can choose between three options:
- Parameterized configuration (recommended for most scenarios). This provides strongly-typed environment configuration with parameters that are validated at deploy time, which prevents errors and simplifies debugging.
- File-based configuration of environment variables . With this approach, you manually create a dotenv file for loading environment variables.
- Runtime environment configuration with the Firebase CLI and
functions.config
.
For most use cases, parameterized configuration is recommended. This approach makes configuration values available both at runtime and deploy time, and deployment is blocked unless all parameters have a valid value. Conversely, configuration with environment variables is not available at deploy time.
Parameterized configuration
Cloud Functions for Firebase provides an interface for defining configuration parameters declaratively inside your codebase. The value of these parameters is available both during function deployment, when setting deployment and runtime options, and during execution. This means that the CLI will block deployment unless all parameters have a valid value.
To define parameters in your code, follow this model:
const functions = require('firebase-functions');
const { defineInt, defineString } = require('firebase-functions/params');
// Define some parameters
const minInstancesConfig = defineInt('HELLO_WORLD_MININSTANCES');
const welcomeMessage = defineString('WELCOME_MESSAGE');
// To use configured parameters inside the config for a function, provide them
// directly. To use them at runtime, call .value() on them.
export const helloWorld = functions.runWith({ minInstances: minInstancesConfig}).https.onRequest(
(req, res) => {
res.send(`${welcomeMessage.value()}! I am a function.`);
}
);
When deploying a function with parameterized configuration variables, the Firebase CLI first attempts to load their values from local .env files. If they are not present in those files and no default
is set, the CLI will prompt for the values during deployment, and then automatically save their values to a .env
file named .env.<project_ID>
in your functions/
directory:
$ firebase deploy
i functions: preparing codebase default for deployment
? Enter a string value for ENVIRONMENT: prod
i functions: Writing new parameter values to disk: .env.projectId
…
$ firebase deploy
i functions: Loaded environment variables from .env.projectId
Depending on your development workflow, it may be useful to add the generated .env.<project_ID>
file to version control.
Configure CLI behavior
Parameters can be configured with an Options
object that controls how the CLI will prompt for values. The following example sets options to validate the format of a phone number, to provide a simple selection option, and to populate a selection option automatically from the Firebase project:
const { defineString } = require('firebase-functions/params');
const welcomeMessage = defineString('WELCOME_MESSAGE', {default: 'Hello World',
description: 'The greeting that is returned to the caller of this function'});
const onlyPhoneNumbers = defineString('PHONE_NUMBER', {input: {text:
{validationRegex: /\d{3}-\d{3}-\d{4}/, validationErrorMessage: "Please enter
a phone number in the format XXX-YYY-ZZZZ"}}});
const selectedOption = defineString('PARITY', {input: {select: {options:
[{value: "odd"}, {value: "even"}]}}})
const storageBucket = defineString('BUCKET', {input: {resource: {type:
"storage.googleapis.com/Bucket"}}, description: "This will automatically
populate the selector field with the deploying Cloud Project’s
storage buckets"})
Parameter types
Parameterized configuration provides strong typing for parameter values, and also support secrets from Cloud Secret Manager. Supported types are:
- Secret
- String
- Boolean
- Integer
- Float
Parameter values and expressions
Firebase evaluates your parameters both at deploy time and while your function is executing. Due to these dual environments, some extra care must be taken when comparing parameter values, and when using them to set runtime options for your functions.
To pass a parameter to your function as a runtime option, pass it directly:
const functions = require('firebase-functions');
const { defineInt} = require('firebase-functions/params');
const minInstancesConfig = defineInt('HELLO\_WORLD\_MININSTANCES');
export const helloWorld = functions.runWith({ minInstances: minInstancesConfig}).https.onRequest(
(req, res) => {
//…
Additionally, if you need to compare against a parameter in order to know what option to pick, you'll need to use built-in comparators instead of checking the value:
const functions = require('firebase-functions');
const { defineBool } = require('firebase-functions/params');
const environment = params.defineString(‘ENVIRONMENT’, {default: ‘dev’});
// use built-in comparators
const minInstancesConfig =environment.equals('PRODUCTION').thenElse(10, 1);
export const helloWorld = functions.runWith({ minInstances: minInstancesConfig}).https.onRequest(
(req, res) => {
//…
Parameters and parameter expressions that are only used at runtime can be accessed with their value
function:
const functions = require('firebase-functions');
const { defineString } = require('firebase-functions/params');
const welcomeMessage = defineString('WELCOME_MESSAGE');
// To use configured parameters inside the config for a function, provide them
// directly. To use them at runtime, call .value() on them.
export const helloWorld = functions.https.onRequest(
(req, res) => {
res.send(`${welcomeMessage.value()}! I am a function.`);
}
);
Built-in parameters
The Cloud Functions SDK offers three pre-defined parameters, available from the firebase-functions/params
subpackage:
-
projectId
— the Cloud project in which the function is running. -
databaseUrl
— the URL of the Realtime Database instance associated with the function (if enabled on the Firebase project). -
storageBucket
— the Cloud Storage bucket associated with the function (if enabled on the Firebase project).
These function like user-defined string parameters in all respects, except that, since their values are always known to the Firebase CLI, their values will never be prompted for on deployment nor saved to .env
files.
Secret parameters
Parameters of type Secret
, defined using defineSecret()
, represent string parameters which have a value stored in Cloud Secret Manager. Instead of checking against a local .env
file and writing a new value to the file if missing, secret parameters check against existence in Cloud Secret Manager, and interactively prompt for the value of a new secret during deployment.
Secret parameters defined in this way must be bound to individual functions that should have access to them:
const functions = require('firebase-functions');
const { defineSecret } = require('firebase-functions/params');
const discordApiKey = defineSecret('DISCORD_API_KEY');
export const postToDiscord = functions.runWith({ secrets: [discordApiKey] }).https.onRequest(
(req, res) => {
const apiKey = discordApiKey.value();
//…
Because the values of secrets are hidden until execution of the function, you cannot use them while configuring your function.
Environment variables
Cloud Functions for Firebase supports the dotenv file format for loading environment variables specified in a .env
file to your application runtime. Once deployed, the environment variables can be read via the process.env
interface.
To configure your environment this way, create a .env
file in your project, add the desired variables, and deploy:
Create a
.env
file in yourfunctions/
directory:# Directory layout: # my-project/ # firebase.json # functions/ # .env # package.json # index.js
Open the
.env
file for edit, and add the desired keys. Zum Beispiel:PLANET=Earth AUDIENCE=Humans
Deploy functions and verify that environment variables were loaded:
firebase deploy --only functions # ... # i functions: Loaded environment variables from .env. # ...
Once your your custom environment variables are deployed, your function code can access them with process.env
syntax:
// Responds with "Hello Earth and Humans"
exports.hello = functions.https.onRequest((request, response) => {
response.send(`Hello ${process.env.PLANET} and ${process.env.AUDIENCE}`);
});
Deploying multiple sets of environment variables
If you need an alternative set of environment variables for your Firebase projects (such as staging vs production), create a .env. <project or alias >
file and write your project-specific environment variables there. The environment variables from .env
and project-specific .env
files (if they exist) will be included in all deployed functions.
For example, a project could include these three files containing slightly different values for development and production:
.env | .env.dev | .env.prod |
PLANET=Earth AUDIENCE=Humans | AUDIENCE=Dev Humans | AUDIENCE=Prod Humans |
Given the values in those separate files, the set of environment variables deployed with your functions will vary depending on your target project:
$ firebase use dev
$ firebase deploy --only functions
i functions: Loaded environment variables from .env, .env.dev.
# Deploys functions with following user-defined environment variables:
# PLANET=Earth
# AUDIENCE=Dev Humans
$ firebase use prod
$ firebase deploy --only functions
i functions: Loaded environment variables from .env, .env.prod.
# Deploys functions with following user-defined environment variables:
# PLANET=Earth
# AUDIENCE=Prod Humans
Reserved environment variables
Some environment variable keys are reserved for internal use. Do not use any of these keys in your .env
files:
- All keys starting with X_GOOGLE_
- All keys starting EXT_
- All keys starting with FIREBASE_
- Any key from the following list:
- CLOUD_RUNTIME_CONFIG
- ENTRY_POINT
- GCP_PROJECT
- GCLOUD_PROJECT
- GOOGLE_CLOUD_PROJECT
- FUNCTION_TRIGGER_TYPE
- FUNCTION_NAME
- FUNCTION_MEMORY_MB
- FUNCTION_TIMEOUT_SEC
- FUNCTION_IDENTITY
- FUNCTION_REGION
- FUNCTION_TARGET
- FUNCTION_SIGNATURE_TYPE
- K_SERVICE
- K_REVISION
- PORT
- K_CONFIGURATION
Store and access sensitive configuration information
Environment variables stored in .env
files can be used for function configuration, but you should not consider them a secure way to store sensitive information such as database credentials or API keys. This is especially important if you check your .env
files into source control.
To help you store sensitive configuration information, Cloud Functions for Firebase integrates with Google Cloud Secret Manager . This encrypted service stores configuration values securely, while still allowing easy access from your functions when needed.
Create and use a secret
To create a secret, use the Firebase CLI.
To create and use a secret:
From the root of your local project directory, run the following command:
firebase functions:secrets:set SECRET_NAME
Enter a value for SECRET_NAME .
The CLI echoes a success message and warns that you must deploy functions for the change to take effect.
Before deploying, make sure your functions code allows the function to access the secret using the
runWith
parameter:exports.processPayment = functions // Make the secret available to this function .runWith({ secrets: ["SECRET_NAME"] }) .onCall((data, context) => { const myBillingService = initializeBillingService( // reference the secret value process.env.SECRET_NAME ); // Process the payment });
Deploy Cloud Functions:
firebase deploy --only functions
Now you'll be able to access it like any other environment variable. Conversely, if another function that does not specify the secret in runWith
tries to access the secret, it receives an undefined value:
exports.anotherEndpoint = functions.https.onRequest((request, response) => {
response.send(`The secret API key is ${process.env.SECRET_NAME}`);
// responds with "The secret API key is undefined" because the `runWith` parameter is missing
});
Once your function is deployed, it will have access to the secret value. Only functions that specifically include a secret in their runWith
parameter will have access to that secret as an environment variable. This helps you make sure that secret values are only available where they're needed, reducing the risk of accidentally leaking a secret.
Managing secrets
Use the Firebase CLI to manage your secrets. While managing secrets this way, keep in mind that some CLI changes require you to modify and/or redeploy associated functions. Specifically:
- Whenever you set a new value for a secret, you must redeploy all functions that reference that secret for them to pick up the latest value.
- If you delete a secret, make sure that none of your deployed functions references that secret. Functions that use a secret value that has been deleted will fail silently.
Here's a summary of the Firebase CLI commands for secret management:
# Change the value of an existing secret firebase functions:secrets:set SECRET_NAME # View the value of a secret functions:secrets:access SECRET_NAME # Destroy a secret functions:secrets:destroy SECRET_NAME # View all secret versions and their state functions:secrets:get SECRET_NAME # Automatically clean up all secrets that aren't referenced by any of your functions functions:secrets:prune
For the access
and destroy
commands, you can provide the optional version parameter to manage a particular version. Zum Beispiel:
functions:secrets:access SECRET_NAME[@VERSION]
For more information about these operations, pass -h
with the command to view CLI help.
How secrets are billed
Secret Manager allows 6 active secret versions at no cost. This means that you can have 6 secrets per month in a Firebase project at no cost.
By default, the Firebase CLI attempts to automatically destroy unused secret versions where appropriate, such as when you deploy functions with a new version of the secret. Also, you can actively clean up unused secrets using functions:secrets:destroy
and functions:secrets:prune
.
Secret Manager allows 10,000 unbilled monthly access operations on a secret. Function instances read only the secrets specified in their runWith
parameter every time they cold start. If you have a lot of function instances reading a lot of secrets, your project may exceed this allowance, at which point you'll be charged $0.03 per 10,000 access operations.
For more information, see Secret Manager Pricing .
Emulator support
Environment configuration with dotenv is designed to interoperate with a local Cloud Functions emulator .
When using a local Cloud Functions emulator, you can override environment variables for your project by setting up a .env.local
file. Contents of .env.local
take precedence over .env
and the project-specific .env
file.
For example, a project could include these three files containing slightly different values for development and local testing:
.env | .env.dev | .env.local |
PLANET=Earth AUDIENCE=Humans | AUDIENCE=Dev Humans | AUDIENCE=Local Humans |
When started in the local context, the emulator loads the environment variables as shown:
$ firebase emulators:start
i emulators: Starting emulators: functions
# Starts emulator with following environment variables:
# PLANET=Earth
# AUDIENCE=Local Humans
Secrets and credentials in the Cloud Functions emulator
The Cloud Functions emulator supports the use of secrets to store and access sensitive configuration information . By default, the emulator will try to access your production secrets using application default credentials . In certain situations like CI environments, the emulator may fail to access secret values due to permission restrictions.
Similar to Cloud Functions emulator support for environment variables, you can override secrets values by setting up a .secret.local
file. This makes it easy for you to test your functions locally, especially if you don't have access to the secret value.
Migrating from environment configuration
If you have been using environment configuration with functions.config
, you can migrate your existing configuration as environment variables (in dotenv format). The Firebase CLI provides an export command that outputs the configuration of each alias or project listed in your directory's .firebaserc
file (in the example below, local
, dev
, and prod
) as .env
files.
To migrate, export your existing environment configurations using the firebase functions:config:export
command:
firebase functions:config:export i Importing configs from projects: [project-0, project-1] ⚠ The following configs keys could not be exported as environment variables: ⚠ project-0 (dev): 1foo.a => 1FOO\_A (Key 1FOO\_A must start with an uppercase ASCII letter or underscore, and then consist of uppercase ASCII letters, digits, and underscores.) Enter a PREFIX to rename invalid environment variable keys: CONFIG\_ ✔ Wrote functions/.env.prod ✔ Wrote functions/.env.dev ✔ Wrote functions/.env.local ✔ Wrote functions/.env
Note that, in some cases, you will be prompted to enter a prefix to rename exported environment variable keys. This is because not all configurations can be automatically transformed since they may be invalid or may be a reserved environment variable key .
We recommend that you carefully review the contents of the generated .env
files before you deploy your functions or check the .env
files into source control. If any values are sensitive and should not be leaked, remove them from your .env
files and store them securely in Secret Manager instead.
You'll also need to update your functions code. Any functions that use functions.config
will now need to use process.env
instead, as shown in Environment variables .
Environment configuration
Before environment variable support was released in firebase-functions v3.18.0
, using functions.config()
was the recommended approach for environment configuration. This approach is still supported, but we recommend all new projects use environment variables instead, as they are simpler to use and improve the portability of your code.
Set environment configuration with the CLI
To store environment data, you can use the firebase functions:config:set
command in the Firebase CLI . Each key can be namespaced using periods to group related configuration together. Keep in mind that only lowercase characters are accepted in keys ; uppercase characters are not allowed.
For instance, to store the Client ID and API key for "Some Service", you might run:
firebase functions:config:set someservice.key="THE API KEY" someservice.id="THE CLIENT ID"
Retrieve current environment configuration
To inspect what's currently stored in environment config for your project, you can use firebase functions:config:get
. It will output JSON something like this:
{
"someservice": {
"key":"THE API KEY",
"id":"THE CLIENT ID"
}
}
This functionality is based on the Google Cloud Runtime Configuration API .
Use functions.config
to access environment configuration in a function
Some configuration is automatically provided under the reserved firebase
namespace. Environment configuration is made available inside your running function via functions.config()
. To use the configuration above, your code might look like this:
const functions = require('firebase-functions');
const request = require('request-promise');
exports.userCreated = functions.database.ref('/users/{id}').onWrite(event => {
let email = event.data.child('email').val();
return request({
url: 'https://someservice.com/api/some/call',
headers: {
'X-Client-ID': functions.config().someservice.id,
'Authorization': `Bearer ${functions.config().someservice.key}`
},
body: {email: email}
});
});
Use environment configuration to initialize a module
Some Node modules are ready without any configuration. Other modules need extra configuration to initialize correctly. We recommend you store this configuration in environment configuration variables rather than hard-coding it. This helps you keep your code much more portable, which lets you open source your application or easily switch between production and staging versions.
For example, to use the Slack Node SDK module, you might write this:
const functions = require('firebase-functions');
const IncomingWebhook = require('@slack/client').IncomingWebhook;
const webhook = new IncomingWebhook(functions.config().slack.url);
Prior to deploying, set the slack.url
environment config variable:
firebase functions:config:set slack.url=https://hooks.slack.com/services/XXX
Additional Environment Commands
-
firebase functions:config:unset key1 key2
removes the specified keys from the config -
firebase functions:config:clone --from <fromProject>
clones another project's environment into the currently active project.
Automatically populated environment variables
There are environment variables that are automatically populated in the functions runtime and in locally emulated functions. These include those populated by Google Cloud , as well as a Firebase-specific environment variable:
process.env.FIREBASE_CONFIG
: Provides the following Firebase project config info:
{
databaseURL: 'https://databaseName.firebaseio.com',
storageBucket: 'projectId.appspot.com',
projectId: 'projectId'
}
This configuration is applied automatically when you initialize the Firebase Admin SDK with no arguments. If you are writing functions in JavaScript, initialize like this:
const admin = require('firebase-admin');
admin.initializeApp();
If you are writing functions in TypeScript, initialize like this:
import * as functions from 'firebase-functions';
import * as admin from 'firebase-admin';
import 'firebase-functions';
admin.initializeApp();
If you need to initialize the Admin SDK with the default project configuration using service account credentials, you can load the credentials from a file and add them to FIREBASE_CONFIG
like this:
serviceAccount = require('./serviceAccount.json');
const adminConfig = JSON.parse(process.env.FIREBASE_CONFIG);
adminConfig.credential = admin.credential.cert(serviceAccount);
admin.initializeApp(adminConfig);