NuxtN
Nuxt6mo ago
16 replies
lazygopher

Nuxt auth middleware with better-auth library

I'm using better-auth for authentication. I'm using a NuxtRouteMiddleware on protected pages so unauthenticated users are redirected to login. This is my middleware
# middleware/auth.ts
export default defineNuxtRouteMiddleware(async (to, _from) => {
    const { user } = useAuthStore()

    // redirect the user to the login screen if they're not authenticated
    if (!user) {
        return navigateTo("/login")
    }
})


When user navigates through the app, it works as expected. When user are loading a protected page as first page or reloading it, they're always redirected to /login.
I initialize my authStore in my default layout
const authStore = useAuthStore()
await authStore.init()


How do I fix it so the middleware gets executed after the store is fully initialized?
Was this page helpful?