Course contentsShow
← Web Development
Lesson 1614 of 2,98229. Web Authentication PatternsFree lesson

Refresh Tokens with Multiple Tabs

Handle token synchronization across browser tabs using storage events and shared refresh logic.

Refresh Tokens with Multiple Tabs

You'll learn how to keep authentication synchronized across multiple browser tabs so all tabs stay logged in together.


When a user opens your app in multiple tabs, each JavaScript context runs independently. If one tab silently refreshes the access token, the other tabs don't automatically know about it—they're still using the old, expired token. Even worse, multiple tabs might try to refresh simultaneously, creating race conditions you learned about in lesson 1612.

The Storage Event Solution

The browser's storage event fires whenever localStorage or sessionStorage changes in a different tab. This is your synchronization mechanism:

// Tab 1 updates the token
localStorage.setItem('accessToken', newToken);

// Tab 2 listens for changes
window.addEventListener('storage', (event) => {
  if (event.key === 'accessToken') {
    console.log('Token updated in another tab:', event.newValue);
    // Update your in-memory token or auth state
  }
});

Centralized Refresh Logic

Create a single refresh coordinator using a shared flag in storage:

async function refreshTokenAcrossTabs() {
  const refreshing = localStorage.getItem('tokenRefreshing');
  
  if (refreshing) {
    // Another tab is handling it, wait for the result
    return waitForStorageUpdate('accessToken');
  }
  
  localStorage.setItem('tokenRefreshing', 'true');
  try {
    const newToken = await callRefreshEndpoint();
    localStorage.setItem('accessToken', newToken); // Triggers storage event
  } finally {
    localStorage.removeItem('tokenRefreshing');
  }
}

Only one tab actually makes the refresh request; others listen for the updated token via the storage event.


Key Takeaway: Use the browser's storage event to broadcast token updates between tabs, and coordinate refresh attempts with shared flags to prevent race conditions and keep all tabs authenticated together.