Skip to content

Firestore not working in beforeAuthStateChanged #8302

@polRk

Description

@polRk

Operating System

macOS

Browser Version

125.0.6422.141

Firebase SDK Version

10.12.2

Firebase SDK Product:

Auth, Firestore

Describe your project's tooling

Vite

Describe the problem

Missing Authorization header when requesting firestore inside beforeAuthStateChanged.

NOT WORKING

beforeAuthStateChanged(auth, async (user) => {
	if (!user) {
		return
	}

	await auth.authStateReady()

	await runTransaction(firestore, async (transaction) => {
		const docRef = doc(firestore, 'users', user.uid)
		const docSnap = await transaction.get(docRef)
		if (!docSnap.exists()) {
			transaction.set(docRef, { email: user.email })
		}

		return
	})
})

WORKING

onAuthStateChanged(auth, async (user) => {
	if (!user) {
		return
	}

	await auth.authStateReady()

	await runTransaction(firestore, async (transaction) => {
		const docRef = doc(firestore, 'users', user.uid)
		const docSnap = await transaction.get(docRef)
		if (!docSnap.exists()) {
			transaction.set(docRef, { email: user.email })
		}

		return
	})
})

Steps and code to reproduce issue

// rules
service cloud.firestore {
  match /databases/{database}/documents {
    match /users/{userId} {
      allow create, read, update: if request.auth != null && request.auth.uid == userId;
    }

    match /{document=**} {
      allow read, write: if false;
    }
  }
}
const auth = getAuth(app)
const firestore = getFirestore(app)

beforeAuthStateChanged(auth, async (user) => {
	if (!user) {
		return
	}

	await auth.authStateReady()

	await runTransaction(firestore, async (transaction) => {
		const docRef = doc(firestore, 'users', user.uid)
		const docSnap = await transaction.get(docRef)
		if (!docSnap.exists()) {
			transaction.set(docRef, { email: user.email })
		}

		return
	})
})

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions