Fix redirect loops and SSR hydration issues in auth flow
All checks were successful
Build And Push Image / docker (push) Successful in 2m59s

- Replace ref with useState in useAuth for SSR compatibility
- Move navigation logic from top-level to onMounted hooks
- Add guest middleware to login page to prevent auth conflicts
- Simplify dashboard auth checks by relying on middleware
- Add loading state to index page during auth resolution

This prevents infinite redirect loops and hydration mismatches that
occurred during server-side rendering when navigating between
authenticated and unauthenticated states.
This commit is contained in:
2025-08-07 17:21:18 +02:00
parent 423d8c3aa1
commit c6a57c7922
5 changed files with 276 additions and 39 deletions

View File

@@ -18,35 +18,26 @@
<script setup lang="ts">
definePageMeta({
middleware: 'auth'
middleware: 'auth',
layout: 'dashboard'
});
const { user, userTier, isAuthenticated, checkAuth } = useAuth();
const { user, userTier } = useAuth();
const loading = ref(true);
const authChecked = ref(false);
// Check authentication on mount
onMounted(async () => {
console.log('🔄 Dashboard mounted, checking authentication...');
// Route to tier-specific dashboard - auth middleware ensures user is authenticated
onMounted(() => {
console.log('🔄 Dashboard mounted, routing to tier-specific page...');
// Ensure auth is checked before routing
await checkAuth();
authChecked.value = true;
console.log('✅ Auth check complete:', {
isAuthenticated: isAuthenticated.value,
user: user.value?.email,
tier: userTier.value
});
// Now route based on auth status
if (isAuthenticated.value && user.value) {
// Auth middleware has already verified authentication - just route to tier page
if (user.value && userTier.value) {
const tierRoute = `/dashboard/${userTier.value}`;
console.log('🔄 Routing to tier-specific dashboard:', tierRoute);
await navigateTo(tierRoute, { replace: true });
navigateTo(tierRoute, { replace: true });
} else {
console.log('🔄 User not authenticated, redirecting to login');
await navigateTo('/login');
console.warn('❌ No user or tier found - this should not happen after auth middleware');
// Fallback - middleware should have caught this
navigateTo('/login');
}
loading.value = false;