fitaiProto/docs/CLERK_SETUP.md
2025-11-19 05:12:19 +01:00

12 KiB

Clerk Authentication Setup Guide

This guide will walk you through setting up Clerk authentication for both the FitAI Admin (Next.js) and Mobile (Expo) applications.

Prerequisites

Table of Contents

  1. Create a Clerk Application
  2. Admin App Setup (Next.js)
  3. Mobile App Setup (Expo)
  4. Testing the Integration
  5. Troubleshooting

1. Create a Clerk Application

Step 1: Sign Up for Clerk

  1. Go to https://dashboard.clerk.com
  2. Sign up for a free account or sign in if you already have one

Step 2: Create a New Application

  1. Click "Add application" in the Clerk Dashboard
  2. Choose a name for your application (e.g., "FitAI")
  3. Select your authentication providers:
    • Email (required) - Enable email/password authentication
    • Optional: Google, Facebook, GitHub, etc.
  4. Click "Create application"

Step 3: Get Your API Keys

After creating your application, you'll see your API keys:

  • Publishable Key: Starts with pk_test_ (for development) or pk_live_ (for production)
  • Secret Key: Starts with sk_test_ (for development) or sk_live_ (for production)

Important: Keep your Secret Key secure and never commit it to version control!


2. Admin App Setup (Next.js)

Step 1: Install Dependencies

The Clerk package is already installed. Verify with:

cd apps/admin
npm list @clerk/nextjs

Step 2: Create Environment Variables

  1. Create a .env.local file in apps/admin/:
cd apps/admin
cp .env.local.example .env.local
  1. Edit .env.local and add your Clerk keys:
# Clerk Authentication
NEXT_PUBLIC_CLERK_PUBLISHABLE_KEY=pk_test_YOUR_PUBLISHABLE_KEY_HERE
CLERK_SECRET_KEY=sk_test_YOUR_SECRET_KEY_HERE

# Clerk URLs
NEXT_PUBLIC_CLERK_SIGN_IN_URL=/sign-in
NEXT_PUBLIC_CLERK_SIGN_UP_URL=/sign-up
NEXT_PUBLIC_CLERK_AFTER_SIGN_IN_URL=/
NEXT_PUBLIC_CLERK_AFTER_SIGN_UP_URL=/

# Database
DATABASE_URL=./data/fitai.db

Step 3: Configure Clerk Dashboard (Admin App)

