Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

keep user logged in while using supabase in react native

I built an auth function that looks like this:

const handleLogin = async (type) => {
    const { user, error } =
      type === "LOGIN"
        ? await supabase.auth.signIn({ email, password })
        : await supabase.auth.signUp({ email, password });

    if (error) {
      alert(error);
    } else if (!user && !error) {
      alert("An email has been sent to you for verification!");
    }
  };

Fetching the jwt and getting the user:

   useEffect(() => {
    
        async () => {
          const jwt = await AsyncStorage.getItem("user");
          const currentUser = supabase.auth.api.getUser(jwt)
          console.log(currentUser)
        }
    
    
        const session = supabase.auth.session();
        setUser(session?.user ?? null);
    
        const { data: authListener } = supabase.auth.onAuthStateChange(
          async (event, session) => {
            const currentUser = session?.user;
            await AsyncStorage.setItem("user", session.access_token);
            console.log(await AsyncStorage.getItem("user"));
            setUser(currentUser ?? null);
          }
        );
    
        return () => {
          authListener?.unsubscribe();
        };
      }, [user]);

but I can't seem to find a way to keep the user logged in inside the app. everytime it restarts the user needs to login again.

Any ideas? Thanks in advance!

like image 427
Menash Bouhadana Avatar asked Sep 07 '26 14:09

Menash Bouhadana


2 Answers

Do make sure to instantiate the supabase client with the AsyncStorage and the following options:

import AsyncStorage from '@react-native-async-storage/async-storage';
import { createClient } from '@supabase/supabase-js'

const supabaseUrl = YOUR_REACT_NATIVE_SUPABASE_URL
const supabaseAnonKey = YOUR_REACT_NATIVE_SUPABASE_ANON_KEY

export const supabase = createClient(supabaseUrl, supabaseAnonKey, {
  localStorage: AsyncStorage as any,
  autoRefreshToken: true,
  persistSession: true,
  detectSessionInUrl: false,
});
like image 114
thorwebdev Avatar answered Sep 10 '26 03:09

thorwebdev


but I can't seem to find a way to keep the user logged in inside the app. everytime it restarts the user needs to login again.

The JS library should already be detecting the user session from the AsyncStorage and restoring it automatically. You can see this logic inside the Auth lib:

Call from constructor: https://github.com/supabase/gotrue-js/blob/8d7eef85a41c5e94a1336f0f44eacc5253186e9b/src/GoTrueClient.ts#L106-L107

Which calls this function: https://github.com/supabase/gotrue-js/blob/8d7eef85a41c5e94a1336f0f44eacc5253186e9b/src/GoTrueClient.ts#L637

You should be able to just add a listener (supabase.auth.onAuthStateChange()) and it will get triggered once the library has refreshed the session. You can add the listener in a useEffect (like you do above), but without the [user] argument so that it is set up immediately.

like image 21
kiwicopple Avatar answered Sep 10 '26 03:09

kiwicopple



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!