Logging out of all tabs when logout occurs on 1 tab
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// Your main component. | |
const MyComponentWrapper = (props) => { | |
// Watch changes to local storage, and if we logout in 1 tab, | |
// logout in every other tab. | |
const syncLogout = (event: StorageEvent): void => { | |
if (event.key === 'logout') { | |
Router.push('/login'); | |
} | |
}; | |
useEffect(() => { | |
window.addEventListener('storage', syncLogout); | |
return () => { | |
window.removeEventListener('storage', syncLogout); | |
window.localStorage.removeItem('logout'); | |
}; | |
}, []); | |
return (<div>your component stuff</div>); | |
}; | |
// Somewhere else, as a handler for your `/logout` route. | |
const logout = (): void => { | |
// 1. Hit your own backend /logout API so you can invalidate the current token. | |
// 2. Delete current user's token. | |
// 3. Now set the 'logout' key in local storage that will be picked up by the storage event listener. | |
window.localStorage.setItem('logout', Date.now().toString()); | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment