Overview
The authentication system consists of three main components:- Clerk - Handles user authentication and session management
- Convex - Provides authenticated backend operations
- Middleware - Protects routes and manages authentication state
Authentication Flow
Configure Clerk with Convex
Set up the Convex auth configuration to work with Clerk. This configuration is located in
convex/auth.config.ts:convex/auth.config.ts
Replace the domain with your Clerk instance URL. The
applicationID should match your Convex configuration.Set up the Convex Client Provider
Wrap your application with the authentication providers in This setup:
providers/convex-client-provider.tsx:providers/convex-client-provider.tsx
- Wraps the app with
ClerkProviderfor authentication - Connects Clerk with Convex using
ConvexProviderWithClerk - Shows content only when authenticated
- Displays a loading state during authentication
Add the provider to your layout
Include the
ConvexClientProvider in your root layout at app/layout.tsx:app/layout.tsx
Environment Variables
Ensure you have the following environment variables configured:Server-Side Authentication
To authenticate API routes or server actions, use Clerk’s server-side utilities:app/api/example/route.ts
Authentication States
The ConvexClientProvider handles three authentication states:| State | Component | Description |
|---|---|---|
| Authenticated | <Authenticated> | User is logged in and verified |
| Loading | <AuthLoading> | Checking authentication status |
| Unauthenticated | Default | User is redirected to sign-in |
Best Practices
Client vs Server: Use
useAuth() hook on the client and auth() function on the server for accessing authentication state.Troubleshooting
Users are not being authenticated
- Verify your Clerk environment variables are correct
- Check that the Clerk domain in
convex/auth.config.tsmatches your Clerk instance - Ensure the middleware matcher includes your protected routes
Convex queries fail with authentication errors
- Confirm
NEXT_PUBLIC_CONVEX_URLis set correctly - Verify the Convex deployment is linked to your Clerk application
- Check that
ConvexProviderWithClerkis wrapping your application properly
Next Steps
- Learn about Real-time Sync to add collaborative features
- Explore Customization to style your authentication UI