FirebaseError: Firebase: No Firebase App '[DEFAULT]' has been created (on NextJS) - firebase

While trying to integrate Firebase auth with my project, I encountered this error:
FirebaseError: Firebase: No Firebase App '[DEFAULT]' has been created - call Firebase App.initializeApp() (app/no-app).
at app (/Volumes/MacOS/Projects/Projects/3. PriceTag/pricetag/node_modules/#firebase/app/dist/index.node.cjs.js:356:33)
at Object.serviceNamespace [as auth] (/Volumes/MacOS/Projects/Projects/3. PriceTag/pricetag/node_modules/#firebase/app/dist/index.node.cjs.js:406:51)
at eval (webpack-internal:///./lib/firebase.js:28:66)
at Object../lib/firebase.js (/Volumes/MacOS/Projects/Projects/3. PriceTag/pricetag/.next/server/pages/enter.js:22:1)
at __webpack_require__ (/Volumes/MacOS/Projects/Projects/3. PriceTag/pricetag/.next/server/webpack-runtime.js:33:42)
at eval (webpack-internal:///./pages/enter.js:7:71)
at Object../pages/enter.js (/Volumes/MacOS/Projects/Projects/3. PriceTag/pricetag/.next/server/pages/enter.js:33:1)
at __webpack_require__ (/Volumes/MacOS/Projects/Projects/3. PriceTag/pricetag/.next/server/webpack-runtime.js:33:42)
at __webpack_exec__ (/Volumes/MacOS/Projects/Projects/3. PriceTag/pricetag/.next/server/pages/enter.js:87:52)
at /Volumes/MacOS/Projects/Projects/3. PriceTag/pricetag/.next/server/pages/enter.js:88:28
at Object.<anonymous> (/Volumes/MacOS/Projects/Projects/3. PriceTag/pricetag/.next/server/pages/enter.js:91:3)
at Module._compile (internal/modules/cjs/loader.js:1133:30)
at Object.Module._extensions..js (internal/modules/cjs/loader.js:1153:10)
at Module.load (internal/modules/cjs/loader.js:977:32)
at Function.Module._load (internal/modules/cjs/loader.js:877:14)
at Module.require (internal/modules/cjs/loader.js:1019:19) {
code: 'app/no-app',
customData: { appName: '[DEFAULT]' }
I get this error whenever I request localhost:3000/enter
Here's the Javascript code:
firebase.js
import firebase from 'firebase/app'
import 'firebase/auth'
import 'firebase/firestore'
var firebaseConfig = {
apiKey: process.env.FIREBASE_API_KEY,
authDomain: process.env.FIREBASE_AUTH_DOMAIN,
projectId: process.env.FIREBASE_PROJECT_ID,
storageBucket: process.env.FIREBASE_STORAGE_BUCKET,
messagingSenderId: process.env.FIREBASE_MESSAGING_SENDER_ID,
appId: process.env.FIREBASE_APP_ID
};
if (!firebase.app.length) {
firebase.initializeApp(firebaseConfig)
}
export const auth = firebase.auth()
export const googleAuthProvider = new firebase.auth.GoogleAuthProvider()
enter.js
import { auth, googleAuthProvider } from '../lib/firebase'
export default function SignInPage() {
return (
<>
<SignInButton />
</>
)
}
// Google Sign In Component
const SignInButton = () => {
const signInWithGoogle = async () => {
await auth.signInWithPopup(googleAuthProvider)
}
return (
<button onClick={signInWithGoogle}>Sign in with Google</button>
)
}
// Sign Out Button component
export const SignOutButton = () => {
return (
<button onClick={() => auth.signOut}>Sign in with Google</button>
)
}
I can't seem to figure out what's causing the error. I did initialise a firebase app, so I'm not sure what's happening here.

With NextJs automatic code splitting, you never know what it is cutting out. I think NextJs is looking at your firebase.js and just including what you used:
import firebase from 'firebase/app'
export const auth = firebase.auth()
export const googleAuthProvider = new firebase.auth.GoogleAuthProvider()
I would just check if firebase is setup every time you use it.
Firebase Web V9
import { getApp as _getApp, getApps, initializeApp } from "firebase/app";
import { getAuth as _getAuth } from "firebase/auth";
import { enableIndexedDbPersistence, getFirestore as _getFirestore } from "firebase/firestore";
const config = {
apiKey: process.env.FIREBASE_API_KEY,
authDomain: process.env.FIREBASE_AUTH_DOMAIN,
databaseURL: process.env.FIREBASE_DATABASE_URL,
projectId: process.env.FIREBASE_PROJECT_ID,
storageBucket: process.env.FIREBASE_STORAGE_BUCKET,
messagingSenderId: process.env.FIREBASE_MESSAGING_SENDER_ID,
appId: process.env.FIREBASE_APP_ID,
};
const firebaseIsRunning = () => !!(getApps().length);
export function getApp() {
if (!firebaseIsRunning()) initializeApp(config);
return _getApp();
}
export function getFirestore() {
const isRunning = firebaseIsRunning();
if (!isRunning) getApp();
const db = _getFirestore();
if (!isRunning)
if (typeof window !== undefined) enableIndexedDbPersistence(db)
return db;
}
export function getAuth() {
if (!firebaseIsRunning()) getApp();
return _getAuth();
}

for anybody that is using firebase V9. This is what you need to do.
import { initializeApp } from 'firebase/app';
import { getFirestore } from "firebase/firestore";
const clientCredentials = {
apiKey: process.env.NEXT_PUBLIC_FIREBASE_API_KEY,
authDomain: process.env.NEXT_PUBLIC_FIREBASE_AUTH_DOMAIN,
projectId: process.env.NEXT_PUBLIC_FIREBASE_PROJECT_ID,
storageBucket: process.env.NEXT_PUBLIC_FIREBASE_STORAGE_BUCKET,
messagingSenderId: process.env.NEXT_PUBLIC_FIREBASE_MESSAGING_SENDER_ID,
appId: process.env.NEXT_PUBLIC_FIREBASE_APP_ID,
measurementId: process.env.NEXT_PUBLIC_FIREBASE_MEASUREMENT_ID,
};
const app = initializeApp(firebaseConfig);
const firestore = getFirestore();
export { firestore }
and you should be fine

Related

FirebaseError: "projectId" not provided in firebase.initializeApp (NextJS)

I'm building a web app with NextJS, NextAuth and Firebase/Firestore, and I'm getting an error:
error - [FirebaseError: "projectId" not provided in firebase.initializeApp.] {
code: 'invalid-argument',
customData: undefined,
toString: [Function (anonymous)]
This is my JS file:
import NextAuth from "next-auth/next";
import TwitterProvider from "next-auth/providers/twitter";
import { FirestoreAdapter } from "#next-auth/firebase-adapter";
import { initializeApp, getApp, getApps } from "firebase/app";
import "firebase/auth";
import { getFirestore, collection, addDoc, getDocs } from "firebase/firestore";
// import { getAnalytics } from "firebase/analytics";
// import { getStorage } from "firebase/storage";
import nextConfig from "next.config";
const firebaseConfig = {
apiKey: nextConfig.env.FIREBASE_API_KEY,
authDomain: nextConfig.env.FIREBASE_AUTH_DOMAIN,
projectId: nextConfig.env.FIREBASE_PROJECT_ID,
storageBucket: nextConfig.env.FIREBASE_STORAGE_BUCKET,
messagingSenderId: nextConfig.env.FIREBASE_MESSAGING_SENDER_ID,
appId: nextConfig.env.FIREBASE_APP_ID,
measurementId: nextConfig.env.FIREBASE_MEASUREMENT_ID,
};
const app = !getApps().length ? initializeApp(firebaseConfig) : getApp();
//const analytics = getAnalytics(app);
const db = getFirestore(app);
//const storage = getStorage(app);
const dbInstance = collection(db, "bugs");
const getBugs = () => {
getDocs(dbInstance).then((data) => {
console.log(data);
});
};
export default NextAuth({
providers: [
TwitterProvider({
clientId: nextConfig.env.TWITTER_CLIENT_ID,
clientSecret: nextConfig.env.TWITTER_CLIENT_SECRET,
version: "2.0", // opt-in to Twitter OAuth 2.0
}),
],
adapter: FirestoreAdapter(db),
});
I can't find any solution on the internet.
Any idea?
In Nextjs, environment variables are only available in the Node.js environment by default, meaning they won't be exposed to the browser.
In order to expose a variable to the browser you have to prefix the variable with NEXT_PUBLIC_
Change your firebase config as shown below and also change the firebase env variables in the .env file to use NEXT_PUBLIC_ prefix.
const firebaseConfig = {
apiKey: process.env.NEXT_PUBLIC_FIREBASE_API_KEY,
authDomain: process.env.NEXT_PUBLIC_FIREBASE_AUTH_DOMAIN,
projectId: process.env.NEXT_PUBLIC_FIREBASE_PROJECT_ID,
storageBucket: process.env.NEXT_PUBLIC_FIREBASE_STORAGE_BUCKET,
messagingSenderId: process.env.NEXT_PUBLIC_FIREBASE_MESSAGING_SENDER_ID,
appId:process.env.NEXT_PUBLIC_FIREBASE_APP_ID,
measurementId: process.env.NEXT_PUBLIC_FIREBASE_MEASUREMENT_ID,
};

Firebase Cloud messaging (Notification)

I'm new here. Been having issues with working with the firebase cloud messaging. Tried sending notification throught the the notification composer but it not promting any notification at my side. N:B I have no knowledge of backend technologies, so only implemented it in the front-end.
This is my code
// For the App.js folder
import { initializeApp } from "firebase/app";
import { getToken, getMessaging, onMessage } from "firebase/messaging";
const firebaseConfig = {
apiKey: "AIzaSyCy1TQbCwalPdU3sBf2sDKraxHpplamGQ8",
authDomain: "fir-project-test-44a6b.firebaseapp.com",
projectId: "fir-project-test-44a6b",
storageBucket: "fir-project-test-44a6b.appspot.com",
messagingSenderId: "648408030635",
appId: "1:648408030635:web:2a94b932f10e11abb6c6ee",
measurementId: "G-2YHQFP9KWX"
};
// Initialize Firebase
const firebaseApp = initializeApp(firebaseConfig);
const messaging = getMessaging(firebaseApp);
Notification.requestPermission().then((permission) => {
if(permission === 'granted'){
console.log('permission granted')
}
})
.catch((err) => {
console.log('permission denied:', err)
})
getToken(messaging, {vapidKey: 'BMRthb-93vz-iQl0XQA8AsKbzMyLq-f2JCB00B2rMb35Z_1iVdWX8CquQ820-z6vyMmdDB0W46FIIS3R5IhTbXY'}).then((token) => {
console.log('my token is', token);
});
onMessage(messaging, (payload) => {
console.log(payload.notification);
new Notification(payload.notification.title, {
body:payload.notification.body
})
})
For the Service worker folder
import { getMessaging, onBackgroundMessage } from "firebase/messaging";
import { initializeApp } from "firebase/app";
importScripts("https://www.gstatic.com/firebasejs/9.16.0/firebase-app.js");
importScripts("https://www.gstatic.com/firebasejs/9.16.0/firebase-messaging.js");
const firebaseConfig = {
apiKey: "AIzaSyCy1TQbCwalPdU3sBf2sDKraxHpplamGQ8",
authDomain: "fir-project-test-44a6b.firebaseapp.com",
projectId: "fir-project-test-44a6b",
storageBucket: "fir-project-test-44a6b.appspot.com",
messagingSenderId: "648408030635",
appId: "1:648408030635:web:2a94b932f10e11abb6c6ee",
measurementId: "G-2YHQFP9KWX"
};
// Initialize Firebase
const firebaseApp = initializeApp(firebaseConfig);
const messaging = getMessaging(firebaseApp);
onBackgroundMessage(messaging, (payload) => {
console.log('received background messages:', payload)
const notificationTitle= payload.notification.notificationTitle
const notificationBody = {
body: payload.notification.body,
}
self.registration.showNotification(notificationTitle, notificationBody);
})
i would apprecitate if someone can come through for me. thanks[image 1(app.jsimage2 (app.js)](https://i.stack.imgur.com/tMoq2.png)
Tried evrything, but to no avail. I want to be able to send notifications to user via the notificTION COMPOSER

Why is Firebase Cloud Messaging not showing on foreground in my vue app?

package.json
"firebase": "^9.14.0",
public/firebase-messaging-sw.js
`
importScripts('https://www.gstatic.com/firebasejs/8.2.7/firebase-app.js')
importScripts('https://www.gstatic.com/firebasejs/8.2.7/firebase-messaging.js')
try {
const config = {
apiKey: "AIzaSyBzFxb1h0INNwZ2dKMF83PfoMXa2aCdXqM",
authDomain: "jobdoh-dc1db.firebaseapp.com",
projectId: "jobdoh-dc1db",
storageBucket: "jobdoh-dc1db.appspot.com",
messagingSenderId: "922163524694",
appId: "1:922163524694:web:a50be771626fa1356077f7",
};
firebase.initializeApp(config);
const messaging = firebase.messaging();
messaging.setBackgroundMessageHandler(payload => {
console.log("Payload :> ", payload)
return self.registration.showNotification("hello", { body: "aaa" })
})
} catch (err) {
console.log("err in sw :> ", err)
}
All console.log that in the firebase-messaging-sw.js are not working.
src/plugins/firebase.js
import { initializeApp, getApps } from 'firebase/app';
import { getMessaging } from 'firebase/messaging'
import '#firebase/app';
const config = {
apiKey: "AIzaSyBzFxb1h0INNwZ2dKMF83PfoMXa2aCdXqM",
authDomain: "jobdoh-dc1db.firebaseapp.com",
databaseURL: "https://jobdoh-dc1db-default-rtdb.asia-southeast1.firebasedatabase.app",
projectId: "jobdoh-dc1db",
storageBucket: "jobdoh-dc1db.appspot.com",
messagingSenderId: "922163524694",
appId: "1:922163524694:web:a50be771626fa1356077f7",
measurementId: "G-VJ4952421E"
};
const apps = getApps();
const app = !apps.length ? initializeApp(config) : apps[0];
const messaging = getMessaging(app)
export default messaging;
src/index.js
import {createApp} from "vue";
import firebaseMessaging from './plugins/firebase';
const app = createApp();
app.config.globalProperties.$messaging = firebaseMessaging;
app.mount("#app");
I declare the messaging service as a global properties.
And use it in the customPage(eg. NotiPage.vue)
src/pages/NotiPage.vue
<template>
<v-btn #click="getToken">Get Token</v-btn>
</template>
<script>
import { getMessaging, onMessage, getToken } from "firebase/messaging";
export default {
methods: {
async getToken() {
const token = await getToken(this.$messaging, {
ServiceWorkerRegistration: "/public/firebase-messaging-sw.js",
vapidKey:
"BKOVTA3E_8xNS8MqBNVWxv8bxlaOman4gaY5jXpMG-wpev19uWFANeyKy6rRDxfx8QEarlUSqwJ7UNiuripRA4c",
});
if (token) {
console.log(token); // I got the token
} else {
// Request permission
}
},
},
mounted(){
const message = getMessaging();
onMessage(message, (payload) => console.log("Messages :> "), payload)
}
}
</script>
I got the token and message on the console. But not show the noti popup in my chrome. I turn on my notification permission on my computer setting and allow the notification on my chrome.
This is console.log image.
Pls advice me. Where did I wrong?
I want to appear notification popup on my browser and running the process in background.

Using Firsebase + Firestore with Deno

I'm trying to use firebase, specifically firestore, wtih Deno, but am running into issues with both v8 and v9 of the APIs.
For v8 I follow this tutorial from Deno, but receive the error Property firestore does not exist on firebase.
import "https://deno.land/x/xhr#0.1.2/mod.ts";
import firebase from "https://cdn.skypack.dev/firebase#8.10.0/app";
import "https://cdn.skypack.dev/firebase#8.10.0/firestore";
const firebaseConfig = { ... };
firebase.initializeApp( firebaseConfig, 'app' );
const firebaseApp = firebase.app( 'app' );
const db = firebase.firestore( firebaseApp );
The same error occurs for firebase version 8.7.0.
For v9 I get the error Service firestore is not available
import "https://deno.land/x/xhr#0.1.2/mod.ts";
import { initializeApp } from "https://cdn.skypack.dev/firebase#9.4.1/app";
import { getFirestore } from "https://cdn.skypack.dev/firebase#9.4.1/firestore";
const firebaseConfig = { ... };
const firebaseApp = initializeApp( firebaseConfig );
const db = getFirestore( firebaseApp );
And if I don't pass firebaseApp to the getFirestore call I get the error No Firebase App '[DEFAULT]' has been created.
...
const db = getFirestore();
MRE
v8.js
import "https://deno.land/x/xhr#0.1.2/mod.ts";
import firebase from "https://cdn.skypack.dev/firebase#8.10.0/app";
import "https://cdn.skypack.dev/firebase#8.10.0/firestore";
const firebaseConfig = {
apiKey: "apikey",
authDomain: "pid.firebaseapp.com",
projectId: "pid",
storageBucket: "pid.appspot.com",
messagingSenderId: "msid",
appId: "aid",
measurementId: "mid"
};
firebase.initializeApp( firebaseConfig, 'app' );
const firebaseApp = firebase.app( 'app' );
const db = firebase.firestore( firebaseApp );
Run with deno run v8.js.
output
> deno run v8.js
Property 'firestore' does not exist on type '{ __esModule: boolean; initializeApp: (options: any, rawConfig: any) => any; app: { (name2: any): any; App: any; }; registerVersion: (libraryKeyOrName: any, version2: any, variant: any) => void; ... 4 more ...; INTERNAL: { ...; }; }'.
const db = firebase.firestore( firebaseApp );
> deno run --no-check v8.js
Uncaught TypeError: Cannot read properties of null (reading 'INTERNAL')
e3.INTERNAL.registerComponent(new Component("firestore", function(e4) {
^
at https://cdn.skypack.dev/-/#firebase/firestore#v2.4.0-WKZzTerrZCqDrKBg0YNc/dist=es2019,mode=imports/optimized/#firebase/firestore.js:11912:8
at I (https://cdn.skypack.dev/-/#firebase/firestore#v2.4.0-WKZzTerrZCqDrKBg0YNc/dist=es2019,mode=imports/optimized/#firebase/firestore.js:11916:4)
at https://cdn.skypack.dev/-/#firebase/firestore#v2.4.0-WKZzTerrZCqDrKBg0YNc/dist=es2019,mode=imports/optimized/#firebase/firestore.js:11920:1
v9.js
import "https://deno.land/x/xhr#0.1.2/mod.ts";
import { initializeApp } from "https://cdn.skypack.dev/firebase#9.4.1/app";
import { getFirestore } from "https://cdn.skypack.dev/firebase#9.4.1/firestore";
const firebaseConfig = {
apiKey: "apikey",
authDomain: "pid.firebaseapp.com",
projectId: "pid",
storageBucket: "pid.appspot.com",
messagingSenderId: "msid",
appId: "aid",
measurementId: "mid"
};
const firebaseApp = initializeApp( firebaseConfig );
const db = getFirestore( firebaseApp );
Run with deno run v8.js
output
> deno run v9.js
Uncaught Error: Service firestore is not available
throw Error(`Service ${this.name} is not available`);
^
at Provider.getImmediate (https://cdn.skypack.dev/-/#firebase/component#v0.5.9-NRovvSCAF0YOkKLBn5pi/dist=es2019,mode=imports/optimized/#firebase/component.js:111:15)
at Oa (https://cdn.skypack.dev/-/#firebase/firestore#v3.3.0-7hhS3yMUs2qdY64sdriE/dist=es2019,mode=imports/optimized/#firebase/firestore.js:9969:39)
at file:///home/brian/Downloads/firebase-test/mrc-v9.ts:17:12
> deno run --no-check v9.js
Uncaught Error: Service firestore is not available
throw Error(`Service ${this.name} is not available`);
^
at Provider.getImmediate (https://cdn.skypack.dev/-/#firebase/component#v0.5.9-NRovvSCAF0YOkKLBn5pi/dist=es2019,mode=imports/optimized/#firebase/component.js:111:15)
at Oa (https://cdn.skypack.dev/-/#firebase/firestore#v3.3.0-7hhS3yMUs2qdY64sdriE/dist=es2019,mode=imports/optimized/#firebase/firestore.js:9969:39)
at file:///home/brian/Downloads/firebase-test/mrc-v9.ts:17:12
As mentioned by #bicarlsen, the issue is related to compatibility between the firebase module. And for that he has raised an issue on Github.
A workaround has been posted in the GitHub thread related to this issue. Instead of import from https://cdn.skypack.dev/firebase#9.4.1/app, you can import from https://www.gstatic.com/firebasejs/9.6.0/firebase-app.js, and similarly by replacing app in the URL for the other modules.

How to fix "Cannot read property 'firestore' of null" in Firestore

I will try to change the setting in the function of firestore() but doesn't work.
I read the document and they said that this future will be removed in a future release but I don't seen the solve. So I hope anyone can help me settle this problem
Operating System version: Majove 10.14.2
Library version: ^6.1.0
Firebase Product: firestore
import * as firebase from 'firebase/app'
import 'firebase/firestore'
require('dotenv').config({ encoding: 'utf8' })
const firebaseConfig = {
apiKey: process.env.API_KEY,
authDomain: process.env.AUTH_DOMAIN,
databaseURL: process.env.DATABASE_URL,
projectId: process.env.PROJECT_ID,
storageBucket: process.env.STORAGE_BUCKET,
messagingSenderId: process.env.MESSAGING_SENDER_ID,
appId: process.env.APP_ID
}
// Initialize Firebase
let firebaseApp = null
if (!firebase.app.length) {
firebaseApp = firebase.initializeApp(firebaseConfig)
}
firebaseApp.firestore().settings({
ssl: false,
timestampsInSnapshots: true
})
export default firebaseApp.firestore()
See https://firebase.google.com/docs/web/setup .
Basic way to initialize firebase is this.
import firebase from "firebase/app";
import "firebase/auth";
import "firebase/firestore";
import "firebase/functions";
import "firebase/storage";
import "firebase/messaging";
import "firebase/performance";
const config = {
// set your config here
};
if (!firebase.apps.length) {
firebase.initializeApp(config);
}
const auth = firebase.auth();
const storage = firebase.storage();
const functions = firebase.functions();
const firestore = firebase.firestore();
let messaging = null;
try {
if (firebase.messaging.isSupported()) {
messaging = firebase.messaging();
messaging.usePublicVapidKey("your publicVapidKey here");
}
} catch (e) {}
const perf = firebase.performance();
export { firebase, auth, storage, functions, firestore, messaging };
I edited your code.
import firebase from 'firebase/app'
import 'firebase/firestore'
require('dotenv').config({ encoding: 'utf8' })
const firebaseConfig = {
apiKey: process.env.API_KEY,
authDomain: process.env.AUTH_DOMAIN,
databaseURL: process.env.DATABASE_URL,
projectId: process.env.PROJECT_ID,
storageBucket: process.env.STORAGE_BUCKET,
messagingSenderId: process.env.MESSAGING_SENDER_ID,
appId: process.env.APP_ID
}
if (!firebase.apps.length) {
firebase.initializeApp(firebaseConfig)
}
const firestore = firebase.firestore();
firestore.settings({
ssl: false,
timestampsInSnapshots: true
})
export default firestore;

Resources