Repository navigation
Which API to use for a navigation guard? #5133
|
I'm using nhost with vue3 + vue-router, with the following navigation guard: router.beforeEach((to) => {
const session = nhost.getUserSession()
if (to.meta.requiresAuth === false || (isAuthenticated && session?.user?.id)) {
return true
} else {
return '/login'
}
})This works most of the time, except that if I leave the page for a while and then navigate to another page, I get a graphql error saying the JWT has expired. If I refresh the page, it loads fine without redirecting to the login page. Which API should I be using instead? I don't want to execute |
Replies: 1 comment 2 replies
|
Use router.beforeEach(async (to) => {
if (to.meta.requiresAuth === false) return true
const session = await nhost.refreshSession() // refreshes only when close to expiry
return session?.user?.id ? true : '/login'
})So it isn't a refresh on every page load: in normal use it's a local check, and a real refresh happens only when the token is about to expire. On the GraphQL error: clients created with |
getUserSession()only reads the stored session (it'sthis.sessionStorage.get()innhost.ts). It never checks expiry or refreshes, so after the page has been idle the guard lets you through with an expired access token.Use
refreshSession()instead. It's built for this: it only calls the auth server when the access token expires withinmarginSeconds(default 60). Otherwise it returns the stored session without a network request, and it returnsnullif there's no session or the refresh fails: