Broadcasting Across Tabs with Local Storage and Storage Event

So, recently I stumbled upon an interesting issue where a user kept encountering the HTTP Error 403 — Forbidden while making API calls. I digged in and found that user was logged in on two different tabs simultaneously. Later on, they logged out from one tab but continued using the app on the other without refreshing the page, causing these persistent 403 errors.

What does this mean? Even though the user was logged in, they were unable to perform actions that required authorization. The fix was straightforward – whenever a user logs out from any tab, they should automatically get logged out from all other tabs where they are logged in. The initial idea that popped into my mind was using WebSockets, but I wanted a simpler approach to address this. On exploring further, I came across the wonders of local storage and how easily we can broadcast messages across tabs using the storage event.

What is local storage?

It allows websites to store key-value pairs locally on a user's device, similar to how you might remember your friend's name along with their phone number. The information stored in local storage remains even when the user closes the browser or navigates away from the website.

What is storage event?

It's an event that is triggered in a web page when there are changes made to the data stored in the web storage (such as localStorage or sessionStorage). This event is broadcasted to all other windows or tabs that are open to the same origin (i.e., the same domain, protocol, and port). It allows different parts of a web application or different browser instances to be aware of changes in the shared web storage.

Let's understand the working behind the magic with an example:

Suppose you have two tabs open in your browser, both showing the same website. In one tab, you change a user setting, and the website updates the value in localStorage. The storage event is triggered, notifying the other tab about the change. The second tab can then react to this event and update its content based on the modified data in localStorage, creating a synchronized experience across multiple tabs or windows.

Here's a working example! Open the page in two different tabs, then check out the Dev tools -> Application -> local storage. Now, brace yourself for the magic – click on the "Logout" button in one tab. Visit the other tab, and guess what? It logs out from there too. Wooooah, the magic worked! Haha, isn't that cool? 😄

CodeSandBox Link

And that's a wrap. Stay tuned for more exciting content in the next blog! 😄