Next.js Discord

Discord Forum

Router.refresh doesn't work well if my website is open in multiple tabs

Unanswered
Schweizerischer Niederlaufhund posted this in #help-forum
Open in Discord
Schweizerischer NiederlaufhundOP
How would a run router.refresh function to make sure my website content is updated across all tabs or devices that are using my application?

I have a button which updates a cookie and on another page I can see the cookie update being reflected. However if I have two tabs open and I re update the cookie on one tab then the 2nd tab would be out of sync since router.refresh would only clear the cache in current tab.

Very weird behaviour. Any work arounds?

21 Replies

Barbary Lion
Next.js typically refreshes only the current tab or window where the function is called.
Use Service Workers for communicate with other tab, or socket io.
I think there's a JS event that is triggered when the tab is active again
you could listen to it and check for cookies update there
however, this behaviour should probably be built-in in Next, I advise looking at github issues or opening one
Barbary Lion
One way to synchronize updates between tabs is to use the Web Storage API along with the storage event.
When you update a cookie in one tab, you can trigger an update in the other tab by storing the updated value in localStorage or sessionStorage.
The storage event is fired in other tabs when changes are made to localStorage or sessionStorage.
You can listen for this event and react to changes.
Asian black bear
@Schweizerischer Niederlaufhund take a look at this article. It is about syncing state between tabs.
https://oakhtar147.medium.com/sync-local-storage-state-across-tabs-in-react-using-usesyncexternalstore-613d2c22819e
Do you set the cookie in JS or via a Set-Cookie header btw? and how do you read it then?
I feel like if you use pure JS it could be up to you to handle the synchronization, by detecting when user access a tab and reading an up to date value
but if you use next features like "cookies()" server-side it should be up to Next to detect that
those articles show how to subscribe to local storage changes
but you can achieve the same for cookies directly by watching for relevant events
check how SWR can automatically refetch data when a component is focues
focused
the idea is to update cookies using some custom logic
so since you control the update, you can also detect those updates and have the component that consumes the cookie to reload