NextJS:如何正确地将 Firebase 分析添加到 NextJS 应用程序

问题描述 投票:0回答:7

我有一个react/nextjs应用程序,我有firebase.js,如下:

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

我不断得到

Firebase初始化错误ReferenceError:导航器未定义

将分析添加到 firebase.js 文件后。将分析添加到应用程序的正确方法是什么?

javascript reactjs vue.js google-cloud-firestore next.js
7个回答
36
投票
import { getAnalytics, isSupported } from "firebase/analytics";

const analytics = isSupported().then(yes => yes ? getAnalytics(app) : null);


6
投票

试试这个

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

2
投票

使用 firebase V 9.16 这就是我解决问题的方法

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}

在 _app.js 中,我导入分析并使用 useEffect 之类的

useEffect(() => {
    analytics;
  }, [])

1
投票

ReferenceError: navigator is not defined
因为在 Nextjs 应用程序的服务器端渲染期间不存在窗口对象。

尝试:

if(typeof window != undefined){
     firebase.analytics()
}

1
投票

使用顶级等待

import { initializeApp } from "firebase/app";
import { getAnalytics, isSupported } from "firebase/analytics";

const firebaseConfig = {
  ... 
};

const firebaseApp = initializeApp(firebaseConfig);

const analytics = await isSupported() ? getAnalytics(firebaseApp) : null

export { analytics }

然后使用 firebase/analytics 中的 logEvent

import { logEvent } from "firebase/analytics";
import { analytics } from "../../firebase/init";

  useEffect(() => {

    analytics && logEvent(analytics, 'page_view', {
      page_title: "/",
      page_path: "/",
    });

  }, [])

0
投票

我刚刚将我的 Firebase 更新到版本 9,并且没有看到此错误。

更新到版本 9 可能是解决此问题的方法。

但是对于版本 9,firebase 声明有一些变化。

import firebase from 'firebase/compat/app'
import 'firebase/compat/auth'
import 'firebase/compat/firestore'

0
投票

仅靠最上面的答案并不能以某种方式为我解决问题。我最后就是这样做的:

import { initializeApp } from "firebase/app";
import { getAnalytics, logEvent, isSupported } from "firebase/analytics";


const firebaseConfig = {
  // ...
};

const app = initializeApp(firebaseConfig);

const analytics = isSupported().then((isSupported) => (isSupported ? getAnalytics(app) : null));

export const logCustomEvent = async (event: MyCustomEventType | string) => {
    if (!analytics) return;

    logEvent(getAnalytics(), event, { platform: "web" });
};

在组件内的使用就像

logCustomEvent(MyEvents.FooBar)

getAnalytics()
中使用
logEvent
很重要,否则我会出错。

© www.soinside.com 2019 - 2024. All rights reserved.