Skip to main content

Command Palette

Search for a command to run...

Observing Supabase Auth State Changes

Updated
•2 min read•View as Markdown
Observing Supabase Auth State Changes

Observing Supabase Auth State Changes

library_books Observing Supabase Auth State Changes

4 min read

[

Jonathan Gamble

jdgamble555 on Wednesday, October 19, 2022 (last modified on Wednesday, October 19, 2022)

](https://code.build/u/86qJ3nXSvhBPUbmdaMwUeb/jdgamble555)

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 { return new Observable((subscriber: Subscriber) => { 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(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) => { 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


library_books Local Supabase Auth Setup

5 min read


More from this blog

Code.Build

331 posts