[javascript] Error: No Firebase App '[DEFAULT]' has been created - call Firebase App.initializeApp()

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?

The answer is


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 {}

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


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”
};

add async in main()

and await before

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': '[email protected]',
              });
              print("send ..");
            },
          ),
          RaisedButton(
            child: Text('get data'),
            onPressed: () {
              myget();
              print("get data ...");
            },
          )
        ],
      ),
    ));
  }
}

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.

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!


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);
            });
    }

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)
        })
    }

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>

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


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();

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)

Examples related to javascript

need to add a class to an element How to make a variable accessible outside a function? Hide Signs that Meteor.js was Used How to create a showdown.js markdown extension Please help me convert this script to a simple image slider Highlight Anchor Links when user manually scrolls? Summing radio input values How to execute an action before close metro app WinJS javascript, for loop defines a dynamic variable name Getting all files in directory with ajax

Examples related to ios

Adding a UISegmentedControl to UITableView Crop image to specified size and picture location Undefined Symbols error when integrating Apptentive iOS SDK via Cocoapods Keep placeholder text in UITextField on input in IOS Accessing AppDelegate from framework? Autoresize View When SubViews are Added Warp \ bend effect on a UIView? Speech input for visually impaired users without the need to tap the screen make UITableViewCell selectable only while editing Xcode 12, building for iOS Simulator, but linking in object file built for iOS, for architecture arm64

Examples related to node.js

Hide Signs that Meteor.js was Used Querying date field in MongoDB with Mongoose SyntaxError: Cannot use import statement outside a module Server Discovery And Monitoring engine is deprecated How to fix ReferenceError: primordials is not defined in node UnhandledPromiseRejectionWarning: This error originated either by throwing inside of an async function without a catch block dyld: Library not loaded: /usr/local/opt/icu4c/lib/libicui18n.62.dylib error running php after installing node with brew on Mac internal/modules/cjs/loader.js:582 throw err DeprecationWarning: Buffer() is deprecated due to security and usability issues when I move my script to another server Please run `npm cache clean`

Examples related to firebase

How can I solve the error 'TS2532: Object is possibly 'undefined'? Getting all documents from one collection in Firestore FirebaseInstanceIdService is deprecated Failed to resolve: com.google.firebase:firebase-core:16.0.1 NullInjectorError: No provider for AngularFirestore Firestore Getting documents id from collection How to update an "array of objects" with Firestore? firestore: PERMISSION_DENIED: Missing or insufficient permissions Cloud Firestore collection count iOS Swift - Get the Current Local Time and Date Timestamp

Examples related to firebase-realtime-database

Error: No Firebase App '[DEFAULT]' has been created - call Firebase App.initializeApp() Firebase Permission Denied how to get all child list from Firebase android Android Firebase, simply get one child object's data Query based on multiple where clauses in Firebase Firebase Storage How to store and Retrieve images