Skip to content

Commit

Permalink
Allow initializing the DB with Firebase private key (for Vercel deplo…
Browse files Browse the repository at this point in the history
…yment) (#11)
  • Loading branch information
carletex authored Feb 7, 2024
1 parent 44bc9ed commit c87ac67
Show file tree
Hide file tree
Showing 2 changed files with 17 additions and 5 deletions.
8 changes: 6 additions & 2 deletions packages/nextjs/.env.example
Original file line number Diff line number Diff line change
Expand Up @@ -4,9 +4,13 @@
# 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 connect to a live Firebase project, you can download the service account key JSON
# and add the path here;
GOOGLE_APPLICATION_CREDENTIALS="/<your>/<path>/<to>/firebaseServiceAccountKey.json"
# If you want to connect to the firebase emulator
# OR copy/paste these values from the JSON file (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

# Setup you project id for firebase
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 c87ac67

Please sign in to comment.