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

使用Firebase signInWithPopup实现Google登录时遭遇firebase/init.json 404错误

Firebase signInWithPopup实现Google登录时遭遇firebase/init.json 404错误

看起来你在使用Firebase Google登录时碰到了firebase/init.json 404的问题,而且你的Auth Domain是官方的firebaseapp.com域名,我来帮你梳理几个可能的解决方向:

1. 避免Firebase重复初始化

你现在在Login组件内部直接执行initializeApp,在Next.js客户端组件里,每次组件渲染都会重新跑这段代码,很容易导致初始化异常,进而引发资源加载错误。建议把Firebase初始化抽离到单独的文件中,确保整个应用只初始化一次:

// utils/firebaseClient.ts
"use client";
import { initializeApp } from "firebase/app";
import { getAuth } from "firebase/auth";

const firebaseConfig = {
    apiKey: "xxxxxxxxxxxxxxxxxxxxxxxxx",
    authDomain: "xxxxxx.firebaseapp.com",
    projectId: "xxxxxx",
    storageBucket: "xxxxx.firebasestorage.app",
    messagingSenderId: "xxxxxx",
    appId: "xxxxxxxxxxx",
    measurementId: "xxxxxx"
};

// 全局只初始化一次Firebase App
const app = initializeApp(firebaseConfig);
export const auth = getAuth(app);

然后在Login组件里直接导入这个auth实例即可,不用再重复初始化:

import { auth } from "./utils/firebaseClient";

2. 检查Firebase控制台的Auth配置

  • 打开Firebase控制台,进入你的项目 → Authentication → Sign-in method,确认Google登录已经被启用;
  • 切换到Settings标签页,检查Authorized domains列表,确保你的xxxxxx.firebaseapp.com已经在列表中(默认情况下Firebase会自动添加,但手动核对一下更稳妥)。

3. 统一登录方式的代码实现

你描述里说用的是signInWithPopup,但代码里实际写的是signInWithRedirect。如果确实想用弹窗登录,把代码改成这样:

const signInWithGoogle = async () => {
    try {
        setInProgress(true);
        const provider = new GoogleAuthProvider();
        const result = await signInWithPopup(auth, provider);
        // 这里可以处理登录成功后的逻辑,比如获取用户信息
        const user = result.user;
        console.log("登录成功:", user);
    } catch (error) {
        console.error("登录失败:", error);
        setInProgress(false);
    }
};

另外,使用弹窗登录时要确保浏览器允许弹出窗口,否则也可能引发异常。

4. 正确处理重定向结果的时机

如果你坚持使用signInWithRedirect,建议把getRedirectResult的调用放到useEffect里,避免组件每次渲染都执行:

useEffect(() => {
    const handleRedirect = async () => {
        try {
            const data = await getRedirectResult(auth);
            if (data) {
                console.log("重定向登录结果:", data);
                router.push("/"); // 登录成功后跳转
            }
        } catch (error) {
            console.error("处理重定向结果出错:", error);
        }
    };
    handleRedirect();
}, [auth, router]);

5. 排除浏览器缓存干扰

有时候浏览器缓存会导致资源加载异常,试试清除浏览器缓存后重新测试,或者用隐身窗口打开页面,看看是否还会出现404错误。

备注:内容来源于stack exchange,提问作者gilzonme

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.04.14 18:13:00