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

Session fetched after middleware execution when SSR is disabled #135

Closed
mitto98 opened this issue Aug 8, 2024 · 2 comments · Fixed by #151
Closed

Session fetched after middleware execution when SSR is disabled #135

mitto98 opened this issue Aug 8, 2024 · 2 comments · Fixed by #151

Comments

@mitto98
Copy link

mitto98 commented Aug 8, 2024

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:

  • Ensure that a session is present and ssr is disabled
  • Add a Nuxt middleware that calls the useUserSession composable and log the returned session and loggedIn value.
  • Reload the app, session is empty and loggedIn is false.
  • Add a plugin that fetches the session immediatelly.
  • Reload the app and, the session is now correctly populated and loggedIn is trye.
@samuelbelo
Copy link

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
Copy link
Owner

atinux commented Aug 28, 2024

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

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging a pull request may close this issue.

3 participants