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
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
How do I fix it so the middleware gets executed after the store is fully initialized?
10 Replies
Hi @lazygopher. I'm kapa.ai, your friendly support bot. I will try to answer your question by searching through the knowledge base. :wave:
----------------------
Your issue is a common one in Nuxt apps: when a protected page is loaded directly (server-side or on reload), your middleware runs before your store (and thus authentication state) is fully initialized, so it always redirects to
Use the documented pattern to skip middleware execution until after hydration, so your store (and thus your auth state) is ready before checking authentication. This will prevent the unwanted redirect to
/login.
Key points from the knowledge sources:
- Middleware runs both on the server and client, and on initial page load it may execute before client-side stores or plugins are hydrated and ready. This can cause authentication checks to fail if the store isn't initialized yet, leading to unwanted redirects Docs: When Middleware Runs.
- To avoid this, you can skip middleware execution on the server, or on the initial client hydration, by checking import.meta.server, import.meta.client, and nuxtApp.isHydrating Docs: When Middleware Runs.
- Example from the docs:
This ensures your middleware only runs when the store is ready Docs: When Middleware Runs.
How to fix your middleware:
Update your auth.ts middleware to skip execution until the store is ready. For example:
This pattern ensures your authentication check only runs when the store is initialized, preventing unwanted redirects on first load or reload Docs: When Middleware Runs.
If you still need to run some logic on the server (e.g., SSR), you may need to ensure your store is initialized server-side as well, but for most client-side auth flows, the above approach is sufficient.
Summary:Use the documented pattern to skip middleware execution until after hydration, so your store (and thus your auth state) is ready before checking authentication. This will prevent the unwanted redirect to
/login on first load or reload.
----------------------
Note: you can ask me a follow up question by @ mentioning me again :speech_balloon:
----------------------<@693201794137981049> Kapa.ai is still learning and improving, please let me know how I did by reacting below.
@kapa.ai I still encounter issues when using authentication in middleware. How common and good practice is it to check auth on pages with onMounted?
Let me check the knowledge base for you again. One moment! :books:
----------------------
Checking authentication in
It is not common or recommended to check authentication in
onMounted on each page is not the recommended or common practice in Nuxt. The preferred and idiomatic way is to use Nuxt's route middleware system for authentication checks. Middleware is specifically designed to run before navigation to a route completes, allowing you to protect pages and redirect unauthenticated users before the page is rendered Docs: Protect App Routes Docs: Route Middleware.
Using onMounted for authentication checks can lead to a poor user experience, as the protected page may briefly render before the redirect occurs, causing a "flash" of protected content or a glitchy redirect. This is exactly the issue that middleware is designed to prevent.
If you are encountering issues with authentication in middleware (such as the store not being initialized), it's better to address those issues directly—such as ensuring your store is ready before the middleware runs—rather than moving the logic to onMounted, which is not best practice in Nuxt Docs: When Middleware Runs.
Summary:It is not common or recommended to check authentication in
onMounted on each page. Use Nuxt route middleware for this purpose, and resolve any initialization issues with your store or authentication logic within the middleware context.
----------------------
Note: you can ask me a follow up question by @ mentioning me again :speech_balloon:
----------------------<@693201794137981049> Kapa.ai is still learning and improving, please let me know how I did by reacting below.
@lazygopher you can call your init in a nuxt plugin
it will wil run once before the middleware, on app start
Hmm is that the way to do it? Where is the optimal place to init auth store?
@kapa.ai is it better to init the auth store in nuxt plugin? or should I init it in my middleware? Or any other best-practice for that works well with definePageMeta middlewares
Let me check the knowledge base for you again. One moment! :books:
----------------------
Based on the provided knowledge sources, the best practice is to initialize your auth store in a Nuxt plugin, not directly in your middleware or in each page. This ensures that your store is ready and populated before any middleware or page logic that depends on authentication runs.
A plugin is the right place to perform initialization logic that should happen before your app or middleware uses the store. For example, you can read cookies or session data and populate your store in a plugin, so that when your middleware runs, it can reliably check the authentication state Stack Overflow: Using cookies in Nuxt 3 APIs and Middlewares.
Here’s a summary of the recommended approach:
- Initialize the store in a plugin (e.g.,
plugins/init-auth.ts), where you can read cookies or other persistent data and set up your store state.
- Use middleware (with defineNuxtRouteMiddleware) to check authentication and redirect as needed, relying on the store already being initialized by the plugin.
- Avoid initializing the store in middleware itself, as middleware should only check state, not perform setup logic.
This pattern works well with definePageMeta middlewares, as the store will be ready before the middleware executes Stack Overflow: Using cookies in Nuxt 3 APIs and Middlewares.
In summary:Initialize your auth store in a Nuxt plugin, not in middleware. This ensures your authentication state is available for middleware checks and aligns with Nuxt best practices. ---------------------- Note: you can ask me a follow up question by @ mentioning me again :speech_balloon: ----------------------
<@693201794137981049> Kapa.ai is still learning and improving, please let me know how I did by reacting below.
@Cake thanks for the suggestion. So I simply place a plugin file and can rely on that it runs before my Vue app runs? (on the client) something like: