I have a problem in my Nuxt3-based website where when I log in to an user account, then log out and log in to another user account, the generated JWT isn’t taken in account by my browser.
What I mean is, I store it in localStorage at login, it works fine, I can do my CRUD as expected.
But when I log out and log in to another test account, my web browsers (Chrome, Firefox, Edge) don’t seem to update the JWT in their cache. So when I update something in my database, my updated_by column is filled with the id of the previous account logged in, not the current one. To solve this issue, I have to manually clear my browser’s cache.
Here is the login and logout logic I’m using.
// Login function
export async function login(credentials) {
try {
const runtimeConfig = useRuntimeConfig()
const response = await fetch(`${runtimeConfig.public.auth}/login`, {
method: 'POST',
body: JSON.stringify(credentials),
headers: {
'Content-Type': 'application/json',
},
})
if (response.status === 401) {
throw 'Invalid credentials'
}
const data = await response.json()
if (data.token) {
localStorage.setItem('jwt', data.token)
await navigateTo('/dashboard')
}
} catch (error) {
throw error
}
}
// Logout function
export async function logout() {
try {
await localStorage.removeItem('jwt')
} catch (error) {
console.error(error)
}
}
And the block where the logout function is being called in a component:
async function logOut() {
await logout()
await navigateTo('/login')
}
<button @click="logOut()" class="menu_item">Disconnect</button>
I tried adding a localStorage.clear(), but I didn’t try to clear the cache into the function, I’ve read that this is not a good practice.
What I expect to do is to not having to manually clear my browser’s cache every time i switch users account for it to aknowledge that the jwt data has changed.
VincentFourcroy is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.