NextJS集成Firebase Google认证时GoogleAuthProvider未定义报错
问题原因&解决方案
- 你使用的是Firebase v9+ 模块化API,代码混用了v8版本的命名空间调用语法
firebaseApp.js未导出firebase对象,login.js中导入的firebase本身就是undefineduiConfig方法接收的参数是auth实例,但代码中错误尝试访问auth.auth.GoogleAuthProvider,该属性不存在firebaseApp.js中连接判断逻辑写反:getApps().length === 0代表还未初始化Firebase,不是连接错误
修正步骤
1. 修正 firebaseApp.js
//firebaseApp.js import { initializeApp, getApps } from "firebase/app" import { getFirestore } from "firebase/firestore" import { getAuth, GoogleAuthProvider } from "firebase/auth" const firebaseConfig = { apiKey: process.env.NEXT_PUBLIC_FIREBASE_API_KEY, authDomain: process.env.NEXT_PUBLIC_FIREBASE_AUTH_DOMAIN, projectId: process.env.NEXT_PUBLIC_FIREBASE_PROJECT_ID, storageBucket: process.env.NEXT_PUBLIC_FIREBASE_STORAGE_BUCKET, messagingSenderId: process.env.NEXT_PUBLIC_FIREBASE_MESSAGING_SENDER_ID, appId: process.env.NEXT_PUBLIC_FIREBASE_APP_ID, measurementId: process.env.NEXT_PUBLIC_FIREBASE_MEASUREMENT_ID, }; // 逻辑修正:只有未初始化时才执行初始化 let app; if (getApps().length === 0) { app = initializeApp(firebaseConfig) } else { app = getApps()[0] } const db = getFirestore(app) const auth = getAuth(app) export { db, auth, GoogleAuthProvider }
2. 修正 firebaseAuthUI.config.js
//firebaseAuthUI.config.js import { GoogleAuthProvider } from "firebase/auth" export const uiConfig = { signInFlow: "popup", signInSuccessUrl: "/", signInOptions: [GoogleAuthProvider.PROVIDER_ID], };
3. 修正 login.js
//login.js import Head from 'next/head'; import { useRouter } from 'next/router'; import { useAuthState } from 'react-firebase-hooks/auth'; import StyledFirebaseAuth from 'react-firebaseui/StyledFirebaseAuth'; import { auth } from '../app/firebaseApp'; import { uiConfig } from '../config/firebaseAuthUI.config'; export default function Login() { const [user, loading, error] = useAuthState(auth); const router = useRouter(); if (loading) return 'loading' if (error) return error.message if (user) { router.push('/'); return null; } return ( <> <Head> <title>Login</title> </Head> <StyledFirebaseAuth uiConfig={uiConfig} firebaseAuth={auth} /> </> ) }
内容的提问来源于stack exchange,提问作者Luke Grech
相关产品推荐
相关产品推荐

