155

I have a firebase database linked up to two apps, one being an iOS app and another being a web app coded in node.js which is a basic algorithm that sets data to the database. When ever i am running the algorithm i am confronted with-

Error: No Firebase App '[DEFAULT]' has been created - call Firebase App.initializeApp(). at Error (native) at R (/Users/dd/Desktop/Code/NODE/node_modules/firebase/app-node.js:22:335) at a (/Users/dd/Desktop/Code/NODE/node_modules/firebase/app-node.js:20:68) at Object.c [as database] (/Users/dd/Desktop/Code/NODE/node_modules/firebase/app-node.js:21:447) at Object. (/Users/dd/Desktop/Code/NODE/Bot.js:24:25) at Module._compile (module.js:570:32) at Object.Module._extensions..js (module.js:579:10) at Module.load (module.js:487:32) at tryModuleLoad (module.js:446:12) at Function.Module._load (module.js:438:3) at Module.runMain (module.js:604:10) at run (bootstrap_node.js:394:7) at startup (bootstrap_node.js:149:9) at bootstrap_node.js:509:3 dd-mac:NODE dd$

Could someone please help?

0

24 Answers 24

105

You are probably invoking firebase before the app is initialized. All calls to firebase must come after .initializeApp();

firebase.initializeApp(config);
var db = firebase.firestore();
4
  • 23
    This was my problem BUT it wasn't because of the line by line order of the code, but rather the order of my IMPORTS. I was importing my code that uses firebase before my code that initialized it.
    – SeanMC
    Jan 21, 2019 at 1:47
  • 1
  • 1
    What do you mean the order of your imports? I have tried this- import firebase from '@react-native-firebase/app'; then import "@react-native-firebase/database" and it doesn't work Oct 10, 2020 at 20:00
  • This was my problem too, but for me it was happening due to Firebase being initialised in my own firebase.js file (which imports from firebase) and, in another module, I was accidentally importing from firebase instead of my (initialised) ./firebase.
    – Ruben9922
    Feb 19, 2021 at 22:13
29

If you are using angular here is a solution.

Complete tutorial source link

Use initializeApp before @NgModule

import { NgModule } from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';
import { RouteReuseStrategy } from '@angular/router';

import { IonicModule, IonicRouteStrategy } from '@ionic/angular';
import { SplashScreen } from '@ionic-native/splash-screen/ngx';
import { StatusBar } from '@ionic-native/status-bar/ngx';

import { AppComponent } from './app.component';
import { AppRoutingModule } from './app-routing.module';
import { environment } from 'src/environments/environment';
import { AuthenticateService } from './services/authentication.service';
import { AngularFireAuthModule } from '@angular/fire/auth';

import * as firebase from 'firebase';

firebase.initializeApp(environment.firebase);

@NgModule({
  declarations: [AppComponent],
  entryComponents: [],
  imports: [
    BrowserModule, 
    IonicModule.forRoot(), 
    AppRoutingModule,
    AngularFireAuthModule
  ],
  providers: [
    StatusBar,
    SplashScreen,
    AuthenticateService,
    { provide: RouteReuseStrategy, useClass: IonicRouteStrategy }
  ],
  bootstrap: [AppComponent]
})
export class AppModule {}
2
  • 35
    A library agnostic question shouldn't be answered with a library specific answer.
    – mesqueeb
    Oct 2, 2019 at 6:41
  • 2
    @mesqueeb this could be an error that only occurs in angular so then it would be fine to answer language-specific. Jun 26, 2020 at 20:04
15

If you are using React Native, this error can also happen if you did not configure the native side properly.

Documentation here: https://rnfirebase.io/

Android

First, download the google-services.json file and place it inside of your project at the following location: /android/app/google-services.json.

Then, add the google-services plugin as a dependency inside of your /android/build.gradle

buildscript {
  dependencies {
    // ... other dependencies
    classpath 'com.google.gms:google-services:4.3.10'
    // Add me --- /\
  }
}

Lastly, execute the plugin by adding the following to your /android/app/build.gradle

apply plugin: 'com.android.application'
apply plugin: 'com.google.gms.google-services' // <- Add this line

iOS

First, Add your GoogleService-Info.plist file to the project through xcode. Make sure it shows up in build phases so you know it's added to the project and not just the folder.

Then, open your /ios/{projectName}/AppDelegate.m file, and add the following:

At the top of the file, import the Firebase SDK:

#import <Firebase.h>

Within your existing didFinishLaunchingWithOptions method, add the following to the top of the method:

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
  // Add me --- \/
  [FIRApp configure];
  // Add me --- /\
  // ...
}
13

