# Troubleshooting Guide - FitAI

This guide helps resolve common issues when setting up and running the FitAI applications.

---

## Mobile App Issues

### ❌ Error: "Unable to resolve expo-web-browser", "expo-auth-session", or "react-dom"

**Error Messages:**
```
Unable to resolve "expo-web-browser" from "node_modules/@clerk/clerk-expo/dist/provider/ClerkProvider.js"
```
or
```
Unable to resolve "expo-auth-session" from "node_modules/@clerk/clerk-expo/dist/hooks/useSSO.js"
```
or
```
Unable to resolve "react-dom" from "node_modules/@clerk/clerk-react/dist/index.js"
```

**Cause:** Missing required dependencies for Clerk OAuth, SSO flows, and web compatibility.

**Solution:**
Install all required Clerk dependencies at once:
```bash
cd apps/mobile
npm install expo-web-browser expo-auth-session expo-secure-store expo-crypto react-dom react-native-web
npx expo start -c
```

**Complete Clerk Dependencies:**
- `expo-web-browser` - OAuth flows and browser interactions
- `expo-auth-session` - SSO and authentication sessions  
- `expo-secure-store` - Secure token storage
- `expo-crypto` - Cryptographic functions
- `react-dom` - React DOM for web compatibility
- `react-native-web` - React Native web compatibility layer

---

### ❌ Error: "Missing Clerk Publishable Key"

**Error Message:**
```
Missing Clerk Publishable Key
Please add EXPO_PUBLIC_CLERK_PUBLISHABLE_KEY to your .env file
```

**Solution:**
1. Create `.env` file in `apps/mobile/`:
   ```bash
   cp .env.example .env
   ```

2. Add your Clerk key from https://dashboard.clerk.com:
   ```env
   EXPO_PUBLIC_CLERK_PUBLISHABLE_KEY=pk_test_your_key_here
   ```

3. Restart Metro bundler:
   ```bash
   npx expo start -c
   ```

---

### ❌ Blank Screen on Mobile App

**Possible Causes:**
- Clerk not initialized properly
- Token cache error
- Navigation state issue

**Solution:**
1. Check console logs for errors
2. Verify all dependencies installed:
   ```bash
   cd apps/mobile
   npm install @clerk/clerk-expo expo-web-browser expo-auth-session expo-secure-store expo-crypto react-dom react-native-web
   ```
3. Clear Metro cache:
   ```bash
   npx expo start -c
   ```
4. Restart Expo Go app completely

---

### ❌ ERESOLVE Dependency Conflicts

**Error Message:**
```
npm error ERESOLVE could not resolve
npm error peer react@"^19.2.0" from react-dom@19.2.0
```

**Solution:**
The project now has an `.npmrc` file that automatically handles this.

If you still see errors:
```bash
cd apps/mobile
npm install
```

The `.npmrc` file contains:
```
legacy-peer-deps=true
```

---

### ❌ Error: "useAuth hook called outside ClerkProvider"

**Cause:** Component using Clerk hooks is rendered before ClerkProvider initializes.

**Solution:**
Ensure your component is wrapped properly:

```tsx
// ✅ Correct - Component inside ClerkProvider
<ClerkProvider>
  <MyComponent />  {/* Can use useAuth here */}
</ClerkProvider>

// ❌ Wrong - Component outside ClerkProvider
<MyComponent />  {/* Cannot use useAuth here */}
<ClerkProvider>
  ...
</ClerkProvider>
```

---

### ❌ Email Verification Code Not Received

**Solutions:**
1. Check spam folder
2. In Clerk Dashboard > Logs, verify email was sent
3. For development testing, enable bypass:
   - Go to Clerk Dashboard
   - Settings > Email, Phone, Username
   - Enable "Development mode" to skip verification

---

## Admin App Issues

### ❌ Error: "Invalid API Key"

**Cause:** Incorrect or missing Clerk API keys.

**Solution:**
1. Verify keys in Clerk Dashboard
2. Check `.env.local` file exists in `apps/admin/`
3. Ensure keys match exactly (no spaces):
   ```env
   NEXT_PUBLIC_CLERK_PUBLISHABLE_KEY=pk_test_xxxxx
   CLERK_SECRET_KEY=sk_test_xxxxx
   ```
4. Restart dev server:
   ```bash
   cd apps/admin
   npm run dev
   ```

---

### ❌ Redirect Loop / Infinite Redirects

**Cause:** Middleware configuration issue.

**Solution:**
1. Check `apps/admin/src/middleware.ts`
2. Verify public routes are defined:
   ```typescript
   const isPublicRoute = createRouteMatcher([
     '/sign-in(.*)',
     '/sign-up(.*)',
   ])
   ```
3. Clear browser cookies
4. Try incognito/private browsing mode

---

### ❌ Error: "clerkMiddleware is not a function"

**Cause:** Outdated Clerk package.

**Solution:**
```bash
cd apps/admin
npm install @clerk/nextjs@latest
npm run dev
```

---

## Database Issues

### ❌ Error: "SQLITE_CANTOPEN: unable to open database file"

**Cause:** Database file or directory doesn't exist.

**Solution:**
```bash
cd apps/admin
mkdir -p data
touch data/fitai.db
npm run dev
```

---

### ❌ Database Schema Out of Sync

**Solution:**
```bash
cd packages/database
npm run db:push
```

---

## Build Issues

### ❌ TypeScript Errors After Install

**Solution:**
```bash
# Admin app
cd apps/admin
npm run typecheck

# Mobile app
cd apps/mobile
npm run typecheck
```

Fix any TypeScript errors reported.

---

### ❌ ESLint Errors

**Solution:**
```bash
# Run lint fix
npm run lint --fix

# Or disable specific rules in .eslintrc
```

---

## Network Issues

### ❌ Mobile App Can't Connect to API

**For Android Emulator:**
```typescript
// Use this URL in mobile app
const API_URL = 'http://10.0.2.2:3000'
```

**For iOS Simulator:**
```typescript
const API_URL = 'http://localhost:3000'
```

**For Physical Device:**
```typescript
// Use your computer's local IP
const API_URL = 'http://192.168.1.XXX:3000'
```

Find your IP:
- **Mac/Linux**: `ifconfig | grep "inet " | grep -v 127.0.0.1`
- **Windows**: `ipconfig` and look for IPv4 Address

---

## Clerk-Specific Issues

### ❌ Social Login Not Working

**Solution:**
1. Enable provider in Clerk Dashboard
2. Add OAuth credentials
3. For mobile, add URL schemes in `app.json`:
   ```json
   {
     "expo": {
       "scheme": "fitai",
       "ios": {
         "bundleIdentifier": "com.fitai.mobile"
       },
       "android": {
         "package": "com.fitai.mobile"
       }
     }
   }
   ```

---

### ❌ Session Not Persisting

**Mobile App:**
- Verify all Clerk dependencies are installed:
  ```bash
  npm list @clerk/clerk-expo expo-secure-store expo-auth-session react-dom react-native-web
  ```
- Check token cache implementation in `_layout.tsx`
- Verify SecureStore permissions

**Admin App:**
- Check browser cookies enabled
- Verify session settings in Clerk Dashboard
- Clear browser cache and try again

---

### ❌ User Metadata Not Saving

**Solution:**
```typescript
// Update user metadata
await clerk.user?.update({
  unsafeMetadata: {
    role: 'client',
    gymId: '123'
  }
})
```

Access metadata:
```typescript
const metadata = user?.unsafeMetadata
```

---

## Performance Issues

### ❌ Slow App Load Time

**Solutions:**
1. Enable caching:
   ```typescript
   // In ClerkProvider
   <ClerkProvider tokenCache={tokenCache}>
   ```

2. Optimize imports:
   ```typescript
   // ✅ Good - named imports
   import { useUser } from '@clerk/clerk-expo'
   
   // ❌ Avoid - default imports can bundle more
   import * as Clerk from '@clerk/clerk-expo'
   ```

---

### ❌ Metro Bundler Slow

**Solution:**
```bash
# Clear all caches
cd apps/mobile
rm -rf node_modules
npm install --legacy-peer-deps
npx expo start -c

# On Windows
rmdir /s /q node_modules
npm install --legacy-peer-deps
npx expo start -c
```

---

## Production Issues

### ❌ Environment Variables Not Working

**Admin App:**
- Must start with `NEXT_PUBLIC_` for client-side
- Restart dev server after changes
- In production, set on hosting platform (Vercel, etc.)

**Mobile App:**
- Must start with `EXPO_PUBLIC_` for Expo
- Run `npx expo start -c` after changes
- Rebuild app for production

---

## Getting Additional Help

### Check Logs

**Admin App:**
```bash
cd apps/admin
npm run dev
# Check terminal output
```

**Mobile App:**
```bash
cd apps/mobile
npm start
# Press 'j' to open debugger
# Check console in Expo Go app
```

**Verify All Clerk Dependencies:**
```bash
cd apps/mobile
npm list @clerk/clerk-expo expo-web-browser expo-auth-session expo-secure-store expo-crypto react-dom react-native-web
```

### Resources

- **Clerk Documentation**: https://clerk.com/docs
- **Clerk Dashboard Logs**: https://dashboard.clerk.com (go to Logs tab)
- **Clerk Discord**: https://clerk.com/discord
- **Expo Docs**: https://docs.expo.dev
- **Next.js Docs**: https://nextjs.org/docs

### Report Issues

If none of these solutions work:

1. Check console for error messages
2. Review stack trace
3. Search Clerk Discord for similar issues
4. Create detailed bug report with:
   - Error message
   - Steps to reproduce
   - Environment (OS, Node version, package versions)
   - Relevant code snippets

---

## Quick Fixes Checklist

When something breaks, try these in order:

- [ ] Restart dev server
- [ ] Clear Metro cache (`npx expo start -c`)
- [ ] Clear browser cache/cookies
- [ ] Verify environment variables
- [ ] Check Clerk Dashboard for issues
- [ ] Verify all dependencies installed
- [ ] Check console for error messages
- [ ] Try incognito/private mode
- [ ] Reinstall node_modules
- [ ] Check internet connection
- [ ] Verify API keys are correct

---

## Complete Dependency List

### Required for Clerk in Mobile App

All of these must be installed:

```bash
npm install @clerk/clerk-expo expo-web-browser expo-auth-session expo-secure-store expo-crypto react-dom react-native-web
```

| Package | Purpose |
|---------|---------|
| `@clerk/clerk-expo` | Core Clerk SDK |
| `expo-web-browser` | OAuth flows and browser interactions |
| `expo-auth-session` | SSO and authentication sessions |
| `expo-secure-store` | Secure token storage |
| `expo-crypto` | Cryptographic functions |
| `react-dom` | React DOM for web compatibility |
| `react-native-web` | React Native web compatibility layer |
| `expo-constants` | App configuration (pre-installed) |
| `expo-linking` | Deep linking support (pre-installed) |

---

**Last Updated:** January 2025  
**Version:** 1.1.0