1

I am trying to use Firebase in my Nodejs project but I keep getting an error and I cannot figure it out.

my firebase.ts

import firebase from 'firebase/app'
import "firebase/database"
const config = {
  apiKey: "xxxxx",
  authDomain: "xxxx.firebaseapp.com",
  databaseURL: "https://xxxxx.firebaseio.com",
  projectId: "xxxxx",
  storageBucket: "xxxxx.appspot.com",
  messagingSenderId: "xxxxx",
  appId: "xxxxx"
};
firebase.initializeApp(config);
export const databaseRef = firebase.database();
export default firebase;

index.ts

export * from './firebase';

Where it is used

import { databaseRef } from '../../common/services/firebase'

await databaseRef.ref('dummy')

I got this error

TypeError: Cannot read property 'ref' of undefined

Frank van Puffelen
  • 565,676
  • 79
  • 828
  • 807
King
  • 1,885
  • 3
  • 27
  • 84
  • The init code and database creation looks correct but your export is fine as well. That leads me to believe the databaseRef is undefined after the `firebase.database()` call. Have you tried logging that variable in the `firebase.ts` file? – Special Character Jan 12 '21 at 20:09
  • no @SpecialCharacter I am just confused. – King Jan 12 '21 at 20:10
  • Does this answer your question? [Cannot read property 'ref' of undefined](https://stackoverflow.com/questions/47253938/cannot-read-property-ref-of-undefined) – Biswajit Panday Jan 12 '21 at 20:11
  • databaseRef is undefined. but why? – King Jan 12 '21 at 20:12
  • @BiswajitPanday the solution there is similar to what I have here. – King Jan 12 '21 at 20:13

1 Answers1

0

Instead of exporting firebase.database() first, try exporting firebase.initializeApp(config)

If the file is to be loaded a second time, check for the existing firebase app instance first.

I am using Firebase Cloud Messaging but the logic should be similar:

// Dependencies
const firebase = require('firebase-admin');

// Service account creds
const serviceAccount = require('../../creds/creds.json');

// Initalize the firebase app
const config = {
    credential: firebase.credential.cert(serviceAccount),
};

// Check for existing firebase app instance
if (!firebase.apps.length) {
    // Create a new one if there is none
    const fb = firebase.initializeApp(config);
    module.exports = { fb, };
} else {
    // otherwise export the existing one
    const fb = firebase.app();
    module.exports = { fb, };
}

Algo7
  • 2,122
  • 1
  • 8
  • 19