Verified Production Fix
[supabase/supabase] Login using github auto logging out
GH-supabase#43508
### ROOT CAUSE
The issue is caused by improper handling of the authentication state and token storage when using GitHub OAuth for login. The application fails to persist the authentication token in `localStorage`, leading to the user being logged out after a page refresh or navigation.
### CODE FIX
javascript
// In your authentication service or component
import { createClient } from '@supabase/supabase-js';
import { useUser } from '@supabase/auth-helpers-react';
const supabase = createClient('your-supabase-url', 'your-supabase-anon-key');
// Store the token in localStorage when the user logs in
supabase.auth.onAuthStateChange(async (event, session) => {
if (session?.access_token) {
localStorage.setItem('supabase-auth-token', session.access_token);
}
});
// Retrieve the token from localStorage and re-authenticate on app load
const initializeAuth = async () => {
const storedToken = localStorage.getItem('supabase-auth-token');
if (storedToken) {
const { data, error } = await supabase.auth.getUser(storedToken);
if (data) {
supabase.auth.setSession({ user: data.user });
}
}
};
// Call initializeAuth when your app loads
initializeAuth();
// Use the useUser hook to get the current user
const { user } = useUser();
This fix ensures that the authentication token is stored in `localStorage` upon successful login and is retrieved and used to re-authenticate the user when the application loads, preventing the automatic logout issue.
digital