Reputation: 1
I am using NextAuth.js for authentication in my Next.js application. Everything works fine when logging in—if I log in on one tab, opening the same project in another tab automatically shows the user as logged in. However, I am facing an issue with logout across multiple tabs.
Logging out from one tab does not clear the session in other open tabs of the same browser.
If I manually refresh the other tabs after logging out, they still appear logged
When logging in, opening a new tab automatically keeps the user logged in (which is expected).
Logout works perfectly fine in a single tab
Used signOut()
from next-auth/react
to log out.
const handleClose = async (type = '') => {
setAnchorEl(null);
if (type === 'logout') {
localStorage.setItem("nextauth_logout", Date.now().toString());
await signOut({ redirect: false });
}
};
I created a custom hook to listen for logout changes in other tab, even this got triggered the session will be automatically updated in the tab which I used to logged out and user will remain as logged in itself
const useMultiTabLogout = () => {
useEffect(() => {
const handleStorageChange = (event) => {
if (event.key === "nextauth_logout" && event.newValue) {
signOut();
}
};
window.addEventListener("storage", handleStorageChange);
return () => window.removeEventListener("storage", handleStorageChange);
}, []);
};
Upvotes: 0
Views: 12