React集成Firebase认证遇app/no-options错误,求未部署时修复方案
修复Firebase认证初始化错误(app/no-options)
我正在开发一个带认证功能的React项目,使用Firebase实现认证,目前遇到如下错误:
Firebase: Need to provide options, when not being deployed to hosting via source. (app/no-options)
以下是我的config-firebase文件代码:
import { initializeApp } from "firebase/app"; import { getAuth } from "firebase/auth"; // For Firebase JS SDK v7.20.0 and later, measurementId is optional const firebaseConfig = { apiKey: "AIzaSyBoKEW_g0gOwNKkHGMAyhXxC0ESfdsVhKI", authDomain: "kargoevi-auth.firebaseapp.com", projectId: "kargoevi-auth", storageBucket: "kargoevi-auth.appspot.com", messagingSenderId: "726037811463", appId: "1:726037811463:web:42d75c7f5c1d1b5b9bf5a2", measurementId: "G-PJXGLVZ6GQ", }; export const auth = getAuth(app); const app = initializeApp(firebaseConfig); export default app;
以下是我的Auth文件代码:
import React, { useState, useEffect } from "react"; import { onAuthStateChanged } from "firebase/auth"; import { auth } from "./base"; export const AuthContext = React.createContext(); export const AuthProvider = ({ children }) => { const [currentUser, setCurrentUser] = useState(null); const [pending, setPending] = useState(true); useEffect(() => { onAuthStateChanged(auth, (user) => { setCurrentUser(user); setPending(false); }); }, []); if (pending) { return <>Loading...</>; } return ( <AuthContext.Provider value={{ currentUser, }} > {children} </AuthContext.Provider> ); };
注:目前尚未部署该项目,请问该如何修复这个错误?
错误原因
代码执行顺序错误:你先调用了getAuth(app),但此时app变量还未通过initializeApp(firebaseConfig)完成初始化,导致getAuth接收的是未定义的参数,触发了app/no-options错误。
修复方案
调整代码顺序,先完成Firebase App的初始化,再基于已初始化的App创建Auth实例:
import { initializeApp } from "firebase/app"; import { getAuth } from "firebase/auth"; // For Firebase JS SDK v7.20.0 and later, measurementId is optional const firebaseConfig = { apiKey: "AIzaSyBoKEW_g0gOwNKkHGMAyhXxC0ESfdsVhKI", authDomain: "kargoevi-auth.firebaseapp.com", projectId: "kargoevi-auth", storageBucket: "kargoevi-auth.appspot.com", messagingSenderId: "726037811463", appId: "1:726037811463:web:42d75c7f5c1d1b5b9bf5a2", measurementId: "G-PJXGLVZ6GQ", }; // 先初始化Firebase App const app = initializeApp(firebaseConfig); // 再基于已初始化的App创建Auth实例 export const auth = getAuth(app); export default app;
额外检查
确认Auth文件中的导入路径正确:当前代码中是import { auth } from "./base";,如果你的Firebase配置文件实际名为config-firebase.js,需要将导入路径修改为import { auth } from "./config-firebase";,避免因导入路径错误导致的其他问题。
内容的提问来源于stack exchange,提问作者Hazal Kaya
相关产品推荐
相关产品推荐

