atinux / nuxt-auth-utils

Add Authentication to Nuxt applications with secured & sealed cookies sessions.
MIT License
974 stars 91 forks source link

Session fetched after middleware execution when SSR is disabled #135

Closed mitto98 closed 2 months ago

mitto98 commented 3 months 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 3 months 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 months 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