🫧

auth.currentUserが取得できない

2025/03/11に公開

はじめに

auth.currentUserを実装しても、値が取得できなかったのでできるようにしました。

auth.currentUserとは

auth.currentUserは、Firebase Authenticationを使用する際に、現在ログインしているユーザーを取得するためのプロパティです。

auth.currentUserが取得できない

下記のコードを書いたのですが、auth.currentUserの値が取得できませんでした。

src/hooks/useAuth.tsx
import { auth } from '../firebase/firebase'

export async function fetchIdToken() { 
  console.log('🔥 Checking auth.currentUser:', auth.currentUser)

  if (auth.currentUser) {
    const idToken = await auth.currentUser.getIdToken()
    console.log('✅ ID Token:', idToken)
    return idToken
  } else {
    console.error('User is not authenticated')
    return null
  }
}

対応

onAuthStateChangedを使ってFirebase Authenticationの初期化完了をさせる処理を入れました。

src/hooks/useAuth.tsx
import { auth } from '../firebase/firebase'

export async function fetchIdToken() {
  // 認証状態が初期化されるまで待機
  await new Promise(resolve => {
    const unsubscribe = auth.onAuthStateChanged(user => {//認証状態の変更を監視 
      unsubscribe()//監視を解除
      resolve(user)//Promiseが解決され,awaitが完了
    })
  })

  console.log('🔥 Checking auth.currentUser:', auth.currentUser)

  if (auth.currentUser) {
    const idToken = await auth.currentUser.getIdToken()
    console.log('✅ ID Token:', idToken)
    return idToken
  } else {
    console.error('User is not authenticated')
    return null
  }
}

どうしてonAuthStateChangedを入れる必要があるのか

Firebaseのauth.currentUserは、認証状態が確定する前にnullになることがあるからです。
特にアプリの初回読み込み時やページリロード時にauth.currentUserをすぐ参照するとnullになる可能性があります。

そのため、onAuthStateChangedを使って認証状態が確定するまで待機することで、確実にauth.currentUserにアクセスできるようにしています。

こちらの内容は公式ドキュメントに書いてあります。
https://firebase.google.com/docs/auth/web/manage-users#web

The recommended way to get the current user is by setting an observer on the Auth object

現在のユーザーを取得するおすすめの方法は、Authオブジェクトにオブザーバーを設定することです。

By using an observer, you ensure that the Auth object isn't in an intermediate state—such as initialization—when you get the current user. When you use signInWithRedirect, the onAuthStateChanged observer waits until getRedirectResult resolves before triggering.

オブザーバを使うことで、現在のユーザを取得するときに Auth オブジェクトが初期化などの中間状態にないことを保証します。signInWithRedirect を使用する場合、onAuthStateChanged オブザーバは getRedirectResult が解決するまで待ってから起動します。

You can also get the currently signed-in user by using the currentUser property. If a user isn't signed in, currentUser is null

currentUserプロパティを使用して、現在サインインしているユーザーを取得することもできます。ユーザがサインインしていない場合、currentUserはNULLになります。

オブザーバーとは

ここでいうオブザーバー (observer) とは、Firebase Authの認証状態の変化を監視するイベントリスナーのことを指します。

Firebase Authでは、onAuthStateChangedがオブザーバーに該当します。
onAuthStateChangedを使うと、ユーザーのログイン・ログアウトの変化を監視し、自動的に処理を実行できます。

Discussion