Currently, I am facing an issue while attempting to deploy a Next JS app to Firebase hosting using the web framework option provided by firebase-tools. The problem arises when trying to initialize firebase-admin as it seems to never properly initialize when fetching data or performing any related tasks. Here is how I am initializing it, which works fine locally:
firebase/firebaseAdminInit.ts
import admin from 'firebase-admin';
export function GetFirebaseAdminApp() {
if(admin.apps.length === 0){
const app = admin.initializeApp({
credential:admin.credential.cert({
clientEmail: process.env.NEXT_FIREBASE_CLIENT_EMAIL as string,
projectId: process.env.NEXT_PUBLIC_FIREBASE_PROJECT_ID as string,
privateKey: process.env.NEXT_FIREBASE_PRIVATE_KEY as string
}),
databaseURL: process.env.NEXT_PUBLIC_FIREBASE_DATABASE_URL as string,
storageBucket: process.env.NEXT_PUBLIC_STORAGE_BUCKET as string
});
return app;
}
return admin.app();
}
How I use it:
lib/repository/products.ts
import { getFirelord, getFirestore, getDocs, query, orderBy, limit, offset, getCountFromServer, addDoc, updateDoc, getDoc, deleteDoc } from "firelord";
import { ProductsMetaType } from "./dtoModels";
import { Product, ProductRequest, productToDomain, productType_toDto } from "../domain/Products";
import { GetFirebaseAdminApp } from "../../firebase/firebaseAdminInit";
import { PagedQuery, PagedResult } from "../domain/PagedQueries";
import formidable from "formidable";
import { DeleteImage, UploadImage } from "./objectStorage";
const app = getFirestore(GetFirebaseAdminApp()); //This should return the firebase-admin app
const productFl = getFirelord<ProductsMetaType>(app, 'Products');
export async function GetAllProducts() {
const docs =
await getDocs(productFl.collection()).then(qSnapshot =>
qSnapshot.docs.map(docSnapshot => docSnapshot.data())
).then(dtoArr => dtoArr.map(productToDomain))
return docs;
}
Upon logging the app in the firebaseAdminInit.ts file, I can see that there is some value present, not null or undefined. However, when used elsewhere, it fails with an error stating that it's not initialized:
FirebaseAppError: The default Firebase app does not exist. Make sure you call initializeApp() before using any of the Firebase services.