As recommended in, I have set up nav guards for my nuxt app in:
/src
/middleware
/navGuard.global.ts
This runs on every route change. Here I check for a logged in user in my data store, attempt login, and redirect if neccessary
export default async (to:Route, from:Route) => {
const appStore = useAppStore()
const auth = useAuthStore()
appStore.page_loading = true;
if (!import.meta.client) return;
if (to.name === 'auth' && !auth.doAuthRedirect) {
console.log('Navigating to auth')
sessionStorage.setItem('lastNavigation', '/auth')
}
if (to.name !== 'auth' && !auth.userId) {
console.log('Looking for user auth in storage')
await auth.setUser()
if (!auth.userId) {
console.log('User not found redirect to auth')
sessionStorage.setItem('lastNavigation', to.path)
auth.doAuthRedirect = true;
return navigateTo('auth');
}
}
console.log('Navigating to:', to.path)
auth.doAuthRedirect = false;
return
};
The problem here is that the reliance on the authStore
and loading user sessions from localStorage means that the serverside and the client side will always mismatch (obviously there will never be a localStorage cred found on the serverside).
What is the theory here? I’m sure I must be doing it fundamentally wrong.
Before someone says it – changing the whole app to CSR is not a solution. The whole point of NUXT is to get as much SSR as possible.
7