Search code examples
reactjsoauth-2.0supabasesupabase-js

Supabase Auth: Google Oauth is succesful, but onAuthStateChange is not triggered


I'm building a Google slides add on. The DB operations are implemented using Supabase and the frontend using React.

I'm trying to use Supabase oauth to authenticate the user via Google.

Here's my code:

const handleSignIn = async () => {
    const { data, error } = await supabaseClient.auth.signInWithOAuth({
      provider: 'google',
      options: {
        skipBrowserRedirect: true,
        redirectTo: 'https://<domain>.com/success',
      },
    });

    if (error || !data || !data.url) {
      console.error('Error signing in:', error);
      return;
    }

    // open google oauth consent screen in new tab
    // without this it tries to open the iframe inside the modal which Google doesn't allow
    // check https://stackoverflow.com/questions/71819128/supabase-auth-onauthstatechange-not-working-when-react-app-is-in-iframe
    window.open(data.url, '_blank');
  };

The user clicks on the link, and is able to sign in. Supabase creates a user identity in the auth.users table. However, I'm unable to get the details of the signed in user. In my top level component I have this:

  const [session, setSession] = useState<Session | null>(null);

  useEffect(() => {
    supabaseClient.auth.getSession().then(({ data: { session } }) => {
      console.log('got session', session);
      setSession(session);
    });

    supabaseClient.auth.onAuthStateChange((event, session) => {
      console.log('authChanged', event, session);
      setSession(session);
    });
  }, []);

The session is always null and I am only seeing 1 console log for INITIAL_SESSION which is null. I can't see any other auth state changes when the user signs in or out.

How do I get the logged in user's auth state changes?


Solution

  • The problem in my case was that the page I was routing to was stripping the access token before Supabase could process it