I'm trying to implement and export the firebase analytics module in Next.js (firebase v9)
I get the error "ReferenceError: window is not defined" for the following code snippet. All previous functions working great.
Any ideas how to fix this?
import { initializeApp, getApps, getApp } from "firebase/app";
import { getAnalytics } from "firebase/analytics";
import { getAuth } from 'firebase/auth'
import { getFirestore } from '@firebase/firestore'
const firebaseConfig = {
//...
};
// Initialize Firebase
const app = !getApps().length ? initializeApp(firebaseConfig) : getApp();
const auth = getAuth();
const db = getFirestore(app)
// try to add analytics
const analytics = getAnalytics(app)
export {auth, db, analytics}
NextJS:
import {initializeApp} from 'firebase/app';
import {getFirestore} from 'firebase/firestore';
import {getAnalytics} from 'firebase/analytics';
const firebaseConfig = JSON.parse(
process?.env?.FIREBASE_CONFIG ?? '{}',
);
let analytics; let firestore;
if (firebaseConfig?.projectId) {
// Initialize Firebase
const app = initializeApp(firebaseConfig);
if (app.name && typeof window !== 'undefined') {
analytics = getAnalytics(app);
}
// Access Firebase services using shorthand notation
firestore = getFirestore();
}
export {analytics, firestore};
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With