In the Clerk Dashboard:

  1. Go to "Application""Paths"

  2. Set the following URLs:

    • Sign-in URL: /sign-in (or use Clerk's hosted pages)
    • Sign-up URL: /sign-up (or use Clerk's hosted pages)
    • Home URL: /
  3. Go to "Sessions"

    • Enable "Multi-session handling" if you want users to have multiple sessions
    • Set session lifetime as needed (default: 7 days)

Step 4: Test the Admin App

cd apps/admin
npm run dev

Visit http://localhost:3000 - you should be redirected to Clerk's sign-in page.


3. Mobile App Setup (Expo)

Step 1: Install Dependencies

The Clerk Expo package and required dependencies are already installed. Verify with:

cd apps/mobile
npm list @clerk/clerk-expo expo-web-browser expo-auth-session expo-secure-store expo-crypto

Note: If you need to install manually:

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

All Required Clerk Dependencies:

  • @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 (already installed)
  • expo-linking - Deep linking support (already installed)

Step 2: Create Environment Variables

  1. Create a .env file in apps/mobile/:
cd apps/mobile
cp .env.example .env
  1. Edit .env and add your Clerk publishable key:
# Clerk Authentication
EXPO_PUBLIC_CLERK_PUBLISHABLE_KEY=pk_test_YOUR_PUBLISHABLE_KEY_HERE

# API Configuration
EXPO_PUBLIC_API_URL=http://localhost:3000/api

# App Configuration
EXPO_PUBLIC_APP_NAME=FitAI
EXPO_PUBLIC_APP_VERSION=1.0.0

Note: For mobile apps, you only need the publishable key (not the secret key).

Step 3: Configure Clerk Dashboard (Mobile App)

In the Clerk Dashboard:

  1. Go to "Application""Mobile"

  2. Add your app's package/bundle identifiers:

    • Android: com.fitai.mobile (or your custom package name)
    • iOS: com.fitai.mobile (or your custom bundle ID)
  3. Go to "Email, Phone, Username" settings:

    • Enable Email address as a required identifier
    • Enable Password as a required authentication strategy
    • Optional: Enable Email verification code for passwordless login

Step 4: Update App Configuration

Edit apps/mobile/app.json to ensure your package names match Clerk configuration:

{
  "expo": {
    "name": "FitAI",
    "slug": "fitai-mobile",
    "version": "1.0.0",
    "ios": {
      "bundleIdentifier": "com.fitai.mobile"
    },
    "android": {
      "package": "com.fitai.mobile"
    }
  }
}

Step 5: Test the Mobile App

cd apps/mobile
npm start

Use Expo Go to scan the QR code and test the app on your device.


4. Testing the Integration

Admin App Testing

  1. Start the admin app:

    cd apps/admin
    npm run dev
    
  2. Test Sign-Up:

    • Visit http://localhost:3000
    • You'll be redirected to Clerk's sign-in page
    • Click "Sign up" and create a test account
    • Complete email verification (check your inbox)
    • You should be redirected to the dashboard
  3. Test Sign-In:

    • Sign out using the user button in the header
    • Sign back in with your credentials
    • Verify you can access protected routes

Mobile App Testing

  1. Start the mobile app:

    cd apps/mobile
    npm start
    
  2. Test Sign-Up:

    • Open the app in Expo Go
    • Tap "Sign Up" on the welcome screen
    • Fill in your details (use a different email than admin)
    • Enter the verification code sent to your email
    • You should be redirected to the home tab
  3. Test Sign-In:

    • Sign out from the Profile tab
    • Sign back in with your credentials
    • Verify navigation works correctly

Cross-Platform Testing

Test that both apps work together:

  1. Create a user in the admin app
  2. Try logging in with the same credentials in the mobile app
  3. Verify user data syncs across platforms

5. Troubleshooting

Common Issues and Solutions

Issue: "Missing Clerk Publishable Key"

Solution:

  • Ensure your .env.local (admin) or .env (mobile) file exists
  • Verify the key starts with pk_test_ or pk_live_
  • Restart your development server after adding the key

Issue: "Invalid API key"

Solution:

  • Double-check your keys in the Clerk Dashboard
  • Make sure you're using the correct environment (test vs. production)
  • Ensure there are no extra spaces or quotes in your .env file

Issue: Mobile app shows blank screen

Solution:

  • Check the console logs for errors
  • Verify @clerk/clerk-expo is installed correctly
  • Ensure expo-secure-store is installed (required for token storage)
  • Ensure expo-web-browser is installed (required for OAuth flows)
  • Try clearing Expo cache: npx expo start -c

Issue: "Unable to resolve expo-web-browser", "expo-auth-session", or "react-dom"

Solution: Install all required Clerk dependencies at once:

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

These packages are required by Clerk for:

  • expo-web-browser - OAuth authentication flows
  • expo-auth-session - SSO and session management
  • expo-secure-store - Secure token storage
  • expo-crypto - Cryptographic operations
  • react-dom - React DOM for web compatibility
  • react-native-web - React Native web compatibility layer

Issue: Email verification code not received

Solution:

  • Check your spam folder
  • In Clerk Dashboard, verify email settings are configured
  • For development, you can check the Clerk Dashboard logs to see sent emails
  • Consider enabling "Development mode" in Clerk to bypass email verification

Issue: Redirect loops or infinite redirects

Solution:

  • Check your middleware configuration in apps/admin/src/middleware.ts
  • Ensure public routes are properly defined
  • Verify NEXT_PUBLIC_CLERK_SIGN_IN_URL is set correctly
  • Clear browser cookies and try again

Issue: "ERESOLVE" errors during npm install

Solution:

  • Use --legacy-peer-deps flag:
    npm install --legacy-peer-deps
    
  • This is normal for React Native projects with multiple dependencies

Issue: Bundling failed with Clerk dependencies

Solution:

  • Ensure all required Expo packages are installed:
    cd apps/mobile
    npm install expo-web-browser expo-auth-session expo-secure-store expo-crypto react-dom react-native-web expo-constants
    
  • Clear Metro bundler cache:
    npx expo start -c
    
  • Verify all dependencies:
    npm list @clerk/clerk-expo
    

Advanced Configuration

Customizing Clerk UI

You can customize Clerk's appearance in both apps:

Admin App (apps/admin/src/app/layout.tsx):

<ClerkProvider
  appearance={{
    baseTheme: "light",
    variables: {
      colorPrimary: "#2563eb",
      fontFamily: "Inter, sans-serif",
    },
  }}
>

Mobile App: Use custom screens (already implemented in apps/mobile/src/app/(auth)/)

Adding Social Providers

  1. In Clerk Dashboard, go to "Social Connections"
  2. Enable providers (Google, Facebook, etc.)
  3. Add OAuth credentials for each provider
  4. No code changes needed - Clerk handles it automatically!

Webhooks (Optional)

To sync Clerk users with your database:

  1. In Clerk Dashboard, go to "Webhooks"
  2. Add endpoint: https://your-domain.com/api/webhooks/clerk
  3. Select events: user.created, user.updated, user.deleted
  4. Implement webhook handler in apps/admin/src/app/api/webhooks/clerk/route.ts

Multi-tenant Support

For gym chains with multiple locations:

  1. Use Clerk Organizations feature
  2. Enable in Clerk Dashboard under "Organizations"
  3. Each gym becomes an organization
  4. Users can belong to multiple organizations

Security Best Practices

  1. Never commit .env files - They're in .gitignore by default
  2. Use different keys for development and production
  3. Enable MFA for admin accounts in Clerk Dashboard
  4. Set up rate limiting for API routes
  5. Regularly rotate API keys in production
  6. Use HTTPS in production (required for OAuth)
  7. Enable session security features in Clerk Dashboard

Next Steps

After successfully setting up Clerk:

  1. Test authentication flows in both apps
  2. Customize the sign-in/sign-up experience
  3. Set up user roles and permissions
  4. 🔄 Implement payment system integration
  5. 🔄 Add attendance tracking with Clerk user IDs
  6. 🔄 Set up webhook handlers for user sync
  7. 🔄 Configure production environment variables
  8. 🔄 Deploy to production with proper SSL/HTTPS

Resources


Support

If you encounter issues not covered in this guide:

  1. Check the Clerk documentation
  2. Search Clerk's Discord community
  3. Review the troubleshooting section above
  4. Check the console logs for detailed error messages

Last Updated: January 2025
Version: 1.0.1
Clerk SDK Versions:

  • @clerk/nextjs: Latest
  • @clerk/clerk-expo: Latest

Required Dependencies for Mobile:

  • 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
  • expo-linking: Deep linking support
  • expo-status-bar: Status bar styling (optional)