Clerk Authentication
Clerk provides complete user management with customizable UI components, webhooks, and built-in security features. This module is already integrated in the template.
Overview
Clerk offers drop-in authentication components with customizable styling, comprehensive user management, and secure session handling.
Key Features:
- Pre-built authentication UI
- Social login providers
- User management dashboard
- Session management
- Webhooks for user events
- Multi-factor authentication
Getting Started
1. Get Your Clerk API Keys
- Go to clerk.com and create an account
- Create a new application in your Clerk dashboard
- Go to “API Keys” section and copy:
- Publishable Key (starts with
pk_test_) - Secret Key (starts with
sk_test_)
- Publishable Key (starts with
2. Add Environment Variables
Add these to your .env.local file:
NEXT_PUBLIC_CLERK_PUBLISHABLE_KEY=pk_test_your_publishable_key_here
CLERK_SECRET_KEY=sk_test_your_secret_key_here3. How It Works in the Template
The template includes pre-configured authentication:
- Layout Integration:
app/layout.tsxincludesClerkProviderwrapper - Sign-in Page:
app/sign-in/[[...sign-in]]/page.tsxwith customized styling - Sign-up Page:
app/sign-up/[[...sign-up]]/page.tsxwith customized styling - Middleware:
middleware.tsprotects dashboard routes - User Sync: Automatic user synchronization to your database
4. Template Structure
app/
├── layout.tsx # ClerkProvider wrapper
├── sign-in/[[...sign-in]]/ # Sign-in page with custom styling
├── sign-up/[[...sign-up]]/ # Sign-up page with custom styling
├── dashboard/ # Protected dashboard page
components/
├── user-sync-provider.tsx # User synchronization component
hooks/
├── use-sync-user.ts # User sync hook
lib/
├── sync-user.ts # User sync utility
middleware.ts # Route protectionUser Management Features
Accessing User Data
The template provides automatic user synchronization:
// In any client component
import { useUser } from '@clerk/nextjs'
const { user, isSignedIn } = useUser()
// User data is automatically synced to your database
// Access user info like: user.firstName, user.emailAddressServer-Side Access
// In API routes (already implemented in template)
import { auth } from '@clerk/nextjs'
const { userId } = auth()
if (!userId) {
return Response.json({ error: 'Unauthorized' }, { status: 401 })
}Automatic User Synchronization
The template automatically syncs users to your database:
- When users sign up: Creates user record in database
- When users sign in: Updates user information if changed
- API endpoint:
/api/userhandles user creation and updates - Hook:
use-sync-user.tsmanages the sync process - Component:
user-sync-provider.tsxwraps the app for auto-sync
Database Schema
The template includes user tables:
For Prisma templates (starterkit):
- Users table with Clerk ID mapping
- Subscriptions and payments tracking
For Supabase templates:
- Profiles table linked to auth.users
- Row Level Security policies
API Endpoints
POST /api/user- Sync user data to databaseGET /api/user- Get current user informationGET /api/user/subscription- Get user subscription statusGET /api/user/payments- Get user payment history
Authentication Flow
The template handles the complete authentication flow:
Sign-In Process
- User visits
/sign-in - Clerk authentication form appears
- After sign-in, redirected to
/dashboard - User data automatically synced to database
Sign-Up Process
- User visits
/sign-up - Completes registration form
- Email verification (configured in Clerk)
- Redirected to dashboard
- User record created in database
- Welcome email sent (if Resend is configured)
Sign-Out
Using the built-in user button or custom implementation:
import { SignOutButton } from '@clerk/nextjs'
<SignOutButton />Customization
Styling Authentication Pages
The template includes custom styling for sign-in/sign-up pages:
// app/sign-in/[[...sign-in]]/page.tsx
<SignIn
appearance={{
elements: {
formButtonPrimary: 'bg-primary hover:bg-primary/90',
card: 'shadow-none border',
}
}}
/>Adding Protected Routes
Update middleware.ts to protect additional routes:
const isProtectedRoute = createRouteMatcher([
'/dashboard(.*)',
'/settings(.*)', // Add new protected routes
'/profile(.*)'
])Environment Configuration
Add your Clerk keys to .env.local:
NEXT_PUBLIC_CLERK_PUBLISHABLE_KEY=pk_test_your_key_here
CLERK_SECRET_KEY=sk_test_your_secret_hereUser Button Integration
The template includes user management in the dashboard:
- User avatar and name display
- Sign-out functionality
- Profile management
- Account settings access
Advanced Configuration
Clerk Dashboard Settings
- Domain Configuration: Set up your domain in Clerk dashboard
- Email Templates: Customize verification and welcome emails
- Social Providers: Enable Google, GitHub, etc.
- Multi-factor Authentication: Enable TOTP/SMS in dashboard
- Session Settings: Configure session duration and security
User Profile Fields
Clerk automatically provides:
user.firstNameuser.lastNameuser.emailAddressuser.imageUrluser.id(Clerk user ID)
Troubleshooting
Authentication not working:
- Verify API keys in
.env.local - Check domain settings in Clerk dashboard
- Ensure middleware is configured correctly
User sync issues:
- Check API endpoint
/api/useris working - Verify database connection
- Look at browser console for sync errors
Redirect problems:
- Set correct redirect URLs in Clerk dashboard
- Check middleware route protection rules
Styling issues:
- Verify Tailwind classes in appearance props
- Check custom CSS conflicts