Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Firebase Analytics with Next.js - window not defined

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}
like image 694
maurice Avatar asked Sep 07 '25 11:09

maurice


1 Answers

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};
like image 114
Adam Beleko Avatar answered Sep 10 '25 01:09

Adam Beleko