You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Next.js使用Firebase 9.0.1时报错Cannot read property 'apps' of undefined如何解决?

问题原因

Firebase v9及以上版本默认采用模块化API设计,不再支持旧版本的命名空间导入方式,你当前写的import firebase from "firebase/app"导入后得到的是undefined,所以访问firebase.apps才会抛出类型错误。

解决方案

方案1:使用compat兼容包(快速适配旧代码,无需大幅修改逻辑)

修改firebase.js的导入语句为compat版本即可,完整代码如下:

// 导入compat版本,兼容v8的命名空间写法
import firebase from "firebase/compat/app";
import "firebase/compat/firestore";
import "firebase/compat/auth";

const firebaseConfig = {
  // 你的配置保持不变
  apiKey: "",
  authDomain: "",
  projectId: "",
  storageBucket: "",
  messagingSenderId: "",
  appId: "",
  measurementId: ""
};

const app = !firebase.apps.length
  ? firebase.initializeApp(firebaseConfig)
  : firebase.app();

const db = app.firestore();
const auth = app.auth();
const provider = new firebase.auth.GoogleAuthProvider();

export { db, auth, provider };

这个方案改完即可直接运行,不需要修改其他调用firebase的业务逻辑。

方案2:使用v9原生模块化写法(官方推荐,长期维护更优)

完全适配v9的新API,打包体积更小,代码如下:

import { initializeApp, getApps, getApp } from "firebase/app";
import { getFirestore } from "firebase/firestore";
import { getAuth, GoogleAuthProvider } from "firebase/auth";

const firebaseConfig = {
  // 你的配置保持不变
  apiKey: "",
  authDomain: "",
  projectId: "",
  storageBucket: "",
  messagingSenderId: "",
  appId: "",
  measurementId: ""
};

// 初始化逻辑等价于之前的存在性判断
const app = getApps().length === 0 ? initializeApp(firebaseConfig) : getApp();

const db = getFirestore(app);
const auth = getAuth(app);
const provider = new GoogleAuthProvider();

export { db, auth, provider };

如果选择该方案,后续其他业务代码调用Firebase的方法也需要同步改成模块化写法,比如Firestore查询需要从db.collection('xxx').get()调整为getDocs(collection(db, 'xxx'))。

内容的提问来源于stack exchange,提问作者soykot2910

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.05 21:12:03