When working with web applications, it is essential to understand how data is stored in the browser. Two commonly used storage mechanisms are localStorage and sessionStorage. While both store data as key-value pairs, they differ in lifespan and scope:
- localStorage: Stores data indefinitely, even after the browser is closed and reopened.
- sessionStorage: Stores data only for the duration of a page session. Once the tab or browser is closed, the data is lost.
A common challenge arises when storing authentication tokens in sessionStorage. Since session data is not shared between tabs and is cleared when a tab is closed, a user opening a new tab must log in again. This can create a frustrating experience, especially in applications where multiple tabs are commonly used.
How to Share the Authentication Token Between Tabs
To maintain authentication across tabs while keeping session-based storage, we can use the BroadcastChannel API. This API enables communication between different tabs or windows of the same origin by broadcasting messages.
Step 1: Setting Up the Broadcast Channel
We first create a BroadcastChannel instance that all tabs can use to send and receive authentication-related messages.
const authChannel = new BroadcastChannel("auth_channel");
authChannel.postMessage({ message: "NEW_TAB" });
In this example, we create a new BroadcastChannel named auth_channel
. When a new tab is opened, it sends a “NEW_TAB” message to notify other tabs.
Step 2: Managing the Authentication Token
To manage the authentication token efficiently, we define utility functions to set, retrieve, and remove the token from sessionStorage.
function setUserToken(token: string) {
window.sessionStorage.setItem("token", token);
}
function getUserToken(): string {
return window.sessionStorage.getItem("token") || "";
}
function removeUserToken() {
window.sessionStorage.removeItem("token");
}
Step 3: Handling Broadcast Messages
We listen for messages on the auth_channel and update authentication states accordingly.
authChannel.addEventListener("message", (e: MessageEvent) => {
const token = getUserToken();
switch (e.data.message) {
case "NEW_TAB":
if (token) {
authChannel.postMessage({ message: "AUTH_TOKEN", token });
}
break;
case "AUTH_TOKEN":
if (!token) {
setUserToken(e.data.token);
}
break;
case "SIGN_OUT":
removeUserToken();
}
});
Explanation:
- NEW_TAB: When a new tab opens, it sends a request. If an existing tab has a token, it responds by sending an AUTH_TOKEN message.
- AUTH_TOKEN: When a tab receives an authentication token, it stores it in sessionStorage.
- SIGN_OUT: When a user logs out, all tabs remove the authentication token to ensure security.
Conclusion
Using the BroadcastChannel API, we can efficiently share authentication tokens between browser tabs while still leveraging sessionStorage. This approach ensures that users remain authenticated across multiple tabs while maintaining security and session-based data handling. This method is particularly useful for applications that require real-time collaboration, such as chat applications, dashboards, or productivity tools.