onAuthStateChange SIGNED_IN event not firing after OAuth

I have a onAuthStateChange subscription in a useEffect hook of my Remix.run app root component. I recently updated my project to use Supabase v2 and now I'm experiencing weird behavior with OAuth signin/signup. Sometimes the SIGNED_IN event is fired almost immediately and everything seems normal but sometimes I get returned to the correct route but nothing happens. Then I might visit another browser tab and when I open my Remix app tab again without any other user action I get signed in. It seems to me like the event (SIGNED_IN) is fired with inconsistent delay. Any help with this?

Here's the hook I place in the root component.

export function useAuthStateChangeSubscription() {
  const fetcher = useFetcher()
  const [searchParams] = useSearchParams()
  const redirectTo = searchParams.get('redirectTo') ?? ROUTE_HOME

  useEffect(() => {
    const {
      data: { subscription: listener },
    } = supabase.auth.onAuthStateChange((event, session) => {
      console.log(event)
      if (event === 'SIGNED_IN') {
        const accessToken = session?.access_token
        const refreshToken = session?.refresh_token

        if (!accessToken) return

        const formData = new FormData()

        formData.append('accessToken', accessToken)
        formData.append('refreshToken', refreshToken || '')
        formData.append('redirectTo', redirectTo)

        fetcher.submit(formData, {
          method: 'post',
          action: '/api/auth/login',
          replace: true,
        })
      }
      if (event === 'SIGNED_OUT') {
        fetcher.submit(null, {
          method: 'post',
          action: '/api/auth/logout',
          replace: true,
        })
      }
    })

    return () => {
      listener?.unsubscribe()
    }
  }, [fetcher, redirectTo])
}
Was this page helpful?