nuxt-auth-utils
nuxt-auth-utils copied to clipboard
Session fetched after middleware execution when SSR is disabled
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.