How to Logout of Multiple Tabs | React Web App
Tags: react, tutorial, broadcastchannel, beginners
Published: 2022-05-20 12:01:46

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](https://github.com/de-mawo/react-dash-v1)** and download or clone the starter project into a directory of your choice on your local machine.

![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/p221t5yhidmaan5hk331.PNG)
After cloning the starter project, you should have a structure as below. Run **npm install** to install the dependencies.

![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/sttji9an3sctx9lcp3wz.PNG)

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](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/uofrtt0a02z4sapuaj3q.PNG)

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](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/ku9xlzh1cwpxigcdzvia.PNG)
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();
       
        
    }
}
```

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;

```
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](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/6hbmhtcumt1tp781uvn6.PNG)

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