I am a newbie in JavaScript. Recently I have installed firebase admin and kept the code in global scope, database.js. Like this.
import app from 'firebase-admin';
import firebase_key from './firebase_key.js';
app.initializeApp({
credential: app.credential.cert(firebase_key),
databaseURL: "https://study-boss-681fa-default-rtdb.firebaseio.com"
});
console.log('database started');
export default app.database();
Now I want to access this database from my service class. My serice class is
import { getDatabase} from "firebase-admin/database";
const database = getDatabase();
This service class code is throwing the following error. FirebaseAppError: The default Firebase app does not exist. Make sure you call initializeApp() before using any of the Firebase services.
If you are just using getDatabase()
directly then there's a high chance that it's being access before your initializeApp
is executed. I would recommend initializing all Firebase services in a single file and importing them wherever required as shown below:
import { initializeApp } from 'firebase-admin/app';
import { getDatabase } from 'firebase-admin/database';
import firebase_key from './firebase_key.js';
const app = initializeApp({
credential: app.credential.cert(firebase_key),
databaseURL: "https://study-boss-681fa-default-rtdb.firebaseio.com"
});
const database = getDatabase(app);
console.log('database started');
export { database };
Now you can import { database } from "..path/to/firebase.js"
wherever required.