'Firebase Analytics with Next.js - window not definded

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}


Solution 1:[1]

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};

Solution 2:[2]

The version 9 SDK doesn't check for the window object. You will have to implement your own check with something like typeof window !== "undefined".

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Adam Beleko
Solution 2 Max