【问题标题】:Firebase Analytics with Next.js - window not definded带有 Next.js 的 Firebase Analytics - 未定义窗口
【发布时间】:2021-11-01 16:14:00
【问题描述】:

我正在尝试在 Next.js (firebase v9) 中实现和导出 firebase 分析模块

我收到以下代码 sn-p 的错误 "ReferenceError: window is not defined"。以前的所有功能都运行良好。

任何想法如何解决这个问题?

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}

【问题讨论】:

    标签: javascript reactjs firebase import next.js


    【解决方案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};
    

    【讨论】:

      【解决方案2】:

      版本 9 SDK 不检查窗口对象。您必须使用typeof window !== "undefined" 之类的方式实施自己的检查。

      【讨论】:

        猜你喜欢
        • 2021-10-06
        • 2021-09-19
        • 1970-01-01
        • 2020-05-06
        • 2021-12-02
        • 2021-10-26
        • 2020-07-07
        相关资源
        最近更新 更多