Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Token mismatch after refresh (handling onTokenChanged) #2

Open
pk992 opened this issue Jun 27, 2022 · 0 comments
Open

Token mismatch after refresh (handling onTokenChanged) #2

pk992 opened this issue Jun 27, 2022 · 0 comments
Assignees
Labels
bug Something isn't working

Comments

@pk992
Copy link

pk992 commented Jun 27, 2022

The bug
If the access token get's refreshed by the Nhost client, a hydration mismatch happens (if the access token is displayed) and further requests like page reloads fail, leading to log-out.

nhostClientRefresh
accessKeyMismatch

To Reproduce
Start the playground, login and wait until the token get's refreshed. Then reload or change the page to see the auth fail.

A possible solution
Adding the following code prevents the bug, but also adds an unecassary, second POST to /api/_nhost/session on each page reload.

plugins/nhost.client.ts: adding onTokenChanged in mounted hook

// Once Nuxt app is mounted
nuxtApp.hooks.hook('app:mounted', () => {
    // Listen to Nhost auth changes
    client.auth.onAuthStateChanged(async (event, session) => {
        await setServerSession(event, session)
        const nhostUser = client.auth.getUser()
        user.value = nhostUser
    })

    // Listen to Nhost token changes
    client.auth.onTokenChanged(async (session) => {
        await setServerSession('TOKEN_CHANGED', session)
        const nhostUser = client.auth.getUser()
        user.value = nhostUser
    })
})

server/api/_nhost/session.ts: adding TOKEN_CHANGED handler

if (signEvent === 'TOKEN_CHANGED') {
    if (!session) {
        throw new Error('Auth session missing!')
    }
    setCookie(
        event,
        `${cookieOptions.name}-access-token`,
        session.refreshToken, {
            domain: cookieOptions.domain,
            maxAge: cookieOptions.lifetime ?? 0,
            path: cookieOptions.path,
            sameSite: cookieOptions.sameSite
        }
    )
}

Right now, I can't think of a clean way to prevent the duplicated POST to /api/_nhost/session.

@xlanex6 xlanex6 self-assigned this Jun 28, 2022
@xlanex6 xlanex6 added the bug Something isn't working label Jun 28, 2022
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
bug Something isn't working
Projects
None yet
Development

No branches or pull requests

2 participants