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
- Node.js >= 18.0.0
- npm >= 9.0.0
- A Clerk account (sign up at https://clerk.com)
Table of Contents
- Create a Clerk Application
- Admin App Setup (Next.js)
- Mobile App Setup (Expo)
- Testing the Integration
- Troubleshooting
1. Create a Clerk Application
Step 1: Sign Up for Clerk
- Go to https://dashboard.clerk.com
- Sign up for a free account or sign in if you already have one
Step 2: Create a New Application
- Click "Add application" in the Clerk Dashboard
- Choose a name for your application (e.g., "FitAI")
- Select your authentication providers:
- Email (required) - Enable email/password authentication
- Optional: Google, Facebook, GitHub, etc.
- 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) orpk_live_(for production) - Secret Key: Starts with
sk_test_(for development) orsk_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
- Create a
.env.localfile inapps/admin/:
cd apps/admin
cp .env.local.example .env.local
- Edit
.env.localand 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:
-
Go to "Application" → "Paths"
-
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:
/
- Sign-in URL:
-
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 SDKexpo-web-browser- OAuth flows and browser interactionsexpo-auth-session- SSO and authentication sessionsexpo-secure-store- Secure token storageexpo-crypto- Cryptographic functionsreact-dom- React DOM for web compatibilityreact-native-web- React Native web compatibility layerexpo-constants- App configuration (already installed)expo-linking- Deep linking support (already installed)
Step 2: Create Environment Variables
- Create a
.envfile inapps/mobile/:
cd apps/mobile
cp .env.example .env
- Edit
.envand 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:
-
Go to "Application" → "Mobile"
-
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)
- Android:
-
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
-
Start the admin app:
cd apps/admin npm run dev -
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
-
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
-
Start the mobile app:
cd apps/mobile npm start -
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
-
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:
- Create a user in the admin app
- Try logging in with the same credentials in the mobile app
- 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_orpk_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
.envfile
Issue: Mobile app shows blank screen
Solution:
- Check the console logs for errors
- Verify
@clerk/clerk-expois installed correctly - Ensure
expo-secure-storeis installed (required for token storage) - Ensure
expo-web-browseris 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 flowsexpo-auth-session- SSO and session managementexpo-secure-store- Secure token storageexpo-crypto- Cryptographic operationsreact-dom- React DOM for web compatibilityreact-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_URLis set correctly - Clear browser cookies and try again
Issue: "ERESOLVE" errors during npm install
Solution:
- Use
--legacy-peer-depsflag: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
- In Clerk Dashboard, go to "Social Connections"
- Enable providers (Google, Facebook, etc.)
- Add OAuth credentials for each provider
- No code changes needed - Clerk handles it automatically!
Webhooks (Optional)
To sync Clerk users with your database:
- In Clerk Dashboard, go to "Webhooks"
- Add endpoint:
https://your-domain.com/api/webhooks/clerk - Select events:
user.created,user.updated,user.deleted - Implement webhook handler in
apps/admin/src/app/api/webhooks/clerk/route.ts
Multi-tenant Support
For gym chains with multiple locations:
- Use Clerk Organizations feature
- Enable in Clerk Dashboard under "Organizations"
- Each gym becomes an organization
- Users can belong to multiple organizations
Security Best Practices
- Never commit
.envfiles - They're in.gitignoreby default - Use different keys for development and production
- Enable MFA for admin accounts in Clerk Dashboard
- Set up rate limiting for API routes
- Regularly rotate API keys in production
- Use HTTPS in production (required for OAuth)
- Enable session security features in Clerk Dashboard
Next Steps
After successfully setting up Clerk:
- ✅ Test authentication flows in both apps
- ✅ Customize the sign-in/sign-up experience
- ✅ Set up user roles and permissions
- 🔄 Implement payment system integration
- 🔄 Add attendance tracking with Clerk user IDs
- 🔄 Set up webhook handlers for user sync
- 🔄 Configure production environment variables
- 🔄 Deploy to production with proper SSL/HTTPS
Resources
- Clerk Documentation: https://clerk.com/docs
- Next.js Integration Guide: https://clerk.com/docs/quickstarts/nextjs
- Expo Integration Guide: https://clerk.com/docs/quickstarts/expo
- Clerk Dashboard: https://dashboard.clerk.com
- Clerk Discord Community: https://clerk.com/discord
Support
If you encounter issues not covered in this guide:
- Check the Clerk documentation
- Search Clerk's Discord community
- Review the troubleshooting section above
- 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 interactionsexpo-auth-session: SSO and authentication sessionsexpo-secure-store: Secure token storageexpo-crypto: Cryptographic functionsreact-dom: React DOM for web compatibilityreact-native-web: React Native web compatibility layerexpo-constants: App configurationexpo-linking: Deep linking supportexpo-status-bar: Status bar styling (optional)