Cannot access 'auth' before initialization in Firebase 9.x - firebase

I'm trying to set up Firebase authentication for a Next.js app. I'm using Firebase 9.6.4. I can't figure out the modular importing in v9, and I'm getting this error when accessing the route /api/login.
ReferenceError: Cannot access 'auth' before initialization
Here is the relevant code:
lib/firebase.js
import firebase from "firebase/app";
import { getAuth } from "firebase/auth";
const firebaseConfig = { ... };
const app = firebase.initializeApp(firebaseConfig, "App Name");
export const provider = new firebase.auth.GoogleAuthProvider();
export const auth = getAuth(app);
export default firebase;
pages/api/login.js
import firebase, { auth, provider } from "../../lib/firebase";
export default function signIn(req, res) {
auth
.signInWithPopup(provider)
.then(...)
.catch(...);
}
...

Related

How to retrieve auth cookie on serverInit in Pinia store?

I have recently started learning Nuxt 3 by trying to implement basic user auth logic with firebase and now I would need to retrieve the cookie from the req to initialise the user auth state inside Pinia store but it seems like nuxtServerInit is not supported by Pinia. After realising this I proceeded to a different solution where I'm using server middleware to pass the req object to an action called nuxtServerInit() but then I ran into another problem which is that I cannot call the auth().verifyIdToken(token) from there because the firebase is initialised inside a plugin which runs afterwards.
After this I also tried to initialise firebase inside server middleware and pass auth object to nuxtServerInit() action and set it to the state but then I could not call an action from there I guess because Pinia has not initialised yet?
How could I overcome the original problem? What could be a better approach?
Heres the firebase init plugin:
import { initializeApp } from 'firebase/app'
import { getAuth } from "firebase/auth"
import { getFirestore } from 'firebase/firestore'
import { useStore } from '~/store/index.js'
export default defineNuxtPlugin(nuxtApp => {
const firebaseConfig = {
apiKey: "API_KEY",
authDomain: "AUTH_DOMAIN",
projectId: "PROJECT_ID",
storageBucket: "STORAGE_BUCKET",
messagingSenderId: "MESSAGING_SENDER_ID",
appId: "APP_ID"
};
const app = initializeApp(firebaseConfig);
const auth = getAuth(app)
const firestore = getFirestore(app)
nuxtApp.vueApp.provide('auth', auth)
nuxtApp.provide('auth', auth)
nuxtApp.vueApp.provide('firestore', firestore)
nuxtApp.provide('firestore', firestore)
const store = useStore()
console.log('AUTH', auth)
auth.onAuthStateChanged((user) => {
store.setAuth(user)
})
})

Quasar boot file setup for firebase

I have read multiple posts on how to setup Firebase with Vue & Quasar and am trying to understand the role of the boot file.
Boot file
import { initializeApp } from 'firebase/app'
import { getAuth, onAuthStateChanged } from 'firebase/auth'
const firebaseConfig = {
** my config here **
}
// init firebase
const app = initializeApp(firebaseConfig)
const db = getFirestore(app)
const auth = getAuth(app)
console.log('FB App: ', app)
// functions
onAuthStateChanged((user) => {
console.log('User state changed')
})
export { db, auth }
When I use firebase in a component do I need to use the following?
import { db, auth } from '#/boot/firebase.js'

Firebase analytics are not supported in this enviroment [duplicate]

I have a react/nextjs app and I have firebase.js as follow:
import firebase from 'firebase/app'
import 'firebase/auth'
import 'firebase/analytics'
import 'firebase/firestore'
const firebaseConfig = {
apiKey: '...'
}
try {
firebase.initializeApp(firebaseConfig)
firebase.analytics()
} catch (err) {
if (!/already exists/.test(err.message)) {
console.error('Firebase initialization error', err.stack)
}
}
export default firebase
I kept getting
Firebase initialization error ReferenceError: navigator is not defined
after adding analytics to the firebase.js file. What is the correct way to add analytics to the app?
import { getAnalytics, isSupported } from "firebase/analytics";
const analytics = isSupported().then(yes => yes ? getAnalytics(app) : null);
Try this one
import firebase from "firebase/app"
import "firebase/auth"
import "firebase/firestore"
import "firebase/storage"
import "firebase/analytics"
const firebaseConfig = {
apiKey: process.env.NEXT_PUBLIC_API_KEY,
authDomain: process.env.NEXT_PUBLIC_AUTH_DOMAIN,
projectId: process.env.NEXT_PUBLIC_PROJECT_ID,
appId: process.env.NEXT_PUBLIC_APP_ID,
storageBucket: process.env.NEXT_PUBLIC_STORAGE_BUCKET,
messagingSenderId: process.env.NEXT_PUBLIC_MESSAGING_SENDER_ID,
measurementId: process.env.NEXT_PUBLIC_MEASUREMENT_ID,
}
if (!firebase.apps.length) {
firebase.initializeApp(firebaseConfig)
}
// Auth export
export const auth = firebase.auth()
// Firestore exports
export const firestore = firebase.firestore()
export const serverTimestamp = firebase.firestore.FieldValue.serverTimestamp
export const fbTimestamp = firebase.firestore.Timestamp
export const fromMillis = firebase.firestore.Timestamp.fromMillis
export const increment = firebase.firestore.FieldValue.increment
// Storage exports
export const storage = firebase.storage()
export const analytics = () => {
if (typeof window !== "undefined") {
return firebase.analytics()
} else {
return null
}
}
export default firebase
ReferenceError: navigator is not defined
because there is no window object present during the server-side rendering of the Nextjs application.
Try:
if(typeof window != undefined){
firebase.analytics()
}
I just updated my firebase to version 9 and this error is not seen.
Update to version 9 could be a solution to this.
But for version 9, there are some changes in firebase declaration.
import firebase from 'firebase/compat/app'
import 'firebase/compat/auth'
import 'firebase/compat/firestore'
Using firebase V 9.16 this how I solved the issue
import { initializeApp } from "firebase/app";
import { getAnalytics, isSupported } from "firebase/analytics";
import { getFirestore } from "firebase/firestore"
const firebaseConfig = {
...
};
let app; let analytics; let db
if(typeof window != undefined){
app = initializeApp(firebaseConfig);
analytics = isSupported().then(yes => yes ? getAnalytics(app) : null);
db = getFirestore(app)
}
export {app, analytics, db}
In _app.js I import analytics and i use useEffect like
useEffect(() => {
analytics;
}, [])

How to initialize web app using Firebase 9? React native and Expo

I'm trying to initialize the app but I get can't find variable firebase, I'm still learning and it's hard to understand firebase. I'm using the latest SDK version
here's how I'm doing that
import { initializeApp } from 'firebase/app';
const firebaseConfig = {
/// config
};
if (!firebase.apps.length) {
initializeApp(firebaseConfig);
}
import { getFirestore, collection, getDocs } from 'firebase/firestore';
const db = getFirestore();
const analytics = getAnalytics(app);

Expo Snack: _firebase.default.firestore is not a function

I made a service in my React Native Expo Snack app that handles the instantiation of different firebase services. Somehow, Snack isn't able to find firestore, as it says "_firebase.default.firestore is not a function". The code used is shows below:
import firebase, { firestore } from 'firebase';
const config = { ... // Deleted, assume the config is correct }
export const FirebaseApp = !firebase.apps.length ? firebase.initializeApp(config) : firebase.app();
export const Firestore = firebase.firestore();
export const Auth = firebase.auth();
Can somebody confirm this should work in Snack? Why doesn't it recognize firestore() as a function?

Resources