auth-js
auth-js copied to clipboard
Updating user metadata in onAuthStateChange causes infinite loop of events
Bug report
Describe the bug
Updating user metadata in onAuthStateChange causes infinite loop of SIGNED_IN and USER_UPDATED events causing my app to crash. I think this happens when multiple tabs are open with the app. When metadata is updated in the focused tab, it triggers a USER_UPDATED event which seems to cause multiple SIGNED_IN events in the tabs that aren't focused
To Reproduce
Run the following code in SessionProvider.tsx
useEffect(() => {
setSession(sb.auth.session())
const { data: authListener } = sb.auth.onAuthStateChange(async (event, session) => {
setSession(session)
// Post session to backend to store login cookies
await fetch("/api/auth", {
method: "POST",
headers: new Headers({ "Content-Type": "application/json", Accept: "application/json" }),
credentials: "same-origin",
body: JSON.stringify({ event, session }),
})
if (session?.user && event === "SIGNED_IN") {
const currProperties = session.user.user_metadata ?? {}
await sb.auth.update({
data: {
last_sign_in_at: new Date().toISOString(),
registered_at: currProperties?.registered_at ?? new Date().toISOString()
}
})
}
})
return () => {
authListener?.unsubscribe()
}
}, [])
Expected behavior
The SIGNED_IN event only fires once
Screenshots
System information
- OS: macOS
- Version of supabase-js: 1.30.0
- Version of Node.js: 16.14.1
Additional context
Add any other context about the problem here.
Seeing the same problem in a React app when using a separate metadata table in the public schema to store information about the user as suggested here. Any updates on this?
Was able to repro this issue with multiple tabs, looking for a solution
The client library is not able to do anything about this. Please make sure you structure your code to avoid this endless loop.