fix: Prevent token race conditions by pre-saving access/refresh tokens to localStorage before NextAuth signIn and refining logout token clearing.

This commit is contained in:
pradeepkumar
2026-03-16 13:25:32 +05:30
parent 63ad223c4c
commit 1e9262edfa
4 changed files with 26 additions and 9 deletions

View File

@@ -56,6 +56,13 @@ export default function LoginPage() {
return;
}
// Save tokens to localStorage BEFORE signIn to prevent race condition
// (dashboard components may call API before TokenSync has synced from session)
if (validateData.data?.accessToken) {
localStorage.setItem('accessToken', validateData.data.accessToken);
localStorage.setItem('refreshToken', validateData.data.refreshToken);
}
// If validation passed, use NextAuth to create session
const result = await signIn('credentials', {
email,
@@ -66,6 +73,9 @@ export default function LoginPage() {
setLoading(false);
if (result?.error) {
// Login failed - clear the tokens we just saved
localStorage.removeItem('accessToken');
localStorage.removeItem('refreshToken');
setError('Login failed. Please try again.');
} else {
router.push('/');

View File

@@ -102,8 +102,11 @@ function VerifyTwoFactorContent() {
});
}
// Save tokens to localStorage BEFORE signIn to prevent race condition
localStorage.setItem('accessToken', response.data.accessToken);
localStorage.setItem('refreshToken', response.data.refreshToken);
// Now sign in with NextAuth using the tokens we received
// We need to call the NextAuth credentials provider with the tokens
const result = await signIn('credentials', {
email: userEmail,
accessToken: response.data.accessToken,
@@ -112,6 +115,8 @@ function VerifyTwoFactorContent() {
});
if (result?.error) {
localStorage.removeItem('accessToken');
localStorage.removeItem('refreshToken');
setError('Failed to complete login. Please try again.');
setLoading(false);
} else {

View File

@@ -23,11 +23,8 @@ export default function LogoutPage() {
// Delete httpOnly cookies via server action (Next.js cookies() API)
await clearAuthCookies();
setTimeout(() => {
// Redirect to login
window.location.reload();
window.location.href = '/login';
}, 3000);
// Redirect to login immediately
window.location.href = '/login';
};
performLogout().catch(() => {