Implement protected routes, authentication guards, and handle deep links.
Route Groups for Auth
Route groups in Expo Router let you apply different layouts to different route sets without affecting URLs.
app/
├── _layout.tsx # Root: decides (auth) vs (app)
├── (auth)/ # Public routes (no auth required)
│ ├── _layout.tsx # Stack layout
│ ├── login.tsx # /login
│ ├── register.tsx # /register
│ └── forgot-password.tsx
├── (app)/ # Protected routes (auth required)
│ ├── _layout.tsx # Tabs layout
│ ├── index.tsx # / (home)
│ ├── search.tsx # /search
│ └── profile.tsx # /profile
└── +not-found.tsx
Root Layout: Auth Decision
// app/_layout.tsx
import { Stack } from 'expo-router';
import { useEffect, useState } from 'react';
import { View, ActivityIndicator, StyleSheet } from 'react-native';
import { useAuth } from '@/hooks/useAuth';
export default function RootLayout() {
const { user, loading, initializeAuth } = useAuth();
const [isReady, setIsReady] = useState(false);
useEffect(() => {
initializeAuth().finally(() => setIsReady(true));
}, [initializeAuth]);
// Show splash while initializing
if (!isReady) {
return (
<View style={styles.splash}>
<ActivityIndicator size="large" color="#3b82f6" />
</View>
);
}
return (
<Stack screenOptions={{ headerShown: false }}>
{user ? (
// Authenticated: show main app
<Stack.Screen name="(app)" />
) : (
// Not authenticated: show auth flow
<Stack.Screen name="(auth)" />
)}
</Stack>
);
}
const styles = StyleSheet.create({
splash: { flex: 1, justifyContent: 'center', alignItems: 'center' },
});Auth Context
// hooks/useAuth.tsx
import { createContext, useContext, useState, useEffect, ReactNode } from 'react';
import { useRouter } from 'expo-router';
import * as SecureStore from 'expo-secure-store';
interface User {
id: string;
email: string;
name: string;
avatar?: string;
}
interface AuthContextType {
user: User | null;
loading: boolean;
login: (email: string, password: string) => Promise<void>;
register: (email: string, password: string, name: string) => Promise<void>;
logout: () => Promise<void>;
initializeAuth: () => Promise<void>;
}
const AuthContext = createContext<AuthContextType | null>(null);
export function AuthProvider({ children }: { children: ReactNode }) {
const [user, setUser] = useState<User | null>(null);
const [loading, setLoading] = useState(true);
const router = useRouter();
const initializeAuth = async () => {
try {
const token = await SecureStore.getItemAsync('auth_token');
const userData = await SecureStore.getItemAsync('user_data');
if (token && userData) {
setUser(JSON.parse(userData));
}
} catch (error) {
console.error('Auth init failed:', error);
} finally {
setLoading(false);
}
};
const login = async (email: string, password: string) => {
const response = await fetch('https://api.example.com/auth/login', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ email, password }),
});
if (!response.ok) throw new Error('Invalid credentials');
const { token, user: userData } = await response.json();
await SecureStore.setItemAsync('auth_token', token);
await SecureStore.setItemAsync('user_data', JSON.stringify(userData));
setUser(userData);
router.replace('/(app)');
};
const register = async (email: string, password: string, name: string) => {
const response = await fetch('https://api.example.com/auth/register', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ email, password, name }),
});
if (!response.ok) throw new Error('Registration failed');
const { token, user: userData } = await response.json();
await SecureStore.setItemAsync('auth_token', token);
await SecureStore.setItemAsync('user_data', JSON.stringify(userData));
setUser(userData);
router.replace('/(app)');
};
const logout = async () => {
await SecureStore.deleteItemAsync('auth_token');
await SecureStore.deleteItemAsync('user_data');
setUser(null);
router.replace('/(auth)/login');
};
return (
<AuthContext.Provider value={{ user, loading, login, register, logout, initializeAuth }}>
{children}
</AuthContext.Provider>
);
}
export function useAuth() {
const context = useContext(AuthContext);
if (!context) throw new Error('useAuth must be used within AuthProvider');
return context;
}Protected Route Guard
// app/(app)/_layout.tsx
import { Tabs } from 'expo-router';
import { useEffect } from 'react';
import { useAuth } from '@/hooks/useAuth';
export default function AppLayout() {
const { user, loading } = useAuth();
// Redirect if not authenticated
useEffect(() => {
if (!loading && !user) {
// This shouldn't happen if root layout works, but safety net
}
}, [user, loading]);
if (loading) return null;
if (!user) return null;
return (
<Tabs screenOptions={{ headerShown: false }}>
<Tabs.Screen name="index" options={{ title: 'Home' }} />
<Tabs.Screen name="search" options={{ title: 'Search' }} />
<Tabs.Screen name="profile" options={{ title: 'Profile' }} />
</Tabs>
);
}Redirecting Unauthenticated Users
For more granular control, use a wrapper component:
// components/RequireAuth.tsx
import { useEffect } from 'react';
import { useRouter, useLocalSearchParams } from 'expo-router';
import { useAuth } from '@/hooks/useAuth';
import { View, ActivityIndicator, StyleSheet } from 'react-native';
export function RequireAuth({ children }: { children: React.ReactNode }) {
const { user, loading } = useAuth();
const router = useRouter();
const params = useLocalSearchParams<{ redirectTo?: string }>();
useEffect(() => {
if (!loading && !user) {
const redirect = params.redirectTo || '/(app)';
router.replace(`/(auth)/login?redirectTo=${encodeURIComponent(redirect)}`);
}
}, [user, loading, router, params.redirectTo]);
if (loading) {
return <View style={styles.loading}><ActivityIndicator size="large" /></View>;
}
if (!user) return null;
return <>{children}</>;
}
const styles = StyleSheet.create({
loading: { flex: 1, justifyContent: 'center', alignItems: 'center' },
});Usage in Protected Screens
// app/(app)/profile.tsx
import { RequireAuth } from '@/components/RequireAuth';
import { View, Text, StyleSheet } from 'react-native';
export default function ProfileScreen() {
return (
<RequireAuth>
<View style={styles.container}>
<Text style={styles.title}>Profile</Text>
{/* Only authenticated users see this */}
</View>
</RequireAuth>
);
}Login Screen with Redirect
// app/(auth)/login.tsx
import { View, Text, TextInput, Pressable, StyleSheet, Alert, Keyboard } from 'react-native';
import { useRouter, useLocalSearchParams } from 'expo-router';
import { useAuth } from '@/hooks/useAuth';
import { useState } from 'react';
export default function LoginScreen() {
const router = useRouter();
const { login } = useAuth();
const params = useLocalSearchParams<{ redirectTo?: string }>();
const [email, setEmail] = useState('');
const [password, setPassword] = useState('');
const [loading, setLoading] = useState(false);
const [error, setError] = useState('');
const handleLogin = async () => {
Keyboard.dismiss();
setError('');
setLoading(true);
try {
await login(email, password);
// Redirect handled in login function
const redirect = params.redirectTo || '/(app)';
router.replace(redirect);
} catch (err) {
setError(err instanceof Error ? err.message : 'Login failed');
} finally {
setLoading(false);
}
};
return (
<View style={styles.container}>
<Text style={styles.title}>Welcome Back</Text>
{error && <Text style={styles.error}>{error}</Text>}
<TextInput
style={styles.input}
placeholder="Email"
value={email}
onChangeText={setEmail}
keyboardType="email-address"
autoCapitalize="none"
textContentType="emailAddress"
autoCompleteType="email"
/>
<TextInput
style={styles.input}
placeholder="Password"
value={password}
onChangeText={setPassword}
secureTextEntry
textContentType="password"
autoCompleteType="password"
/>
<Pressable style={[styles.button, loading && styles.buttonLoading]} onPress={handleLogin} disabled={loading}>
<Text style={styles.buttonText}>{loading ? 'Signing in...' : 'Sign In'}</Text>
</Pressable>
<Pressable onPress={() => router.push('/(auth)/register')}>
<Text style={styles.link}>Don't have an account? Sign up</Text>
</Pressable>
</View>
);
}Deep Link Handling
Configure URL Scheme
// app.json
{
"expo": {
"scheme": "myapp",
"ios": {
"bundleIdentifier": "com.myapp.mobile",
"associatedDomains": ["applinks:myapp.com"]
},
"android": {
"package": "com.myapp.mobile",
"intentFilters": [
{
"action": "VIEW",
"autoVerify": true,
"data": [
{ "scheme": "https", "host": "myapp.com", "pathPrefix": "/" },
{ "scheme": "myapp" }
],
"category": ["BROWSABLE", "DEFAULT"]
}
]
}
}
}Handle Deep Links in Root Layout
// app/_layout.tsx
import { Stack } from 'expo-router';
import { Linking, Platform } from 'react-native';
import { useEffect } from 'react';
import { useAuth } from '@/hooks/useAuth';
import * as SecureStore from 'expo-secure-store';
export default function RootLayout() {
const { user, initializeAuth } = useAuth();
const [isReady, setIsReady] = useState(false);
const [initialUrl, setInitialUrl] = useState<string | null>(null);
useEffect(() => {
// Get initial URL (cold start)
Linking.getInitialURL().then((url) => {
if (url) setInitialUrl(url);
});
// Listen for URLs while app is running
const subscription = Linking.addEventListener('url', ({ url }) => {
handleDeepLink(url);
});
initializeAuth().finally(() => setIsReady(true));
return () => subscription.remove();
}, [initializeAuth]);
const handleDeepLink = async (url: string) => {
// Parse URL: myapp://movie/123 or https://myapp.com/movie/123
const path = url.replace(/^.*?\/\/[^/]+\//, '/');
// If user not logged in, store for after login
if (!user) {
await SecureStore.setItemAsync('pending_deep_link', path);
return;
}
// Navigate to the deep link path
// router.push(path); // Would need router context
};
if (!isReady) return <SplashScreen />;
return (
<Stack>
{user ? <Stack.Screen name="(app)" /> : <Stack.Screen name="(auth)" />}
</Stack>
);
}Process Pending Deep Link After Login
// hooks/useAuth.tsx (updated login)
const login = async (email: string, password: string) => {
// ... existing login logic ...
setUser(userData);
// Check for pending deep link
const pendingLink = await SecureStore.getItemAsync('pending_deep_link');
if (pendingLink) {
await SecureStore.deleteItemAsync('pending_deep_link');
router.push(pendingLink);
} else {
router.replace('/(app)');
}
};Universal Links / App Links Verification
# iOS: Host apple-app-site-association at https://myapp.com/.well-known/apple-app-site-association
{
"applinks": {
"apps": [],
"details": [
{
"appID": "TEAM_ID.com.myapp.mobile",
"paths": ["/movie/*", "/profile/*", "NOT /admin/*"]
}
]
}
}
# Android: Host assetlinks.json at https://myapp.com/.well-known/assetlinks.json
[{
"relation": ["delegate_permission/common.handle_all_urls"],
"target": {
"namespace": "android_app",
"package_name": "com.myapp.mobile",
"sha256_cert_fingerprints": ["SHA256_FINGERPRINT"]
}
}]Testing Deep Links
# iOS Simulator
xcrun simctl openurl booted "myapp://movie/123"
xcrun simctl openurl booted "https://myapp.com/movie/123"
# Android Emulator
adb shell am start -W -a android.intent.action.VIEW -d "myapp://movie/123" com.myapp.mobile
adb shell am start -W -a android.intent.action.VIEW -d "https://myapp.com/movie/123" com.myapp.mobile
# Expo CLI
npx uri-scheme open myapp://movie/123 --ios
npx uri-scheme open myapp://movie/123 --androidNavigation Patterns with Auth
Onboarding Flow (First Launch Only)
// app/_layout.tsx
import { Stack } from 'expo-router';
import * as SecureStore from 'expo-secure-store';
import { useEffect, useState } from 'react';
export default function RootLayout() {
const [showOnboarding, setShowOnboarding] = useState(false);
const [checked, setChecked] = useState(false);
useEffect(() => {
SecureStore.getItemAsync('has_seen_onboarding').then((value) => {
setShowOnboarding(!value);
setChecked(true);
});
}, []);
if (!checked) return <SplashScreen />;
return (
<Stack screenOptions={{ headerShown: false }}>
{showOnboarding ? (
<Stack.Screen name="onboarding" />
) : (
<>
<Stack.Screen name="(auth)" />
<Stack.Screen name="(app)" />
</>
)}
</Stack>
);
}
// app/onboarding.tsx
import { View, Text, Pressable, StyleSheet } from 'react-native';
import { useRouter } from 'expo-router';
import * as SecureStore from 'expo-secure-store';
export default function OnboardingScreen() {
const router = useRouter();
const finish = async () => {
await SecureStore.setItemAsync('has_seen_onboarding', 'true');
router.replace('/(auth)/login');
};
return (
<View style={styles.container}>
<Text style={styles.title}>Welcome to MyApp!</Text>
<Pressable style={styles.button} onPress={finish}>
<Text style={styles.buttonText}>Get Started</Text>
</Pressable>
</View>
);
}Logout with Clean Navigation
// app/(app)/settings.tsx
import { View, Text, Pressable, StyleSheet, Alert } from 'react-native';
import { useRouter } from 'expo-router';
import { useAuth } from '@/hooks/useAuth';
export default function SettingsScreen() {
const { logout, user } = useAuth();
const router = useRouter();
const handleLogout = () => {
Alert.alert(
'Sign Out',
'Are you sure you want to sign out?',
[
{ text: 'Cancel', style: 'cancel' },
{ text: 'Sign Out', style: 'destructive', onPress: async () => {
await logout();
router.replace('/(auth)/login');
}
},
]
);
};
return (
<View style={styles.container}>
<Text style={styles.title}>Settings</Text>
<Text style={styles.userEmail}>{user?.email}</Text>
<Pressable style={styles.logoutButton} onPress={handleLogout}>
<Text style={styles.logoutText}>Sign Out</Text>
</Pressable>
</View>
);
}Try It
Build the auth flow. Test: 1) Cold start → shows login. 2) Login → redirects to app. 3) Deep link when logged out → redirects after login. 4) Deep link when logged in → navigates directly.
# Test deep links
npx uri-scheme open myapp://movie/123 --ios
npx uri-scheme open myapp://movie/123 --android
# Test universal links (requires hosted domain)
# xcrun simctl openurl booted "https://myapp.com/movie/123"Build complete auth with onboarding
- Create onboarding screen (shown once)
- Implement login/register with SecureStore
- Set up root layout with (auth) and (app) groups
- Add RequireAuth wrapper for protected screens
- Configure app scheme and test deep links
- Handle deep links before and after login
- Add logout with confirmation
- Test: fresh install → onboarding → login → app → deep link
Route groups ((auth), (app)) separate layouts without URL changes. Root layout decides which group to show based on auth state. Deep links: configure scheme + associated domains/intent filters. Store pending links in SecureStore, process after login. Always test cold start, background, and foreground deep link scenarios.
Resources
- Expo Router: Route Groups: https://docs.expo.dev/router/advanced/route-groups/
- Expo Router: Authentication: https://docs.expo.dev/router/advanced/authentication/
- Expo Router: Deep Linking: https://docs.expo.dev/router/reference/deep-linking/
- Expo SecureStore: https://docs.expo.dev/versions/latest/sdk/securestore/
- iOS Universal Links: https://developer.apple.com/documentation/xcode/supporting-universal-links-in-your-app
- Android App Links: https://developer.android.com/training/app-links