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

Next.js项目集成Firestore失败求助:配置后无法正常运行

Next.js 集成 Firebase 报错解决

我在Next.js项目中执行npm i firebase安装了Firebase,复制配置代码后无法正常使用,出现如下报错。

页面组件代码

import Head from 'next/head'
import Image from 'next/image'
import { Inter } from '@next/font/google'
import { useEffect, useState } from 'react'
import { dbb } from '@/src/providers/firebase'

const inter = Inter({ subsets: ['latin'] })

export default function Home() {
  const [data, setData] = useState(null);
  useEffect(() => {
    const unsubscribe = dbb.collection('languages').onSnapshot((snapshot) => {
      const data = [];
      snapshot.forEach((doc) => {
        data.push({ id: doc.id, ...doc.data() })
      });
      setData(data);
      console.log(data);
    })
  }, []);
// ... 剩余代码

Firebase 配置文件代码

// Import the functions you need from the SDKs you need
import { initializeApp } from "firebase/app";

// TODO: Add SDKs for Firebase products that you want to use
// https://firebase.google.com/docs/web/setup#available-libraries

// Your web app's Firebase configuration
// For Firebase JS SDK v7.20.0 and later, measurementId is optional
const firebaseConfig = {
    // 你的配置内容
};

// Initialize Firebase
const app = initializeApp(firebaseConfig);

export const dbb = getFirestore(app);

报错信息

报错截图
报错内容:ReferenceError: getFirestore is not defined

解决方法

  1. 补充缺失的导入语句
    配置文件中使用了getFirestore方法,但未从Firebase SDK中导入。需在配置文件顶部添加导入:
import { getFirestore } from "firebase/firestore";

修改后的完整配置文件:

// Import the functions you need from the SDKs you need
import { initializeApp } from "firebase/app";
import { getFirestore } from "firebase/firestore"; // 新增导入

// 你的Firebase配置
const firebaseConfig = {
    // 配置内容
};

// Initialize Firebase
const app = initializeApp(firebaseConfig);

export const dbb = getFirestore(app);
  1. 验证依赖版本
    确保安装的Firebase为v9及以上模块化版本,和当前导入方式匹配。若为旧版本,需调整导入方式或升级依赖。

  2. 适配Next.js环境
    在Next.js中建议将Firebase初始化封装为单例模式,避免重复初始化,确保在服务端/客户端组件中正确调用。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.02 10:40:49