If you using Dart and Flutter

  1. add firebase_core dependency to pubspac.ymal.
  2. go to main.dart
  3. import 'package:firebase_core/firebase_core.dart';

4.add async in main()

follow my code

void main() async {
  WidgetsFlutterBinding.ensureInitialized();
  await Firebase.initializeApp();
  runApp(MyApp());
}

class MyApp extends StatelessWidget {
  var fsconnect = FirebaseFirestore.instance;

  myget() async {
    var d = await fsconnect.collection("students").get();
    // print(d.docs[0].data());

    for (var i in d.docs) {
      print(i.data());
    }
  }

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
        home: Scaffold(
      appBar: AppBar(
        title: Text('Firebase Firestore App'),
      ),
      body: Column(
        children: <Widget>[
          RaisedButton(
            child: Text('send data'),
            onPressed: () {
              fsconnect.collection("students").add({
                'name': 'sarah',
                'title': 'xyz',
                'email': 'sarah@gmail.com',
              });
              print("send ..");
            },
          ),
          RaisedButton(
            child: Text('get data'),
            onPressed: () {
              myget();
              print("get data ...");
            },
          )
        ],
      ),
    ));
  }
}
2
  • 1
    does this work for you. I tried same thing adding async in Main. Doesn't solve the issue. Now I follow link . The link also doesn't solve. getting the error Firebase is not initialized. Sep 22, 2020 at 13:57
  • 1
    That solution didn't work for me either. I did everything correctly and according to this video youtube.com/watch?v=Z0jFkP0A3B0 but unfortunately I still get the error message...
    – Tom
    Oct 16, 2021 at 12:49
8

I had a similar issue following Firebase's online guide found here.

The section heading "Initialize multiple apps" is misleading as the first example under this heading actually demonstrates how to initialize a single, default app. Here's said example:

// Initialize the default app
var defaultApp = admin.initializeApp(defaultAppConfig);

console.log(defaultApp.name);  // "[DEFAULT]"

// Retrieve services via the defaultApp variable...
var defaultAuth = defaultApp.auth();
var defaultDatabase = defaultApp.database();

// ... or use the equivalent shorthand notation
defaultAuth = admin.auth();
defaultDatabase = admin.database();

If you are migrating from the previous 2.x SDK you will have to update the way you access the database as shown above, or you will get the, No Firebase App '[DEFAULT]' error.

Google has better documentation at the following:

  1. INITIALIZE: https://firebase.google.com/docs/database/admin/start

  2. SAVE: https://firebase.google.com/docs/database/admin/save-data

  3. RETRIEVE: https://firebase.google.com/docs/database/admin/retrieve-data

7

My problem was because I added a second parameter:

AngularFireModule.initializeApp(firebaseConfig, 'reservas')

if I remove the second parameter it works fine:

AngularFireModule.initializeApp(firebaseConfig)
2
  • Does it matter if you use firebase.initializeApp as opposed to AngularFireModule.initializeApp
    – D.Hodges
    Aug 25, 2020 at 1:56
  • 1
    The second parameter creates a new "app" handle. If one omits that parameter, the app name [DEFAULT] is implied, thus "the default app". Why this mattered for you is likely that code can implicitly use the default by eg. firebase.firestore() whereas with the custom "app" (first) the return value, an "app handle" must be passed around. I use both ways. The default for the main web app and the named variant within a library.
    – akauppi
    Feb 19, 2021 at 9:17
5

This may not be best answer but, I had to initialize app with admin and firebase like below. I use admin for it's own purposes and firebase as well.

const firebase = require("firebase");
const admin = require("firebase-admin");

admin.initializeApp(functions.config().firebase);
firebase.initializeApp(functions.config().firebase);
// Get the Auth service for the default app
var authService = firebase.auth();

 function createUserWithEmailAndPassword(request, response) {
        const email = request.query.email;
        const password = request.query.password;
        if (!email) {
            response.send("query.email is required.");
            return;
        }
        if (!password) {
            response.send("query.password is required.");
            return;
        }
        return authService.createUserWithEmailAndPassword(email, password)
            .then(success => {
                let responseJson = JSON.stringify(success);
                console.log("createUserWithEmailAndPassword.responseJson", responseJson);
                response.send(responseJson);
            })
            .catch(error => {
                let errorJson = JSON.stringify(error);
                console.log("createUserWithEmailAndPassword.errorJson", errorJson);
                response.send(errorJson);
            });
    }
4

Flutter web

