Skip to Content
DocsAuthenticationClerk Authentication

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

  1. Go to clerk.com  and create an account
  2. Create a new application in your Clerk dashboard
  3. Go to “API Keys” section and copy:
    • Publishable Key (starts with pk_test_)
    • Secret Key (starts with sk_test_)

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_here

3. How It Works in the Template

The template includes pre-configured authentication:

  • Layout Integration: app/layout.tsx includes ClerkProvider wrapper
  • Sign-in Page: app/sign-in/[[...sign-in]]/page.tsx with customized styling
  • Sign-up Page: app/sign-up/[[...sign-up]]/page.tsx with customized styling
  • Middleware: middleware.ts protects 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 protection

User 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.emailAddress

Server-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/user handles user creation and updates
  • Hook: use-sync-user.ts manages the sync process
  • Component: user-sync-provider.tsx wraps 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 database
  • GET /api/user - Get current user information
  • GET /api/user/subscription - Get user subscription status
  • GET /api/user/payments - Get user payment history

Authentication Flow

The template handles the complete authentication flow:

Sign-In Process

  1. User visits /sign-in
  2. Clerk authentication form appears
  3. After sign-in, redirected to /dashboard
  4. User data automatically synced to database

Sign-Up Process

  1. User visits /sign-up
  2. Completes registration form
  3. Email verification (configured in Clerk)
  4. Redirected to dashboard
  5. User record created in database
  6. 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_here

User 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

  1. Domain Configuration: Set up your domain in Clerk dashboard
  2. Email Templates: Customize verification and welcome emails
  3. Social Providers: Enable Google, GitHub, etc.
  4. Multi-factor Authentication: Enable TOTP/SMS in dashboard
  5. Session Settings: Configure session duration and security

User Profile Fields

Clerk automatically provides:

  • user.firstName
  • user.lastName
  • user.emailAddress
  • user.imageUrl
  • user.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/user is 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
Last updated on