# Observing Supabase Auth State Changes

![Observing Supabase Auth State Changes](https://cdn.hashnode.com/res/hashnode/imageupload/v1678070977750/436dd43c-1360-4a36-acac-a7f91fc7e446.png)

library\_books Observing Supabase Auth State Changes
----------------------------------------------------

###### _4 min read_

[

![Jonathan Gamble](https://cdn.hashnode.com/res/hashnode/imageupload/v1678070979322/446edd1d-ce2c-4127-856b-7cb6984a37a1.png)

**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](https://supabase.com/docs/reference/javascript/).

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

  

* * *

library\_books Local Supabase Auth Setup
----------------------------------------

###### _5 min read_

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

* * *
