Auth Store

Access the current user with Svelte stores

SvelteFire

You can skip the code and just install SvelteFire to use this store.

Simple Store

A simple implementation for prototyping

file_type_typescript firebase.ts
const currentUser = writable<User | null>(null);

onAuthStateChanged(auth, (user) => {
  currentUser.set(user);
});

Custom Store

Full implementation with unsubscribe and SSR support.

file_type_typescript firebase.ts
/**
 * @returns a store with the current firebase user
 */
function userStore() {
  let unsubscribe: () => void;

  if (!auth || !globalThis.window) {
    console.warn('Auth is not initialized or not in browser');
    const { subscribe } = writable<User | null>(null);
    return {
      subscribe,
    }
  }

  const { subscribe } = writable(auth?.currentUser ?? null, (set) => {
    unsubscribe = onAuthStateChanged(auth, (user) => {
      set(user);
    });

    return () => unsubscribe();
  });

  return {
    subscribe,
  };
}

export const user = userStore();

Questions? Let's chat

Open Discord