'No Firebase App '[DEFAULT]' has been created' even though initializeApp is called - javascript

I am trying to add Firebase (Firestore) to my Nuxt project, however I am recieving the following error when initialising a const from firebase.firestore() in my index.vue file:
Uncaught FirebaseError: Firebase: No Firebase App '[DEFAULT]' has been
created - call Firebase App.initializeApp() (app/no-app).
I have installed Firebase in my project and also the module (#nuxtjs/firebase).
My nuxt.config.js file looks like this:
export default {
...
plugins: ['~/plugins/firebase.js'],
components: true,
buildModules: [
'#nuxt/typescript-build',
'#nuxtjs/tailwindcss',
],
modules: [],
...
}
And my firebase.js file is within my plugins folder as follows:
import firebase from 'firebase/app'
const config = {
...
}
let app = null
if (!firebase.apps.length) {
app = firebase.initializeApp(config)
}
export default firebase
I've compared the above to other examples online and haven't spotted any issues. However I'm new to everything from Nuxt to Firebase, so I may be missing something obvious. Any suggestions appreciated.

This typically happens if you call initializeApp() more than once on a single firebase app. If you're working with a single firebase db, make sure to initialize it when your app starts.

According to this GitHub Discussion this snippet for firebase.js should work:
import fb from "firebase/app"
export const firebase = !fb.apps.length ? fb.initializeApp(firebaseConfig) : fb.app()
// somecomponent.js
import {firebase} from "../firebase.js"
// do your firebase stuff here
Credit to #Brunocrosier with his post; even though this snippet isn't case-specific, I decided to include it for the sake of completeness.
Besides this thread - generally speaking, Uncaught FirebaseError: Firebase: No Firebase App '[DEFAULT]' has been created - call Firebase App.initializeApp() (app/no-app). is often a result of of either calling firebase. before initializing via .initializeApp(); or by calling .initializeApp() multiple times (for example Next.js might try to initialize it on the back- as well as the frontend - which seems to be the case in your code) within your firebase app.
Hence as a solution I highly suggest to move your initialization to the firebase.js file in order to initialize it directly when your app starts.
For further reading purposes:
The nuxt/firebase documentation
Error: No Firebase App '[DEFAULT]' has been created - call Firebase App.initializeApp()
The previously mentioned GitHub Discussion
FireBase JavaScript documentation

This normally happens when you try to access firestore before initializing the firebase. So as default we can check if firebase is initialized or not by firebase.apps.length but it's not a good practice to initialize firebase each and every time.
so if you are only using firestore then in your plugin you can export firestore directly after initialization like following,
import firebase from 'firebase/app'
const config = {
...
}
let app = null
if (!firebase.apps.length) {
app = firebase.initializeApp(config)
}
export default firebase.firestore()
But since you are working with nuxt there is special nuxt package called firebase/nuxt
with that installed you can define your configuration in nuxt config inside the module section as bellow,
modules: [
[
'#nuxtjs/firebase',
{
config: {
apiKey: '<apiKey>',
authDomain: '<authDomain>',
databaseURL: '<databaseURL>',
projectId: '<projectId>',
storageBucket: '<storageBucket>',
messagingSenderId: '<messagingSenderId>',
appId: '<appId>',
measurementId: '<measurementId>'
},
services: {
auth: true // Just as example. Can be any other service.
}
}
]
],
I think it is a better way to use firebase inside the nuxt.js

Related

Why does Firebase Admin SDK have a starting app length of 1?

I have a NextJS app that uses getStaticProps to pre-fetch data from firebase storage and firestore. Since getStaticProps never runs on the client, I decided to use Firebase Admin SDK to fetch my data. I initialize the app by using a seperate js file that initializes the app if the length of the initialized apps is 0, like so:
import * as admin from "firebase-admin"
if (!admin.app.length) {
try {
admin.initializeApp({
credential: admin.credential.cert({
clientEmail: process.env.FIREBASE_CLIENT_EMAIL,
privateKey: process.env.FIREBASE_PRIVATE_KEY,
projectId: process.env.NEXT_PUBLIC_FIREBASE_PROJECT_ID,
}),
storageBucket: process.env.NEXT_PUBLIC_FIREBASE_STORAGE_BUCKET,
})
} catch (e) {
console.error("Unable to initialize app!");
console.log(e)
}
}
export default admin;
For some reason, when importing this module and using the admin variable, the app crashes, telling me that I haven't Initialized an app. Doing a console log before the if check shows the the length of admin.app is 1, even though it says that I haven't initialized it.
Why is this the case? I can fix the bug by just using admin.app.length <= 1 as the if check, but I am confused on why an app is initialized before I called initializeApp.

Using Firebase with npm

I would like to use Firebase in my project with NPM and I installed it using "npm i firebase".
This worked fine so I made a new file called "app.js".
Here I would like to put my Firebase code, but it's not working, I get the following error message in my console:
Failed to load module script: Expected a JavaScript module script but the server responded with a MIME type of "text/html". Strict MIME type checking is enforced for module scripts per HTML spec.
I put the script in my in HTML with type="module":
<script src="./app.js" defer type="module"></script>
How can I fix this?
Here's my Firebase code that's in app.js
//MODULE DUS GEEN IIFE
// Import the functions you need from the SDKs you need
import { initializeApp } from "../../node_modules/firebase/app";
import { getAuth, signInWithPopup, GoogleAuthProvider } from "../../node_modules/firebase/auth";
import { getDatabase } from "../../node_modules/firebase/database";
// TODO: Add SDKs for Firebase products that you want to use
// https://firebase.google.com/docs/web/setup#available-libraries
// Your web app's Firebase configuration
// For Firebase JS SDK v7.20.0 and later, measurementId is optional
const firebaseConfig = {
apiKey: "",
authDomain: "",
projectId: "",
storageBucket: "",
messagingSenderId: "",
appId: "",
measurementId: ""
};
// Initialize Firebase
const app = initializeApp(firebaseConfig);
const analytics = getAnalytics(app);
const provider = new GoogleAuthProvider();
const auth = getAuth();
const database = getDatabase(app);
signin.addEventListener("click", () => {
console.log("hi")
})
Thanks in advance!
EDIT: Pictures of my node modules folder and firebase.
Try using it as a normal text/javascript instead of module
Since modules normally use strict mode, it probably doesn't have all the features of a module resulting in the file not loading as expected, as stated here in the core JS module features
https://javascript.info/modules-intro#core-module-features
Edit: The issue is with the path to the file you're importing. As seen in the screenshot below, this is the directory structure in '......node_modules/firebase/app':
So, the file you're importing actually doesn't exist there, that's why the 404 error HTML page.
That method works when running the app in a node environment, like React. Now for a browser, there are some files just within the '......node_modules/firebase/' directory which can be used in a web-browser environment
For your project, the files are:
firebase-app.js
firebase-auth.js
firebase-database.js
As in the screenshot below
So to import them in your file, do it this way:
import { initializeApp } from "../../node_modules/firebase/firebase-app";
import { getAuth, signInWithPopup, GoogleAuthProvider } from "../../node_modules/firebase/firebase-auth";
import { getDatabase } from "../../node_modules/firebase/firebase-database";

Vue + Firebase: Functions useEmulator() ignored

I found this line of code in the Firebase docs firebase.functions().useEmulator('localhost', 5001) that supposedly points your Vue app to the locally running emulator, but for some reason my project is ignoring said line of code and continues to call the remotely deployed function instead.
Here's what the relevant part of my #/plugins/firebase.js looks like:
import firebase from 'firebase/app';
import 'firebase/functions';
firebase.initializeApp({
apiKey: process.env.VUE_APP_FIREBASE_API_KEY,
authDomain: process.env.VUE_APP_FIREBASE_AUTH_DOMAIN,
databaseURL: process.env.VUE_APP_FIREBASE_DATABASE_URL,
projectId: process.env.VUE_APP_FIREBASE_PROJECT_ID,
storageBucket: process.env.VUE_APP_FIREBASE_STORAGE_BUCKET,
messagingSenderId: process.VUE_APP_FIREBASE_MESSAGE_SENDER_ID,
appId: process.env.VUE_APP_FIREBASE_APP_ID,
measurementId: process.env.VUE_APP_FIREBASE_MEASUREMENT_ID
});
firebase.functions().useEmulator('localhost', 5001);
const func = {
botcheck: firebase.app().functions('europe-west2').httpsCallable('validateRecaptcha'),
};
export { func };
And then to call the botcheck function, I'll run the following in a Vuex action:
const fb = require('#/plugins/firebase');
...
await fb.func.botcheck();
What am I doing wrong? How do I get it to correctly point to my locally running emulator?
Vue project versions:
vue: 2.6.11
firebase: 8.3.2
Functions project versions:
firebase-admin: 9.2.0
firebase-functions: 3.11.0
Let me know if I need to include additional information.
This line:
firebase.functions()
is functionally equivalent to:
firebase.app().functions('us-central1')
In your current code, you connect functions that don't specify a region to the emulator. Because you specify the region as europe-west2 when using it, you need to connect the europe-west2 functions to the emulator. You can do this by changing this line:
firebase.functions().useEmulator('localhost', 5001);
to use the correct region:
firebase.app().functions('europe-west2').useEmulator('localhost', 5001)
Additional Note: While firebase.functions() and firebase.app().functions() return the same instance of a Functions object (connected to the us-central1 region), firebase.app().functions('us-central1') (where you pass in the region) returns a different instance of Functions. You would need to connect each instance that you use to the emulator.
Here's your code as I make sure that useEmulator() is configured properly with Cloud Functions for Firebase Emulator. Feel free to try it:
import firebase from 'firebase/app';
import 'firebase/functions';
const firebaseConfig = {
// Your config
};
const app = firebase.initializeApp(firebaseConfig);
const functions = app.functions('europe-west2');
functions.useEmulator('localhost', 5001);
const func = {
botcheck: functions.httpsCallable('validateRecaptcha'),
};
export { func };

Firebase works fine in Web App but it's giving me the error while I try to run it on Android [duplicate]

When I try to initialize Firebase Cloud Firestore, I ran into the following error:
Uncaught TypeError: WEBPACK_IMPORTED_MODULE_0_firebase.firestore is not a function
I installed firebase with npm install firebase --save previously.
import * as firebase from 'firebase';
import router from '../router';
const config = {
apiKey: "a",
authDomain: "a",
databaseURL: "a",
projectId: "a",
storageBucket: "a",
messagingSenderId: "a"
};
if(!firebase.apps.length){
firebase.initializeApp(config);
let firestore = firebase.firestore();
}
I fixed it by importing multiple libraries: firebase and firebase/firestore. That's because the firebase core library does not include the firestore library.
import firebase from 'firebase/app';
import 'firebase/firestore';
If you are using the version the version 9 of firebase, then you need to use this instead:
// v9 compat packages are API compatible with v8 code
import firebase from 'firebase/compat/app';
import 'firebase/compat/firestore';
Here is the link for the upgrade from version 8 to version 9 https://firebase.google.com/docs/web/modular-upgrade.
Keep in mind: the compat libraries are a temporary solution that will be removed completely in a future major SDK version (such as version 10 or version 11). Your ultimate goal is to remove compat code and keep only version 9 modular-style code in your app.
For the time being, you can utilize compat libraries but you should try to switch from compat to modular in the future.
First, make sure you have latest version of firebase:
npm install firebase#4.12.0 --save
Next, add both firebase and firestore:
const firebase = require("firebase");
// Required for side-effects
require("firebase/firestore");
Initialize the firebase app:
firebase.initializeApp({
apiKey: '### FIREBASE API KEY ###',
authDomain: '### FIREBASE AUTH DOMAIN ###',
projectId: '### CLOUD FIRESTORE PROJECT ID ###'
});
// Initialize Cloud Firestore through Firebase
var db = firebase.firestore();
source: https://firebase.google.com/docs/firestore/quickstart?authuser=0
import { firebase } from '#firebase/app';
import '#firebase/firestore'
If you're using authentication as well
import '#firebase/auth';
I also struggled with this for a bit. what I did in the end was quite straightforward.
for versions 9 and higher, just do the following
import firebase from 'firebase/compat/app';
import 'firebase/compat/firestore';
import 'firebase/compat/auth';
// TODO: Add SDKs for Firebase products that you want to use
// https://firebase.google.com/docs/web/setup#available-libraries
// Your web app's Firebase configuration
const firebaseConfig = {
apiKey:
authDomain:
projectId:
storageBucket:
messagingSenderId:
appId:
};
// Initialize Firebase
const firebaseApp = firebase.initializeApp(firebaseConfig);
const db = firebaseApp.firestore;
const auth = firebaseApp.auth();
export { auth };
export default db;
//cheers
Hope this helps to someone who faces the same problem when deploying an Angular app to Firestore.
In Angular 8 project, I had the same error when deploying to Firestore.
I fixed it by adding another module AngularFirestoreModule.
App.module.ts is like this:
...
import { AngularFireModule } from '#angular/fire';
import { AngularFirestore, AngularFirestoreModule } from '#angular/fire/firestore'; // << Note AngularFirestoreModule !!!
import { AngularFireDatabaseModule } from '#angular/fire/database';
...
imports: [
BrowserModule,
FormsModule,
AngularFireModule.initializeApp(environment.firebaseConfig),
AngularFirestoreModule,
AngularFireDatabaseModule,
...
package.json:
...
"dependencies": {
"#angular/animations": "~8.2.2",
"#angular/common": "~8.2.2",
"#angular/compiler": "~8.2.2",
"#angular/core": "~8.2.2",
"#angular/fire": "^5.2.1",
"#angular/forms": "~8.2.2",
"#angular/platform-browser": "~8.2.2",
"#angular/platform-browser-dynamic": "~8.2.2",
"#angular/router": "~8.2.2",
"ajv": "^6.10.2",
"bootstrap-scss": "^4.3.1",
"core-js": "^2.5.4",
"firebase": "^6.4.0",
...
UPDATE:
When I deployed to some other hosting provider, this did not help. For this case, I added the original firebase library and it worked.
import { firestore } from 'firebase';
You can create a separate component for initialization of firebase on you application using credentials.
firebase-context.js
import * as firebase from 'firebase'
import 'firebase/firestore';
const firebaseConfig = {
apiKey: "XXXX",
authDomain: "XXXXX.firebaseapp.com",
databaseURL: "https://XXXX-app-web.firebaseio.com",
projectId: "XXXX",
storageBucket: "XXXX-app-web.appspot.com",
messagingSenderId: "XXXXXX",
appId: "1:XXX:web:XXXX",
measurementId: "G-XXXX"
};
export default !firebase.apps.length
? firebase.initializeApp(firebaseConfig).firestore()
: firebase.app().firestore();
In case, you need to deal with database operation you don't need to call the initialize method each time, you can use common component method which is earlier created.
import FirebaseContext from "./firebase-context";
export const getList = () => dispatch => {
FirebaseContext.collection("Account")
.get()
.then(querySnapshot => {
// success code
}).catch(err => {
// error code
});
}
If by any chance, your code is under witchcraft, and import firebase/firestore won't work, then include it directly:
import '#firebase/firestore/dist/esm/index';
If it's not there, then:
npm install #firebase/firestore
The problem is not import the firestore
firebase has many features.
You need to import or import from the CDN what you want to implement from the list below.
The official reference says to load firebase-firestore.js.
<script src="https://www.gstatic.com/firebasejs/7.19.0/firebase-app.js"></script>
<script src="https://www.gstatic.com/firebasejs/7.19.0/firebase-firestore.js"></script>
if you want to use npm, here
npm install firebase#7.19.0 --save
url is here
https://firebase.google.com/docs/firestore/quickstart?authuser=0#set_up_your_development_environment
I had same Error and tried to follow the official website but did not work.
Then I googled error and landed in this post.
I tried:
import * as firebase from 'firebase';
import 'firebase/firestore';
However, it did not work for me but I added /firebase to the first line import * as firebase from 'firebase/firebase'; and everything is working perfectly.
It also works with require:
const firebase = require("firebase/firebase");
// Required for side-effects
require("firebase/firestore");
If you are updating from an earlier version of firebase and you are pulling your hair out about this issue, try
const Firebase = require('firebase/firebase') instead of require('firebase/app')
In my case the problem was that I've accidentally added firebase-admin alongside with the firebase package in my package.json. And firebase-admin took precedence so even after adding the imports as per the accepted answer I was still getting the same error.
Removing the redundant firebase-admin from the client app fixed the problem.
As a note, firebase-admin is intended for server side to operate in admin mode, while the firebase package is a client side library.
import { getFirestore } from "firebase/firestore";
Just try this and see how it goes
To use firestore you need to add this link at the top of your html page.
//After initializing firebase, in your main javascript page call...
var data = firebase.firestore();
<script src="https://www.gstatic.com/firebasejs/7.1.0/firebase-firestore.js"></script>
<script src="https://www.gstatic.com/firebasejs/6.2.3/firebase-storage.js"></script>
Solution for Angular 8 (as of 4th January 2020):
Delete package-lock.json file
Run npm install
import AngularFirestoreModule from #angular/fire/firestore
Just need to import AngularFirestoreModule.
// App.module.ts
import { AngularFireModule } from '#angular/fire';
import { AngularFirestore, AngularFirestoreModule } from '#angular/fire/firestore';
import { AngularFireDatabaseModule } from '#angular/fire/database';
imports: [
AngularFireModule.initializeApp(environment.firebaseConfig),
AngularFirestoreModule,
AngularFireDatabaseModule
]
If you're like me and like everything typed on typescript (it's the purpose, by the way), you can try:
import * as firebase from "nativescript-plugin-firebase";
import { User, firestore } from "nativescript-plugin-firebase";
import * as firebaseapp from "nativescript-plugin-firebase/app";
So you can do stuff like that:
firebase.getCurrentUser().then((user: User) => { /* something */ });
const mycollection : firestore.CollectionReference = firebaseapp.firestore().collection("mycollection");
Removing node_modules directory together with package-lock.json and then running npm install fixed it for me.
https://github.com/angular/angularfire2/issues/1880
I used to have the same problem, it was a bug. I was importing firestore from firebase (it was done automatically by the IDE...) when i should imported it from the .js file where i initialized firebase app.
I am using the latest version of Angular 8.2.14, when I deployed to production, it cause this problem, so I add the following to app.module.ts
imports: [
...,
AngularFireModule.initializeApp(environment.firebaseConfig),
AngularFirestoreModule,
AngularFireDatabaseModule,
...
],
providers: [AngularFirestore, AngularFirestoreModule],
I found a useful comment in Github by alclimb
he mentioned about firebase analytics won't work in Node.js, because it meant to be used with a browser (this is mention in the official documentation)
Enabling Firestore for Nativescript
During plugin installation you'll be asked whether or not you use Firestore.
In case you're upgrading and you have the firebase.nativescript.json file in your project root, edit it and add: "firestore": true. Then run rm -rf platforms && rm -rf node_modules && npm i.
init / initializeApp
By default Firestore on iOS and Android persists data locally for offline usage (web doesn't by default, and the regular Firebase DB doesn't either on any platform). If you don't like that awesome feature, you can pass persist: false to the init function.
Note that initializeApp is simply an alias for init to make the plugin compatible with the web API.
const firebase = require("nativescript-plugin-firebase/app");
firebase.initializeApp({
persist: false
});
collection
A 'collection' is at the root of any Firestore interaction. Data is stored as a 'document' inside a collection.
const citiesCollection = firebase.firestore().collection("cities");
Source: nativescript-plugin-firebase
In vanilla javascript on the client you need to include this script to make it work:
<script src="https://www.gstatic.com/firebasejs/8.6.1/firebase-firestore.js"></script>
as it's not included in the default snippet Google asks you to copy paste in your website.
Source: https://firebase.google.com/docs/firestore/quickstart?authuser=0
For 2022 readers, please check your firebase version.
The latest version now is 9.x. It is little different from mostly YouTube guides.
You need firebase#8.x to follow YouTube guides.
npm uninstall firebase
npm install firebase#8.x
Docs: https://firebase.google.com/docs/firestore/quickstart?authuser=0#web-version-9_1
For version 9 of firebase you can use
import firebase from 'firebase/compat/app';
import "firebase/compat/firestore";
For me, the issue came from using the wrong import. I create the firebase app elsewhere in my code with initializeApp. This is a server side node.js app. Firebase Admin cannot be used in the client anyway.
Incorrect
import admin from 'firebase-admin';
this.stripeAccountColl = admin.firestore(this.firebaseApp).collection("StripeAccount");
Correct
import { getFirestore } from 'firebase-admin/firestore';
this.stripeAccountColl = getFirestore(this.firebaseApp).collection("StripeAccount");
In my case, the error was because I tried to import a file that used firebase.firestore() before I actually imported "firebase/firestore"
To use Firestore cloud functions on Node.js you should use admin.firestore() instead of admin.database(). Also you should be sure that your module firebase-admin on package.json is up to 5.4.1 or above. Looking like something like:
{
"name": "functions",
"description": "Cloud Functions for Firebase",
"dependencies": {
"firebase-admin": "^5.4.1",
"firebase-functions": "^0.7.0"
}
}
I think I've got it for folks using electron-webpack. Solution was from a post related to importing codemirror. https://github.com/electron-userland/electron-webpack/issues/81
This worked for me.
// package.json
{
//...
"electronWebpack": {
"whiteListedModules": [
"firebase"
]
},
//...
}
simply the answer is just to link these script in your html file and check that the issue is resolved
script src="https://www.gstatic.com/firebasejs/8.6.1/firebase-auth.js"
script src="https://www.gstatic.com/firebasejs/8.6.1/firebase-firestore.js
gives upvote if it is helpful for fixing your problem

Is it safe to use exported Firebase as global object

I had a discussion with my team. We were talking about should we export firebase object to use everywhere in our ReactJS project or do we have to use Redux to store the firebase object.
I've tried using export statement and it's working just fine.
import * as firebase from "firebase";
firebase.initializeApp({
apiKey: "xxxx",
authDomain: "xxxxx",
projectId: "xxx"
});
const firestore = firebase.firestore();
export { firebase, firestore };
Would it be better if I store firebase in state management or this approach is good enough.
I'm not React developer, but I used Firebase with Vue. I know these two are completely different frameworks, but maybe this case will help you.
I installed Firebase plugin in Vue (globally). Then I used state management to store for example login state.
After installation (below):
import VueFire from 'vuefire'
Vue.use(VueFire)
new Vue({
store,
render: h => h(App)
}).$mount('#app')
I used Firebase reference to access it, for example:
methods: {
addToDb: function () {
this.$firebaseRefs.data.child('count').set(1);
}
}
So in your case exporting will do, I guess.

Categories

Resources