Skip to content

Commit

Permalink
Allow initialize DB with firebase private key
Browse files Browse the repository at this point in the history
  • Loading branch information
carletex committed Feb 7, 2024
1 parent 44bc9ed commit 9625dcb
Show file tree
Hide file tree
Showing 2 changed files with 16 additions and 4 deletions.
6 changes: 5 additions & 1 deletion packages/nextjs/.env.example
Original file line number Diff line number Diff line change
Expand Up @@ -4,8 +4,12 @@
# Firebase live vs local emulator.
# Important: Only one of the following lines should be uncommented at a time.

# If you want to connecto to a live firebase project, you can use download the service account key json file and add the path here
# If you want to connecto to a live firebase project, you can use download the service account key json
# and add the path here;
GOOGLE_APPLICATION_CREDENTIALS="/<your>/<path>/<to>/firebaseServiceAccountKey.json"
# OR extract copy/paste this values (easier for production environments):
FIREBASE_CLIENT_EMAIL="your_firebase_admin_sdk_email@your_project_id.iam.gserviceaccount.com"
FIREBASE_PRIVATE_KEY="-----BEGIN...END PRIVATE"
# If you want to connect to the firebase emulator
FIRESTORE_EMULATOR_HOST=localhost:8080

Expand Down
14 changes: 11 additions & 3 deletions packages/nextjs/services/database/firestoreDB.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import { applicationDefault, getApps, initializeApp } from "firebase-admin/app";
import { applicationDefault, cert, getApps, initializeApp } from "firebase-admin/app";
import { getFirestore } from "firebase-admin/firestore";

const getFirestoreConnector = () => {
Expand All @@ -9,12 +9,20 @@ const getFirestoreConnector = () => {
}

if (process.env.GOOGLE_APPLICATION_CREDENTIALS) {
console.log("Initializing LIVE Firestore");
console.log("Initializing LIVE Firestore with GOOGLE_APPLICATION_CREDENTIALS");
initializeApp({
credential: applicationDefault(),
});
} else if (process.env.FIREBASE_PRIVATE_KEY) {
console.log("Initializing LIVE Firestore with FIREBASE_PRIVATE_KEY");
initializeApp({
credential: cert({
projectId: process.env.FIREBASE_PROJECT_ID,
privateKey: process.env.FIREBASE_PRIVATE_KEY?.replace(/\\n/g, "\n"),
clientEmail: process.env.FIREBASE_CLIENT_EMAIL,
}),
});
} else {
// ToDo. Something is not working. Getting "Error: Could not load the default credentials."
console.log("Initializing local Firestore instance");
initializeApp({
projectId: process.env.FIREBASE_PROJECT_ID,
Expand Down

0 comments on commit 9625dcb

Please sign in to comment.