Home
>
Observing Supabase Auth State Changes

Observing Supabase Auth State Changes

3 min read
Jonathan Gamble

jdgamble555 on Wednesday, October 19, 2022 (last modified on Sunday, December 17, 2023)

We need to subscribe to the auth state of Supabase at all times, but each framework has their own approach to this. Here is a compilation. We must get the current state, then subscribe to onAuthStateChange.

Note: all my tutorials use the JS SDK V2.

All of the code follows the same pattern:

  1. Get and save the current user state
  2. Subscribe to any changes, save user state on change

Angular - Observable

This assumes you have this.supabase variable.

	authState(): Observable<User | null> {
  return new Observable((subscriber: Subscriber<User | null>) => {
    this.supabase.auth.getSession().then(session =>
      subscriber.next(session.data.session?.user)
    );
    const auth = this.supabase.auth.onAuthStateChange(async ({ }, session) => {
      subscriber.next(session?.user);
    });
    return auth.data.subscription.unsubscribe;
  });
}

React - Hooks

This assumes you have imported your supabase variable as well as useEffect and useState.

	export const useAuthState = ():  User | null => {
  const [user, setUser] = useState<User | null>(null);

  supabase.auth.getSession().then(session =>
    setUser(session.data.session?.user);
  );

  useEffect(() => {
    const auth = supabase.auth.onAuthStateChange(async ({ }, session) => {
      setUser(session?.user);
    });
    return auth.data.subscription.unsubscribe;
  }, []);
  return user;
};

Svelte - Stores

This assumes you have imported your supabase variable as well as readable.

	export const authState = readable(null, (set: Subscriber<User | null>) => {
  supabase.auth.getSession().then(session =>
    set(session.data.session?.user);
  );
  const auth = supabase.auth.onAuthStateChange(async ({ }, session) => {
    set(session?.user);
  });
  return auth.data.subscription.unsubscribe;
};

Now if you want to setup this up to get the session information instead of directly the user information, you could easily change the code.

TODO: Vue, SolidJS, Angular Service, QWIK

Happy Supabasing,

J


Related Posts

© 2024 Code.Build