For me the error occurred when I run my application in "release" mode

flutter run -d chrome --release

and when I deployed the application on the Firebase hosting

firebase deploy

Solution

Since I initialized Firebase in the index.html, I had to change the implementation order of firebase and main.dart.js

<script>
  var firebaseConfig = {
  apiKey: "xxxxxxxxxxxxxxxxxxxxxx",
  authDomain: "xxxxxxxxxxx.firebaseapp.com",
  databaseURL: "https://xxxxxxxxxx.firebaseio.com",
  projectId: "xxxxxxxxxxx",
  storageBucket: "xxxxxxxx.appspot.com",
  messagingSenderId: "xxxxxxxxxxx",
  appId: "1:xxxxxxxxxx:web:xxxxxxxxxxxxx",
  measurementId: "G-xxxxxxxxx"
  };
  // Initialize Firebase
  firebase.initializeApp(firebaseConfig);
  firebase.analytics();
</script>

//moved below firebase init
<script src="main.dart.js" type="application/javascript"></script>
1
  • 1
    This solves the issue
    – Dario Brux
    Nov 1, 2021 at 23:44
3

The answer may already be given somewhere but here is my take to this error which may be thrown for multiple reasons:

  1. Default app is initialized after the other one. Correct way is to initialize the default app first and then the rest.
  2. firebase.apps.app() is being called before default app initialization. This code is basically returning the default app instance. Since it is not present, hence the error.
  3. Lastly, you are initializing other firebase services like auth, database, firestore, etc before app is initialized.
2
  • For me it was #3. I had named exports {firebaseClient, dbClient,authClient,storageClient} where the individual services were defined as const dbClient = firebaseClient.firestore(); ....
    – arunmenon
    Dec 29, 2020 at 12:40
  • Hadn't heard of 1. Will check!
    – akauppi
    Feb 19, 2021 at 9:26
3

If you are on react native and developing for IOS then I think you forgot the linking steps of firebase module.

follow the below steps..!

open your /ios/{projectName}/AppDelegate.m file, and add the following:

At the top of the file, import the Firebase SDK:

#import <Firebase.h>

Within your existing didFinishLaunchingWithOptions method, add the following to the top of the method:

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
  // Add this  --- \/
  if ([FIRApp defaultApp] == nil) {
    [FIRApp configure];
  }
  // Add me --- /\
  // ...
}
2

If you are starting out a react-native app and seeing this issue, then you have to follow all the instructions listed in firebase (when you setup iOS/android app) or the instructions @ React-native google auth android DEVELOPER_ERROR Code 10 question

enter image description here

2

Got the same error while working with iOS. Hope you have already installed the Firebase using pods. You need to do the following. Open the Xcode and open AppDelegate.m file and import

#import "FIRApp.h"

Now call configure method in didFinishLaunchingWithOptions delegate method

  [FIRApp configure];

Now run your app. It should work. Here is doc link

1

YOU CALL THIS IN JADE: firebase.initializeApp(config); IN THE BEGIN OF THE FUNC

script.
    function signInWithGoogle() {
        firebase.initializeApp(config);
        var googleAuthProvider = new firebase.auth.GoogleAuthProvider
        firebase.auth().signInWithPopup(googleAuthProvider)
        .then(function (data){
            console.log(data)
        })
        .catch(function(error){
            console.log(error)
        })
    }
2
  • I don't think this is relevant to the question stated.
    – akauppi
    Feb 19, 2021 at 9:14
  • @akauppi It is related. I used this solution in angular. Instead of writing in app module, I just included in the beginning of the function. Feb 18, 2022 at 17:39
1

This error is because you are trying to use firebase function before it has successfully initialised

Fix:

Place the function you want to call inside setInterval block such that the function is called only once the app has been initialised:

 let isFirebaseAppDefined = false;
    setInterval(() => {
      if (!isFirebaseAppDefined) {
        if (firebase.app()) {

          // Function that needs to run after the initialisation comes here
          // Example re-captcha verifier or other auth function

          isFirebaseAppDefined = true;
        }
      }
    }, 100);
1

another solution is here.

use APP_INITIALIZER

https://angular.io/api/core/APP_INITIALIZER

export function appInitializer() {
  return () => firebase.initializeApp(firebaseConfig);
}

...
@NgModule({
 ...
 providers: [{
   provide: APP_INITIALIZER,
   useFactory: () => appInitializer
   multi: true
  }]
 })
export class AppModule {}
1

