I'm working with SvelteKit and Firebase to build a website. There's a document in my Firestore that only logged in users can accces, I already set a rule for that. The problem that I'm facing is that the load function which fetchs data from the database is sending back a permission denied error as if the user is not logged in. The load function seems to run before the auth state if changed.
I tried using a simple store that stores the authenticated user to check if the user is signed in, but unfortunately the getDoc function can't be awaited
// $lib/stores/authStore.jsimport { writable } from 'svelte/store';import { auth } from '$lib/firebase';import { onAuthStateChanged } from 'firebase/auth';export function authStore(auth) { let unsubscribe; const { subscribe } = writable(auth.currentUser, (set) => { unsubscribe = onAuthStateChanged(auth, (user) => { set(user); }); return () => unsubscribe; }); return { subscribe };}
// +page.server.jsimport { authStore } from '$lib/stores/authStore.js';import { doc, getDoc } from 'firebase/firestore';export async function load() { let protectedDoc; authStore.subscribe((user) => { if (user) { const docRef = doc(db, 'myCollection/myDoc') await getDoc(docRef).then((snapshot) => { protectedDoc = snapshot.data(); }); return { protectedDoc } }; })}
I tried something similar to a few discussions, but had no successSvelteKit async function load not working or Firebase onAuthStateChanged cannot be made blocking
Sveltekit: Wait for resolve in +layout.ts before load() in +page.ts
How should I write this load function in order to the read the firebase document only after user auth state is not null?