Middlewares

Is Logged In

🧭 Overview

The is-logged-in.ts middleware ensures a user is authenticated before accessing protected routes. If the user is not logged in, it redirects them to the login page and stores the intended route so they can be redirected back after successful authentication.


📄 Code Example

// middleware/is-logged-in.ts
export default defineNuxtRouteMiddleware(async (to, from) => {
  const authStore = useAuthStore();

  if (!authStore.is_authenticated) {
    const localePath = useLocalePath();
    const rootStore = useRootStore();

    // Save intended destination to redirect after login
    rootStore.after_auth_intended_route = to.fullPath;

    // Redirect to login page
    return await navigateTo(localePath("/login"));
  }
});

⚙️ How It Works

  1. Auth Check: Verifies whether the user is authenticated using authStore.is_authenticated.
  2. Route Memory: If not authenticated, stores the user's target route in after_auth_intended_route.
  3. Redirection: Navigates the user to the localized login route using localePath("/login").

🔧 Use Case

This middleware is typically used in pages such as:

/pages/;
account / profile.vue;
orders.vue;
pro-card.vue;

Apply it using:

definePageMeta({
  middleware: ["is-logged-in"],
});

📝 Notes

  • The intended route is remembered so users can be returned to it after logging in.
  • Works with localized paths thanks to useLocalePath().
  • Designed for full user session verification, not for guest access.

📚 Learn More


Copyright © 2026