I got this error in ios when I updated the React Native version, add this instruction in method: didFinishLaunchingWithOptions from file: ios/{AppName}/AppDelegate.m

   if ([FIRApp defaultApp] == nil) {
     [FIRApp configure];
   }

It should look like this: enter image description here

0

Use Initialize app in the app.module.ts

import { environment } from 'src/environments/environment';
firebase.initializeApp(environment.firebase);

This will clear the error.
You can use firebase.database() without any errors

0

I had the same issue. When I tried adding my flutter web app to firebase I took the Script tags google gave me in the setup process and pasted them into my index.html. That didn't work for me even AFTER I modified my main.dart with the following lines in the main method:

WidgetsFlutterBinding.ensureInitialized();
await Firebase.initializeApp();
runApp(MyApp());

Using the Script in the format posted here I got it working: https://firebase.flutter.dev/docs/installation/web

If there are other people having the same issue and blindly copying the Script Tags Google gives you in the Firebase Setup.... this helped me. Just get it into the format posted by FlutterFire.

0

in my case i was using

getAuth()
getFirestore()

with out passing the app instead use it like

const app = initializeApp(config);
const auth = getAuth(app);
const db = getFirestore(app);
0

Step 1:

Using npm

npm install --save @react-native-firebase/app

Using Yarn

yarn add @react-native-firebase/app

step 2: Generating Android credentials in https://console.firebase.google.com/ The "Android package name" must match your local project's package name which can be found inside of the manifest tag within the /android/app/src/main/AndroidManifest.xml file within your project.

Download the google-services.json file and place it inside of your project at the following location: /android/app/google-services.json.

step3: and then add the google-services plugin as a dependency inside of your /android/build.gradle file: classpath 'com.google.gms:google-services:4.3.13'

Lastly, execute the plugin by adding the following to your /android/app/build.gradle file: apply plugin: 'com.android.application' apply plugin: 'com.google.gms.google-services' // <- Add this line

That's all....

1
  • Your answer could be improved with additional supporting information. Please edit to add further details, such as citations or documentation, so that others can confirm that your answer is correct. You can find more information on how to write good answers in the help center.
    – Community Bot
    Sep 17, 2022 at 14:26
0

Use this: https://github.com/abhi3700/My_Learning_Databases/tree/main/Firebase#initialize-firestore

const fs = require("firebase-admin");

const serviceAccount = require("../../../helper/serviceAccountKey.json");

let db = null;

// initialize firebase
if (!fs.apps.length) {
  fs.initializeApp({
    credential: fs.credential.cert(serviceAccount),
    // name: "zippy-mvp2",
  });

  db = fs.firestore();

  // allow undefined values.
  db.settings({
    ignoreUndefinedProperties: true,
  });
} else {
  db = fs.app().firestore();
}
-1

I think This Error is Arrived Because of You are using Class Component in Respective React Platform that Doesn't get Proper Configuration. So You Write Configuration in componentWillMount().

componetWillMount() {
const config = {
apiKey: “xxxxxxxxxxxxxxxxxxxxxxxx”,
authDomain: “auth-bdcdc.firebaseapp.com 20”,
databaseURL: “https://auth-bdcdc.firebaseio.com 7”,
projectId: “auth-bdcdc”,
storageBucket: “auth-bdcdc.appspot.com 2”,
messagingSenderId: “xxxxxxxxxx”
};
-1

In my case the solution was remplace this

const firebaseConfig = {
        apiKey: "",
        authDomain: "",
        databaseURL: "",
        projectId: "",
        storageBucket: "",
        messagingSenderId: "",
        appId: "",
        measurementId: ""
    };
const app = initializeApp(firebaseConfig);

to this.....

import { initializeApp } from "https://www.gstatic.com/firebasejs/9.6.8/firebase-app.js";
firebase.initializeApp({
        apiKey: "",
        authDomain: "",
        databaseURL: "",
        projectId: "",
        storageBucket: "",
        messagingSenderId: "",
        appId: "",
        measurementId: ""
    });

I hope it works for you :)

1
  • It doesn't work
    – abhi3700
    Sep 29, 2022 at 11:56
-2

I found the solution!

Follow these steps:

Flutter Firebase and Android issue - unable to Initialise. Cannot find google-services.json with latest migration instructions executed

After that, execute:

flutter build apk --debug
flutter build apk --profile
flutter build apk --release

and then, run app! it works for me!

1
  • Can you summarize the steps in your link, or describe why this solution fixed the issue? As it stands, this neither provides a solution nor provides any explanation to solve the OP's problem.
    – MJ12358
    Mar 18, 2022 at 4:34

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.