wobsoriano / vue-clerk

Community Clerk Vue SDK.
https://vue-clerk.com
MIT License
144 stars 13 forks source link

Inconsistent behavior in auth middleware in Nuxt #13

Closed stephenhebert closed 6 months ago

stephenhebert commented 9 months ago

Thank you for this contribution to the JS / Vue community!

I'm observing some strange behavior and wondering if it might be an issue. It could be that it's working properly and I just don't understand the intended function.

It seems like the first time I load vue-clerk / useClerk after warming up my Nuxt dev server, it functions as expected -- on the client side, clerk.loaded is true and clerk.user is defined. However, with every subsequent page load, clerk.loaded will be false and clerk.user will be undefined. Is this expected?

I'm seeing this behavior in the https://github.com/wobsoriano/nuxt-clerk-template repo. My only changes are to add my keys to .env and to add some logs to console in the middleware/auth.ts:

  // On client, check if clerk is loaded and log to console
  if (process.client) {
    if (clerk.loaded)
      console.log('Clerk loaded!');
    else
      console.log('Clerk not loaded!');
    console.log('Clerk user:', clerk.user)
  }
stephenhebert commented 9 months ago

Ok. I think I may have found a workaround for my use case.

import { useClerk, useClerkProvide } from 'vue-clerk';
import { until } from '@vueuse/core';

export default defineNuxtRouteMiddleware(async() => {
  const clerk = useClerk();
  const { isClerkLoaded } = useClerkProvide();

  // On client, wait for clerk to be loaded and 
  // redirect to sign-in if user is not logged in
  if (process.client) {
    await until(isClerkLoaded).toBe(true);
    if (!clerk.user?.id) return navigateTo('/sign-in');
  }
});