Clear User Session In Flutter Web App In All Open Browser Tabs

In this post, we will learn how to clear user session in Flutter web app from in all open browser tabs. We will make use of window storage event listener for this purpose.

Introduction

Generally, users have a tendency to open any website in multiple tabs in their browser. Flutter web app can be loaded in multiple tabs without any problems. However, if user was logged in on multiple tabs and then logs out from one of those tabs, how can you update the app session in all the other open tabs? How to log out the user from all open tabs when user logs out from one tab?

So, basically, we want to redirect users to the login screen of the Flutter web app in all open active tabs.

Solution

For this purpose, we will make use of the StorageEvent property of a browser local storage.

Making Use Of Storage Event Listener

We can add an storage event listener to the browser window using some javascript as below:

window.addEventListener('storage', function (event) {
        
    }, false);

This event listener listens to events related to local storage of the browser. Keep in mind that this listener can listen to events happening in other tabs but not on the same tab. So, if your Flutter web app is running on a single tab, this event listener will never receive any notifications!

Identify User Session Key In Local Storage

Let’s configure to clear user session in Flutter web app by adding event listener for storage.

First, you need to identify what is the key value of the local storage item which is storing the user session. You can inspect using browser developer tools for this.

Inspecting Flutter Web Local Storage

Next, use the key flutter.userToken (your key could be different :P) to check if the value was updated.

Add Script To Clear User Session In Flutter Web App

Create a script file app_script.js inside your Flutter web project.

Inside this file, we add a local storage event listener like below.

function addWindowEventListeners() {
    //listen to log out state from multiple tabs
    window.addEventListener('storage', function (event) {
        if (event.key == "flutter.userToken") {
            if(event.newValue.length < 3) {
               this.window.location.reload();
            }
        }
    }, false);
}

addWindowEventListeners();

Here, we are checking if the session key matches our user session token holder key. If the newValue is cleared, we ask the browser window to reload.

Finally, call this script by adding the script file inside the index.html head tag.

<script src="app_script.js" defer></script>