ekno
ekno

Reputation: 69

User needs to refresh the page to get logged in after third party authentification (Supabase, NextJS)

I'm using supabase with next and third party auth. The problem is that my user has to refresh the page to get logged in after using third party auth. I have tried getting the user's data from the client side with supabase methods and useEffect and from the server side with getServerSideProps with supabase methods and sql request but my userState won't update. However I can see the created user token in my localStorage and in the cookies...

This problem occurs only online, when I'm on localhost everything is working. When the user is loggin in with email everything is working. I noticed that the token is persisting in the url when I'm on local, but it flashes then diasapear when I'm online.

Thanks to anyone who could help.

Upvotes: 1

Views: 2303

Answers (2)

user9199922
user9199922

Reputation: 1

This is the current solution for client components, which I found to work (no need for useEffect):

  const supabase = createClientComponentClient<Database>({});
  const [session, setSession] = useState<Session | null>(null);

  supabase.auth.onAuthStateChange((event, session) => {
  if (event == "SIGNED_IN") setSession(session);
  });

Upvotes: 0

ekno
ekno

Reputation: 69

I found the solution so I will write it here for people with the same problem.

Since the signIn methods returns nothing with third auth, you should use onAuthStateChange to get the user's info.

useEffect(() => {
        supabase.auth.onAuthStateChange(() => {
            setUser(supabase.auth.user())
        })
    }, [])

Upvotes: 0

Related Questions