I know there is a NextJS Auth ways to do it but its not comfortable to me and I'm used to do it in firebase, but I don't understand why it is receiving an error in authentication?
Basically I have this bunch of codes.
And the getAuth() is giving me an error..
// Import the functions you need from the SDKs you need
import { initializeApp } from "firebase/app";
import { getFirestore } from "firebase/firestore";
import { getStorage } from "firebase/storage";
import { getAuth ,GoogleAuthProvider, FacebookAuthProvider, TwitterAuthProvider,GithubAuthProvider } from "firebase/auth";
// TODO: Add SDKs for Firebase products that you want to use
// https://firebase.google.com/docs/web/setup#available-libraries
console.log(process.env.API_KEY);
console.log(process.env.AUTH_DOMAIN);
console.log(process.env.PROJECT_ID);
console.log(process.env.STORAGE_BUCKET);
console.log(process.env.MESSAGING_SENDER_ID);
console.log(process.env.APP_ID);
// Your web app's Firebase configuration
const firebaseConfig = {
apiKey: process.env.API_KEY,
authDomain: process.env.AUTH_DOMAIN,
projectId: process.env.PROJECT_ID,
storageBucket: process.env.STORAGE_BUCKET,
messagingSenderId: process.env.MESSAGING_SENDER_ID,
appId: process.env.APP_ID,
};
// Initialize Firebase
const app = initializeApp(firebaseConfig);
export const db = getFirestore(app);
export const storage = getStorage(app);
export const authentication = getAuth();
export const google = new GoogleAuthProvider();
export const facebook = new FacebookAuthProvider();
export const twitter = new TwitterAuthProvider();
export const github = new GithubAuthProvider();
This is the error I received in nextjs.
But all my firebase config in .env file is right and its working in console.log() can anyone tell me why it is not working? I've been annoyed lately at any bugs I receive in NextJS that I don't understand where it come from.
According to Exposing Environment Variables to the Browser, all of your process.env variables should be prefixed with NEXT_PUBLIC_.
Also as a local test, you can copy the project config directly from your project settings in the Firebase cloud UI and replace your config that's dependent on env variables. Use that to verify you're able to connect - then go back to your environment variables.
Related
I'm practicing making some projects which are using ReactJS, but when I saved the config file as below, It showed the error as the title. Has anyone ever been trouble with this? Please help me!
Thanks!
import { initializeApp } from "firebase/app";
import { getAnalytics } from "firebase/analytics";
import firebase from 'firebase/compat/app';
import 'firebase/analytics';
import 'firebase/compat/auth';
import 'firebase/compat/firestore';
// 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: "AIzaSyD0rxJTIV4RIKfdFJB6G--9md2-SAEDwjs",
authDomain: "chat-app-d3f09.firebaseapp.com",
projectId: "chat-app-d3f09",
storageBucket: "chat-app-d3f09.appspot.com",
messagingSenderId: "361125159681",
appId: "1:361125159681:web:9557ff40c4e38e30ba3100",
measurementId: "G-X1Q63CL2N2"
};
// Initialize Firebase
const app = initializeApp(firebaseConfig);
const analytics = getAnalytics(app);
const auth = firebase.auth();
const db = firebase.firestore();
export { db, auth }
export default firebase
You are using firebase version 9 with 8 & >.
Try:
const app = initializeApp(firebaseConfig);
const analytics = getAnalytics(app);
//const auth = firebase.auth();
const auth = getAuth(app)
//const db = firebase.firestore();
const db = getFirestore(app)
Or if you want to use version 8 & > then:
const app = firebase.initializeApp(firebaseConfig);
//const analytics = getAnalytics(app);
const auth = firebase.auth();
const db = firebase.firestore();
Note that firebase version 9+ is written in functional way.
I am working on a react project that I am I want to use both Auth and real-time database from firebase. I have managed to set auth but database import is giving me a hard time. I want to use the (database().child().push() ) method to push data to the database but I can't call the database().ref() method in my firebase Config. Anyone?
import { initializeApp } from "firebase/app";
import { getAuth } from 'firebase/auth'
// Your web app's Firebase configuration
const firebaseConfig = {
apiKey: "AIzaSyD8aGnZYjhCTopgdNhuykWvmkJSHKj_h7E",
authDomain: "bonnie-d17be.firebaseapp.com",
databaseURL: "https://bonnie-d17be-default-rtdb.firebaseio.com",
projectId: "bonnie-d17be",
storageBucket: "bonnie-d17be.appspot.com",
messagingSenderId: "397471611615",
appId: "1:397471611615:web:3f6a743f4770ff8718c76a"
};
// Initialize Firebase
const app = initializeApp(firebaseConfig);
export const authentication = getAuth(app);
export default app;
Firebase's documentation has examples of both name-spaced (V8) and new functional (V9) syntax. To push a new node, try the following code:
// Initialize database similar to auth
import { getDatabase } from "firebase/database";
export const database = getDatabase();
import { push, child, ref } from "firebase/database";
const dbRef = ref(database)
push(child(dbRef, 'path/')).then(() => {
console.log("Data added")
})
Difficulty in setting up this app as firebase, exported from firebase/app doesn't seem to have the firestore() method on it (See attached image). This is my code. Someone please help me fix it.
// Import the functions you need from the SDKs you need
import firebase from 'firebase/app';
// 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 app = firebase.initializeApp(firebaseConfig)
export const firestore = firebase.firestore()
Maybe you're using Firestore v9. So you might be using the methods from the old API
You can check what version of firebase you've installed by looking at the major version of the npm package in your package.json
Here is a snippet from the Firestore docs on how to initialize firestore with with the web version v9 (https://firebase.google.com/docs/firestore/quickstart)
// Initialize Cloud Firestore through Firebase
import { initializeApp } from "firebase/app"
import { getFirestore } from "firebase/firestore"
const firebaseApp = initializeApp({
apiKey: '### FIREBASE API KEY ###',
authDomain: '### FIREBASE AUTH DOMAIN ###',
projectId: '### CLOUD FIRESTORE PROJECT ID ###'
});
const db = getFirestore();
I started a project and occurred an error when importing firebase in more than one component.
In this firebase start file:
import firebase from 'firebase'
const firebaseConfig = {
apiKey: "fdsfsdfdsf",
authDomain: "fdsfdsfsdfdsf",
databaseURL: "sdfdsfdsf",
projectId: "dsfdsfdsf",
storageBucket: "dsfdsfdsf",
messagingSenderId: "dsfdsfsdfdsf"
}
const FbApp = firebase.initializeApp(firebaseConfig)
export default FbApp.auth()
Then in the components:
import firebase from '../lib/firebaseClient'
With a single component works well, but if I add a new component with:
import firebase from '../lib/firebaseClient'
The application fail:
FirebaseError: Firebase: Firebase App named '[DEFAULT]' already exists (app/duplicate-app).
I had same issue, then I found out this:
if (!firebase.apps.length) {
firebase.initializeApp({});
}
https://github.com/zeit/next.js/issues/1999
The solution:
import firebase from 'firebase'
try {
firebase.initializeApp({
databaseURL: 'dfgdfg'
})
} catch (err) {
// we skip the "already exists" message which is
// not an actual error when we're hot-reloading
if (!/already exists/.test(err.message)) {
console.error('Firebase initialization error', err.stack)
}
}
const auth = firebase.auth()
export default auth
My understanding is that the error is due to calling initializeApp() more than once for your database. Scan through your code to make sure you only call initializeApp() once. For me, this included checking any js files that might be calling the method and checking for duplicate js files in your html file.
I recently solved this error in my own code. My issue was caused by accidentally linking my javascript file, which calls initializeApp(), in the head and in the body of my html file. My fix was to delete the duplicate javascript tag in the head of my html file so only one existed in the body.
On serverside something like this should work
const admin = require('firebase-admin');
const serviceAccount = require('./../../credentials/server');
// Check if firebase already been initialized
if (!admin.apps.length) {
// Initialize Firestore.
admin.initializeApp({
credential: admin.credential.cert(serviceAccount),
});
}
Summarizing all good answers.
A better fix would be to load environment variables from .env.local into process.env.
//.env.local
NEXT_PUBLIC_FIREBASE_API_KEY=
NEXT_PUBLIC_FIREBASE_AUTH_DOMAIN=
NEXT_PUBLIC_FIREBASE_PROJECT_ID=
NEXT_PUBLIC_FIREBASE_STORAGE_BUCKET=
NEXT_PUBLIC_FIREBASE_MESSAGING_SENDER_ID=
NEXT_PUBLIC_FIREBASE_APP_ID=
Next up, we can initialize the Firebase SDK on the client-side like this.
//shared/configs/firebase.js
import firebase from 'firebase/app';
import 'firebase/auth';
import '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,
};
if (!firebase.apps.length) {
firebase.initializeApp(clientCredentials);
}
export default firebase;
Finally, import the Firebase deps to other file.
//pages/index.js
import firebase from '../shared/configs/firebase';
So I ran into this issue because of some aspect of Next's hot reloading. I was using code like the following to ensure that I didn't call initializeApp more than once:
export let adminClient;
adminClient = adminClient || admin.initializeApp({...});
This didn't work because it seemed like the hot reloading was clearing adminClient, so I kept trying to call initializeApp, even though firebase still had the app recorded as being initialized.
To fix this, I used the following snippet:
const getAppInstance = () => {
if (admin.apps.length) {
return admin.apps[0];
} else {
return initApp();
}
}
export const adminClient = getAppInstance();
which works on a fresh server start, or when hot reloading due to code changes in development.
If you are using a new Modular SDK v9.0.1 then it might not support the "firebase" namespace.
The Implementation, I used
import { initializeApp, getApps } from "firebase/app"
import { getFirestore } from "firebase/firestore"
import { getAuth } from "firebase/auth"
//App configure
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_MESSAGGING_SENDER_ID,
appId: process.env.NEXT_PUBLIC_FIREBASE_APP_ID,
measurementId: process.env.NEXT_PUBLIC_MEASUREMENT_ID
};
if (!getApps().length) {
console.log(`...`)
}
const app = initializeApp(firebaseConfig)
const db = getFirestore(app)
const auth = getAuth(app)
export {db, auth}
export default app
Reference:
StackOverflow: Visit
Firebase Docs: Visit
Firebase Tutorial Setup: Visit
I started a project and occurred an error when importing firebase in more than one component.
In this firebase start file:
import firebase from 'firebase'
const firebaseConfig = {
apiKey: "fdsfsdfdsf",
authDomain: "fdsfdsfsdfdsf",
databaseURL: "sdfdsfdsf",
projectId: "dsfdsfdsf",
storageBucket: "dsfdsfdsf",
messagingSenderId: "dsfdsfsdfdsf"
}
const FbApp = firebase.initializeApp(firebaseConfig)
export default FbApp.auth()
Then in the components:
import firebase from '../lib/firebaseClient'
With a single component works well, but if I add a new component with:
import firebase from '../lib/firebaseClient'
The application fail:
FirebaseError: Firebase: Firebase App named '[DEFAULT]' already exists (app/duplicate-app).
I had same issue, then I found out this:
if (!firebase.apps.length) {
firebase.initializeApp({});
}
https://github.com/zeit/next.js/issues/1999
The solution:
import firebase from 'firebase'
try {
firebase.initializeApp({
databaseURL: 'dfgdfg'
})
} catch (err) {
// we skip the "already exists" message which is
// not an actual error when we're hot-reloading
if (!/already exists/.test(err.message)) {
console.error('Firebase initialization error', err.stack)
}
}
const auth = firebase.auth()
export default auth
My understanding is that the error is due to calling initializeApp() more than once for your database. Scan through your code to make sure you only call initializeApp() once. For me, this included checking any js files that might be calling the method and checking for duplicate js files in your html file.
I recently solved this error in my own code. My issue was caused by accidentally linking my javascript file, which calls initializeApp(), in the head and in the body of my html file. My fix was to delete the duplicate javascript tag in the head of my html file so only one existed in the body.
On serverside something like this should work
const admin = require('firebase-admin');
const serviceAccount = require('./../../credentials/server');
// Check if firebase already been initialized
if (!admin.apps.length) {
// Initialize Firestore.
admin.initializeApp({
credential: admin.credential.cert(serviceAccount),
});
}
Summarizing all good answers.
A better fix would be to load environment variables from .env.local into process.env.
//.env.local
NEXT_PUBLIC_FIREBASE_API_KEY=
NEXT_PUBLIC_FIREBASE_AUTH_DOMAIN=
NEXT_PUBLIC_FIREBASE_PROJECT_ID=
NEXT_PUBLIC_FIREBASE_STORAGE_BUCKET=
NEXT_PUBLIC_FIREBASE_MESSAGING_SENDER_ID=
NEXT_PUBLIC_FIREBASE_APP_ID=
Next up, we can initialize the Firebase SDK on the client-side like this.
//shared/configs/firebase.js
import firebase from 'firebase/app';
import 'firebase/auth';
import '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,
};
if (!firebase.apps.length) {
firebase.initializeApp(clientCredentials);
}
export default firebase;
Finally, import the Firebase deps to other file.
//pages/index.js
import firebase from '../shared/configs/firebase';
So I ran into this issue because of some aspect of Next's hot reloading. I was using code like the following to ensure that I didn't call initializeApp more than once:
export let adminClient;
adminClient = adminClient || admin.initializeApp({...});
This didn't work because it seemed like the hot reloading was clearing adminClient, so I kept trying to call initializeApp, even though firebase still had the app recorded as being initialized.
To fix this, I used the following snippet:
const getAppInstance = () => {
if (admin.apps.length) {
return admin.apps[0];
} else {
return initApp();
}
}
export const adminClient = getAppInstance();
which works on a fresh server start, or when hot reloading due to code changes in development.
If you are using a new Modular SDK v9.0.1 then it might not support the "firebase" namespace.
The Implementation, I used
import { initializeApp, getApps } from "firebase/app"
import { getFirestore } from "firebase/firestore"
import { getAuth } from "firebase/auth"
//App configure
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_MESSAGGING_SENDER_ID,
appId: process.env.NEXT_PUBLIC_FIREBASE_APP_ID,
measurementId: process.env.NEXT_PUBLIC_MEASUREMENT_ID
};
if (!getApps().length) {
console.log(`...`)
}
const app = initializeApp(firebaseConfig)
const db = getFirestore(app)
const auth = getAuth(app)
export {db, auth}
export default app
Reference:
StackOverflow: Visit
Firebase Docs: Visit
Firebase Tutorial Setup: Visit