atinux / nuxt-auth-utils

Minimal Auth module for Nuxt 3.
MIT License
818 stars 79 forks source link

Session fetched after middleware execution when SSR is disabled #135

Closed mitto98 closed 2 weeks ago

mitto98 commented 1 month ago

Ciao,

When ssr is disabled the user session data remains empty during the initial page load if the session is retrieved using the useUserSession composable in the middleware. If I add plugin that call the fetch function returned by the useUserSession composable the session, the session is correctly populated by the time the middleware runs.

This is the middleware/auth.global.ts file

export default defineNuxtRouteMiddleware(() => {
  const { loggedIn, user } = useUserSession();

  console.log("User is logged in", loggedIn.value);

  if (!loggedIn.value) {
    return navigateTo("/auth/keycloak", { external: true });
  }
});

This is the plugins/01.loadsession.ts file that fixed my issue:

export default defineNuxtPlugin(async (nuxtApp) => {
  // nuxtApp.hook("app:created", async () => {
  await useUserSession().fetch();
  // });
});

I've tried to hook the session fetch to app:created, but it is still executing it before the middleware is executed. If you have a better solution I can test it and do a PR, I'm not sure if my current solution will work in others scenarios.

Steps to Reproduce:

samuelbelo commented 4 weeks ago

I am facing the same issue. Besides my application does behave correctly in development, it does not retrieve the session in production. I am using azure static web app.

atinux commented 2 weeks ago

Thank you for reporting and investigating!

I was focused on the hydration mismatch and forgot that we need to fetch without waiting for CSR.

You can use the v0.3.5