KindeK
Kinde12mo ago
17 replies
Mert Efe Cerit

Nuxt + Kinde Module Logic Problems

Hello,
We are using the Kinde Nuxt module for an application on Nuxt, and we are facing some issues. Let me first explain what we are trying to achieve.

Goal:
All application routes should be protected, and the user should be logged out and redirected to the login page based on token expiration.

Problem:
After the token expires, the user is redirected to the login page, but without filling in any inputs, the user is automatically logged in again and returned to the relevant page. What should happen instead is that when the token expires or a 401 is returned, the user should be redirected to the login page and required to fill in the relevant fields.

Action Taken:
I wanted to write a global middleware to check whether the user is logged in whenever a page is refreshed or when route changes occur, as it didn’t make sense to use definePageMeta inside every single page.

Problem Encountered with the Action Taken:
When a force refresh occurs, the Kinde Nuxt module only runs once on the SSR side and doesn’t work for every route change. To address this, we used the useAuth hook, but even then, it showed us as still logged in even after the token had expired, so we couldn’t use it.
The useKindeClient works on the SSR side but returns null on the client side. The useAuth wasn’t functioning correctly either.

Code for my middleware:

export default defineNuxtRouteMiddleware(async () => {
    const client = useKindeClient();
    if (client) {
        const isAuth = await client.isAuthenticated();
        if (isAuth) {
            const token = await client.getToken();
            if (process.env.NODE_ENV === 'development') {
                console.log('token', token)
                console.log('refreshTokens', await client.refreshTokens());
            }
            useState('token', () => token);
            return true;
        }else{
            useState('token', () => null);
            return navigateTo('/api/login', {external:true});
        }
    }
})
Was this page helpful?