Reputation: 13366
I'm new to SvelteKit and want to make sure I'm not missing something obvious. Where is the best place to store auth status so I can grant/block access to parts of my app efficiently -- using Firebase Auth?
Right now I'm storing it in a writable store. Like so:
import { writable } from 'svelte/store'
import type firebase from 'firebase/auth'
const authStore = writable<{
isLoggedIn: boolean,
user?: firebase.UserInfo
}>({
isLoggedIn: false
})
And then in __layout.svelte I use it like so:
onMount(() => {
onAuthStateChanged(auth, (user) => {
authStore.set({
isLoggedIn: user != null,
user
})
})
})
I should add, I use the static adapter as all my "server" side code will be in Firebase Cloud Functions and won't be using endpoints.
But occasionally during dev I run into SSR issues... I'm not sure if I can (or should) be using context="module" over onMount, etc.
The Svelte and SvelteKit docs are amazing but don't delve into scenarios -- like best practices of maintaining auth across pages, etc.
That aside, so far SvelteKit + Firebase has been a fantastic platform to work in.
Upvotes: 2
Views: 1102
Reputation: 1234
I usually wrap my client side stuff with an additional browser check. This helps with ssr issues.
import {browser} from '$app/env';
if (browser){
onMount(() => {
onAuthStateChanged(auth, (user) => {
authStore.set({
isLoggedIn: user != null,
user
})
})
})
}
I've also noticed that Firebase's onAuthStateChanged event often fires twice when the auth state is changed, which is somewhat confusing. This is discussed in various places if you search for "firebase onauthstatechanged runs twice". This doesnt entirely answer your question but will hopefully save you some time.
Upvotes: 1