How to keep store in sync with supabase's multitab session?
A logged in user's data is stored in store:
When a user signs out within the app, store is reset to default values. So far it works as expected.
However, if the logged in user is viewing the app on multiple tabs and logs out on one of them then rest of the tabs remain active because store is not synced between tabs.
I asked this on Supabase's forum and got the following response:
Me: I have noticed that when a session is active on one tab, it doesn't refresh on other tabs. After some searching, I came across this PR: https://github.com/supabase/gotrue-js/pull/566 It mentions that storageKey should be used for the channel's name. What is- and where is the storageKey obtained from?
Moderator: storageKey is used to separate the supabase clients so they don't interact. If you don't use it in createClient options then all of the tabs should be in sync.
Me: Tabs are in sync how? For example, I store the logged in user's data in a redux- like store. Should I subscribe to some type of auth event in order to know if a user is logged out?
Moderator: Supabase-js is set up to keep the local storage in sync for multiple tabs. I don't know what redux-like storage is in the context here. I don't think you said what your environment is. But on simple javascript browser Supabase uses local storage to keep the tabs in sync (or it is supposed to). If you are doing something with sessions on your own then you would need to describe that method and see if someone has ideas.I'm not quite sure how to proceed here. I inspected the local-storage and found that an access key is stored there:
sb-[app id]-auth-token: { access_token: ... }
Is there a way to listen to this change?
How can I keep the tabs in sync, with store in mind?2 Replies
I have tried the following after some more googling:
Since local storage is kept in sync for all tabs, i thought perhaps there's away to listen to such event and came across
window.onstorage
.
Then tried the following, and call the function responsible for loading user's session info:
This seems to be working and keeps multiple tabs in sync, whether user logs in or out.
If there is a cleaner/better way, please let me know Listening to storage seems sensible to me. Another option would be to explicitly communicate between your tabs using the broadcast api: https://developer.mozilla.org/en-US/docs/Web/API/Broadcast_Channel_API
MDN Web Docs
Broadcast Channel API - Web APIs | MDN
The Broadcast Channel API allows basic communication between browsing contexts (that is, windows, tabs, frames, or iframes) and workers on the same origin.