DEV Community

Cover image for How to Logout of Multiple Tabs | React Web App
Prince De Mawo
Prince De Mawo

Posted on

How to Logout of Multiple Tabs | React Web App

In a real world scenario , you would want users who visit your site to have a great user experience . Security , on the other hand, is of prime importance to users and a secure web app improves user-trust which has a positive effect towards “good business”. A common use behavior of users on websites that require authentication, is opening of multiple tabs as they browse or make transactions. In such a situation, you would like users to be able to sign in and sign out successfully without worrying about whether they are logged out of all tabs or not.

One of the ways to improve user experience in such a scenario is to make sure that when a user signs out of any tab of your website ,they are logged out of all other tabs once. Thereafter, sensitive data should be removed from the screen by redirecting the user to a public page and possibly clearing JWT tokens from local Storage.

I have implemented a simple beginner friendly example of this kind of feature. Let us go ahead and see how I did it. Go on this link and download or clone the starter project into a directory of your choice on your local machine.

Image description
After cloning the starter project, you should have a structure as below. Run npm install to install the dependencies.

Image description

Go ahead in your terminal a install this dependency npm i broadcast-channel
To learn more about Broadcast Channel API , I encourage you to go on the following links:
[https://developer.mozilla.org/en-US/docs/Web/API/Broadcast_Channel_API]
[https://github.com/pubkey/broadcast-channel]

Once you are done installing the broadcast-channel dependency, run npm start in your terminal to start your application. Your application should now be running on port 3000 or any port you may have configured.

Image description

Go ahead and click the sign in button and you will directed to the dashboard. As a test, duplicate the current tab into 3 or for 4 tabs then go back to the first tab and click sign out.

Image description
As you can see, you are directed to the sign in page on this first tab but the other tabs are still logged in (not good user experience right?). To solve this issue , we will add a few lines of code into the auth.js file inside the auth folder.

Replace the existing code in your auth.js file with the below code and save;

import history from 'history/browser'
import { BroadcastChannel } from 'broadcast-channel';

const logoutChannel = new BroadcastChannel('logout');

export const login = () => {
    localStorage.setItem("token", "this_is_a_demo_token")
    history.push('/app/dashboard')
}

export const checkToken = () => {
    const token = localStorage.getItem("token", 'this_is_a_demo_token' )
    if(!token) return alert('You are not logged in')
    return token

}

export const logout = () => {
    logoutChannel.postMessage("Logout")
    localStorage.removeItem("token", 'this_is_a_demo_token' )
    window.location.href = window.location.origin + "/";

}

export const logoutAllTabs = () => {
    logoutChannel.onmessage = () => {
        logout();
        logoutChannel.close();


    }
}
Enter fullscreen mode Exit fullscreen mode

So what we did here was to import the broadcast channel module and we created an instance , logoutChannel, and it "logout". Whenever we sign out , a message "Logout" is sent to other tabs on the same host and port ( host is your local machine and port 3000).
Furthermore , replace the existing code in your App.js file with the code below and save;

import React, { useEffect } from "react";
import { logoutAllTabs } from "./auth/auth";
import Router from "./routes";


function App() {
useEffect(() => {
 logoutAllTabs()
}, [])


  return (
    <>

     <Router/>

    </>
  );
}

export default App;

Enter fullscreen mode Exit fullscreen mode

Now lets start again, close all the other tabs and leave one on the sign in page, click sign in and get directed to the dashboard. Duplicate the current tab into 3 more tabs. At this stage if you sign out from one of the pages, all other open tabs should be logged out as well at the same time.

Image description

That's all folks!. You are now able to implement this in your own React application as well. If you find the tutorial useful please kindly give me a star on GitHub or follow me on twitter https://twitter.com/de_mawo

Top comments (0)