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

NuxtJs应用中Firebase Authentication重定向后onAuthStateChanged返回null

Nuxt中Firebase Authentication重定向后onAuthStateChanged返回null的问题

我在Nuxt应用中使用Firebase Authentication,按照Firebase文档配置GoogleAuthProvider实现认证,但重定向成功后,onAuthStateChanged()监听器始终返回null。

用户进入应用时,Nuxt会在客户端执行插件,初始化Firebase配置后调用useFirebaseAuth.ts中的initUser()函数,若登录成功则打印用户信息。

注:将signInWithRedirect替换为signInWithPopup后,功能可正常运行。

相关代码

plugins/firebase.client.ts

import { initializeApp } from "firebase/app";
import { initUser } from "~~/composables/useFirebaseAuth";

export default defineNuxtPlugin(() => {

    const config = useRuntimeConfig();
    const firebaseConfig = {
        apiKey: "...",
        authDomain: "...",
        databaseURL: "...",
        projectId: "...",
        appId: "...",
        messagingSenderId: "...",

    };

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

    initUser(firebaseApp);
})

composables/useFirebaseAuth.ts

import { FirebaseApp } from "firebase/app";
import { getAuth,signInWithPopup, GoogleAuthProvider, onAuthStateChanged, signInWithRedirect, signOut, User } from "firebase/auth";
import { equalTo, getDatabase, onValue, orderByChild, query, ref as dbRef } from "firebase/database";

export const signInUser = async () => {
    const provider = new GoogleAuthProvider();
    const auth = getAuth();
    await signInWithRedirect(auth, provider)

}


export const initUser = async (firebaseApp: FirebaseApp) => {
    const auth = getAuth(firebaseApp)
    const db = getDatabase()

    onAuthStateChanged(auth, user => {

        if (user) {
            console.log(user)
        } else {
            console.log("user not logged in")
            return navigateTo('/login')

        }
    });
}


export const signOutUser = async () => {
    const auth = getAuth();
    await signOut(auth)
}

项目背景

项目已开发2个月,该认证功能1个月前可正常工作,目前出现此问题。已查阅Stack Overflow相关回答,但未解决问题。

环境信息

  • Node版本:v19.5.0
  • NPM版本:
{
  "npm": "9.3.1",
  "node": "19.5.0",
  "v8": "10.8.168.25-node.11",
  "uv": "1.44.2",
  "zlib": "1.2.13",
  "brotli": "1.0.9",
  "ares": "1.18.1",
  "modules": "111",
  "nghttp2": "1.51.0",
  "napi": "8",
  "llhttp": "8.1.0",
  "uvwasi": "0.0.14",
  "acorn": "8.8.1",
  "simdutf": "3.1.0",
  "undici": "5.14.0",
  "openssl": "3.0.7+quic",
  "cldr": "42.0",
  "icu": "72.1",
  "tz": "2022g",
  "unicode": "15.0",
  "ngtcp2": "0.8.1",
  "nghttp3": "0.7.0"
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.03 00:10:47