bagsy/apps/mobile/app/_layout.tsx
bananabas ba6aeb6c7c feat: add configurable backend URL with UI prompt
- App now prompts for backend URL on first launch
- Stores in SecureStore for persistence
- Default: http://localhost:3001
- Can be changed in app settings
- Backend setup screen at /app/(auth)/backend-setup.tsx
2026-03-28 08:39:00 +00:00

71 lines
2 KiB
TypeScript

import { useEffect, useState } from 'react';
import { Stack } from 'expo-router';
import { useAuthStore } from '@/store/auth';
import { useWebSocket } from '@/hooks/useWebSocket';
import { authClient } from '@/lib/auth-client';
import { getBackendUrl } from '@/lib/api';
/**
* Root layout with auth guard
* Routes to backend-setup if not configured, then to auth stack or app stack
*/
export default function RootLayout() {
const { user, setUser, setIsLoading } = useAuthStore();
const [backendConfigured, setBackendConfigured] = useState(false);
const [checked, setChecked] = useState(false);
// Initialize WebSocket connection when authenticated
useWebSocket();
useEffect(() => {
// Check if user is already authenticated
async function checkAuth() {
try {
setIsLoading(true);
const response = await authClient.getSession();
const sessionData = (response as any)?.data;
if (sessionData && (sessionData.user || sessionData.data?.user)) {
const user = sessionData.user || sessionData.data?.user;
setUser(user);
}
} catch (error) {
console.error('Auth check failed:', error);
} finally {
setIsLoading(false);
}
}
// Check if backend URL is configured
async function checkBackend() {
const url = await getBackendUrl();
setBackendConfigured(!!url);
setChecked(true);
}
checkBackend();
checkAuth();
}, [setUser, setIsLoading]);
if (!checked) {
return null; // Or a loading screen
}
return (
<Stack
screenOptions={{
headerShown: false,
}}
>
{!backendConfigured ? (
// Backend not configured - show setup first
<Stack.Screen name="(auth)/backend-setup" />
) : user ? (
// User is authenticated - show app stack
<Stack.Screen name="(app)" />
) : (
// User is not authenticated - show auth stack
<Stack.Screen name="(auth)" />
)}
</Stack>
);
}