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

Next.js集成Firebase v9认证时报auth is not a function错误如何解决

问题排查与解决方法

你的错误由3处代码不符合Firebase v9 compat模式使用规则、React Hook调用规则导致,按以下步骤修改即可:

  • 修正firebase/auth的引入路径:Firebase v9的compat兼容模式下,所有子服务也需要从compat路径引入,把import "firebase/auth"替换为import "firebase/compat/auth"
  • 删除auth实例化代码多余的.default:你已经通过默认导入拿到了firebase compat实例,不需要再访问.default属性,把const auth = firebase.default.auth();替换为const auth = firebase.auth();
  • 调整useAuthState调用位置:React Hook只能在函数组件内部或自定义Hook中调用,你当前把const [user] = useAuthState(auth);写在了Home组件外部,需要移动到Home组件内部。

修改后的完整代码

import Head from "next/head";
import firebase from "firebase/compat/app";
import "firebase/compat/auth";
import { useAuthState } from "react-firebase-hooks/auth";
import Reddit from "../components/Reddit";

// 增加初始化判断,避免热重载时重复初始化报错
if (!firebase.apps.length) {
  firebase.initializeApp({
    apiKey: "<api-key>",
    authDomain: "<auth-domain>",
    projectId: "<project-id>",
    storageBucket: "<storage-bucket>",
    messagingSenderId: "166670883433",
    appId: "1:166670883433:web:f24816c8fe909b0f89e0f8",
  });
}
const auth = firebase.auth();

export default function Home() {
  // Hook移到组件内部调用
  const [user] = useAuthState(auth);
  return (
    <div className="h-screen bg-black text-white">
      <Head>
        <title>Reddit - Dive into anything!</title>
        <link rel="icon" href="/logo.svg" />
      </Head>
      {user ? <Reddit /> : <SignIn />}
    </div>
  );
}

function SignIn() {
  const signInWithGoogle = () => {
    const provider = new firebase.auth.GoogleAuthProvider();
    auth.signInWithPopup(provider);
  };
  return (
    <div>
      <button onClick={signInWithGoogle}>Sign in with google</button>
    </div>
  );
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.24 18:15:03