Auth state change listeners help your app know when a user logs in or out. This way, your app can update what it shows without needing a refresh.
Auth state change listeners in Supabase
const { data: authListener } = supabase.auth.onAuthStateChange((event, session) => {
// Your code here
});The event tells you what happened, like 'SIGNED_IN' or 'SIGNED_OUT'.
The session contains user info if logged in, or null if logged out.
const { data: authListener } = supabase.auth.onAuthStateChange((event, session) => {
if (event === 'SIGNED_IN') {
console.log('User signed in:', session.user.email);
}
});const { data: authListener } = supabase.auth.onAuthStateChange((event, session) => {
if (event === 'SIGNED_OUT') {
console.log('User signed out');
}
});const { data: authListener } = supabase.auth.onAuthStateChange((event, session) => {
console.log('Auth event:', event);
console.log('Session:', session);
});This program sets up a listener for authentication state changes using Supabase. It logs when a user signs in or out. It runs for 60 seconds before stopping the listener.
import { createClient } from '@supabase/supabase-js'; const supabaseUrl = 'https://xyzcompany.supabase.co'; const supabaseKey = 'public-anonymous-key'; const supabase = createClient(supabaseUrl, supabaseKey); console.log('Starting auth listener...'); const { data: authListener } = supabase.auth.onAuthStateChange((event, session) => { console.log(`Auth event detected: ${event}`); if (event === 'SIGNED_IN' && session) { console.log(`User signed in: ${session.user.email}`); } else if (event === 'SIGNED_OUT') { console.log('User signed out'); } else { console.log('Other auth event or no session'); } }); // Simulate waiting for auth events setTimeout(() => { console.log('Stopping auth listener...'); authListener.subscription.unsubscribe(); }, 60000);
The listener runs in the background and triggers your code whenever the auth state changes.
Remember to unsubscribe the listener when it is no longer needed to avoid memory leaks.
Time complexity is minimal since it reacts only to events, not polling.
Auth state change listeners keep your app updated with user login status.
Use them to show or hide content based on whether a user is signed in.
Always unsubscribe listeners when done to keep your app efficient.