Skip to content

Session fetched after middleware execution when SSR is disabled #135

@mitto98

Description

@mitto98

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.

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions