Complete Clerk integration skill pack with 24 skills covering authentication, user management, embeddable UIs, and identity platform. Flagship tier vendor pack.
Installation
Open Claude Code and run this command:
/plugin install clerk-pack@claude-code-plugins-plus
Use --global to install for all projects, or --project for current project only.
Skills (24)
Configure Clerk CI/CD integration with GitHub Actions and testing.
Clerk CI Integration
Overview
Set up CI/CD pipelines with Clerk authentication testing. Covers GitHub Actions workflows, Playwright E2E tests with Clerk auth, test user management, and CI secrets configuration.
Prerequisites
- GitHub repository with Actions enabled
- Clerk test API keys (
pktest/sktest) - npm/pnpm project configured
Instructions
Step 1: GitHub Actions Workflow
# .github/workflows/test.yml
name: Test with Clerk Auth
on:
pull_request:
branches: [main]
push:
branches: [main]
jobs:
test:
runs-on: ubuntu-latest
env:
NEXT_PUBLIC_CLERK_PUBLISHABLE_KEY: ${{ secrets.CLERK_PK_TEST }}
CLERK_SECRET_KEY: ${{ secrets.CLERK_SK_TEST }}
CLERK_WEBHOOK_SECRET: ${{ secrets.CLERK_WEBHOOK_SECRET_TEST }}
steps:
- uses: actions/checkout@v4
- uses: actions/setup-node@v4
with:
node-version: 20
cache: npm
- run: npm ci
- run: npm run build
- run: npm test
- name: Install Playwright
run: npx playwright install --with-deps chromium
- name: Run E2E tests
run: npx playwright test
env:
CLERK_TEST_USER_EMAIL: ${{ secrets.CLERK_TEST_USER_EMAIL }}
CLERK_TEST_USER_PASSWORD: ${{ secrets.CLERK_TEST_USER_PASSWORD }}
Step 2: Configure GitHub Secrets
Add these secrets in GitHub repo > Settings > Secrets:
| Secret | Value |
|---|---|
CLERKPKTEST |
pktest... from dev instance |
CLERKSKTEST |
sktest... from dev instance |
CLERKWEBHOOKSECRET_TEST |
whsec_... from dev webhooks |
CLERKTESTUSER_EMAIL |
ci-test@yourapp.com |
CLERKTESTUSER_PASSWORD |
Strong test password |
Step 3: Playwright Auth Setup
// e2e/auth.setup.ts
import { test as setup, expect } from '@playwright/test'
import path from 'path'
const authFile = path.join(__dirname, '.auth/user.json')
setup('authenticate', async ({ page }) => {
await page.goto('/sign-in')
// Fill Clerk sign-in form
await page.fill('input[name="identifier"]', process.env.CLERK_TEST_USER_EMAIL!)
await page.click('button:has-text("Continue")')
await page.fill('input[name="password"]', process.env.CLERK_TEST_USER_PASSWORD!)
await page.click('button:has-text("Continue")')
// Wait for redirect to authenticated page
await page.waitForURL('/dashboard')
await eTroubleshoot common Clerk errors and issues.
Clerk Common Errors
Overview
Diagnose and resolve common Clerk authentication errors. Organized by error category with root cause analysis and fix code.
Prerequisites
- Clerk SDK installed
- Access to Clerk Dashboard for configuration verification
- Browser developer tools for client-side debugging
Instructions
Error Category 1: Configuration Errors
Clerk: Missing publishableKey
// Cause: ClerkProvider not receiving key
// Fix: Ensure env var is set and accessible
// .env.local
NEXT_PUBLIC_CLERK_PUBLISHABLE_KEY=pk_test_...
// Verify in code:
console.log('PK:', process.env.NEXT_PUBLIC_CLERK_PUBLISHABLE_KEY) // Should not be undefined
ClerkProvider must wrap your application
// Cause: Clerk hook used outside provider
// Fix: Wrap root layout with ClerkProvider
// app/layout.tsx
import { ClerkProvider } from '@clerk/nextjs'
export default function RootLayout({ children }: { children: React.ReactNode }) {
return (
<ClerkProvider>
<html><body>{children}</body></html>
</ClerkProvider>
)
}
Error Category 2: Authentication Errors
formidentifiernot_found
// Cause: Email not registered in Clerk instance
// Fix: Check correct Clerk instance (dev vs prod) and user exists
// Diagnostic:
import { createClerkClient } from '@clerk/backend'
const clerk = createClerkClient({ secretKey: process.env.CLERK_SECRET_KEY! })
const users = await clerk.users.getUserList({ emailAddress: ['user@example.com'] })
console.log('User found:', users.totalCount > 0)
formpasswordincorrect
// Cause: Wrong password or user set up with OAuth only
// Fix: Check auth strategy in Clerk Dashboard
// User may need password reset:
// Dashboard > Users > Select user > Authentication > Reset password
session_exists (Error during sign-in)
// Cause: User already has active session
// Fix: Sign out first or redirect
'use client'
import { useAuth } from '@clerk/nextjs'
import { redirect } from 'next/navigation'
export default function SignInPage() {
const { isSignedIn } = useAuth()
if (isSignedIn) redirect('/dashboard')
// ... render sign-in form
}
Error Category 3: Middleware Errors
Infinite redirect loop
// Cause: Sign-in page not in public routes
// Fix: Add auth pages to public route matcher
import { clerkMiddleware, createRouteMatcher } from '@Implement user sign-up and sign-in flows with Clerk.
Clerk Core Workflow A: Sign-Up & Sign-In
Overview
Implement authentication flows with Clerk: pre-built components for rapid setup, custom forms for full UI control, OAuth social login, email/phone verification, and multi-factor authentication.
Prerequisites
- Clerk SDK installed and configured (
clerk-install-authcompleted) - OAuth providers enabled in Dashboard > User & Authentication > Social Connections
- Sign-in/sign-up environment variables set
Instructions
Step 1: Pre-Built Components (Quick Start)
// app/sign-in/[[...sign-in]]/page.tsx
import { SignIn } from '@clerk/nextjs'
export default function SignInPage() {
return (
<div className="flex min-h-screen items-center justify-center">
<SignIn
appearance={{
elements: {
rootBox: 'mx-auto',
card: 'shadow-xl rounded-2xl',
headerTitle: 'text-2xl',
socialButtonsBlockButton: 'rounded-lg',
},
}}
routing="path"
path="/sign-in"
signUpUrl="/sign-up"
/>
</div>
)
}
// app/sign-up/[[...sign-up]]/page.tsx
import { SignUp } from '@clerk/nextjs'
export default function SignUpPage() {
return (
<div className="flex min-h-screen items-center justify-center">
<SignUp routing="path" path="/sign-up" signInUrl="/sign-in" />
</div>
)
}
# .env.local — routing configuration
NEXT_PUBLIC_CLERK_SIGN_IN_URL=/sign-in
NEXT_PUBLIC_CLERK_SIGN_UP_URL=/sign-up
NEXT_PUBLIC_CLERK_AFTER_SIGN_IN_URL=/dashboard
NEXT_PUBLIC_CLERK_AFTER_SIGN_UP_URL=/onboarding
Step 2: Custom Sign-In Form (Full UI Control)
'use client'
import { useSignIn } from '@clerk/nextjs'
import { useRouter } from 'next/navigation'
import { useState } from 'react'
export function CustomSignIn() {
const { signIn, setActive, isLoaded } = useSignIn()
const router = useRouter()
const [email, setEmail] = useState('')
const [password, setPassword] = useState('')
const [error, setError] = useState('')
const [loading, setLoading] = useState(false)
if (!isLoaded) return null
const handleSubmit = async (e: React.FormEvent) => {
e.preventDefault()
setError('')
setLoading(true)
try {
const result = await signIn.create({
identifier: email,
password,
})
if (result.status === 'complete') {
// Session created — activate it and redirect
await setActive({ session: result.createdSessionId })
router.push('/dashboard')
Implement session management and middleware with Clerk.
Clerk Core Workflow B: Session & Middleware
Overview
Implement session management and route protection with Clerk middleware. Covers clerkMiddleware() configuration, auth() patterns, custom session claims, JWT templates for external services, organization-scoped sessions, and session token v2.
Prerequisites
@clerk/nextjsinstalled with ClerkProvider wrapping the app- Next.js 14+ with App Router
- Sign-in/sign-up flows working (
clerk-core-workflow-acompleted)
Instructions
Step 1: Configure clerkMiddleware with Route Matchers
// middleware.ts (project root)
import { clerkMiddleware, createRouteMatcher } from '@clerk/nextjs/server'
const isPublicRoute = createRouteMatcher([
'/',
'/sign-in(.*)',
'/sign-up(.*)',
'/api/webhooks(.*)',
'/pricing',
'/blog(.*)',
])
const isAdminRoute = createRouteMatcher(['/admin(.*)'])
const isApiRoute = createRouteMatcher(['/api(.*)'])
export default clerkMiddleware(async (auth, req) => {
// Public routes: no auth required
if (isPublicRoute(req)) return
// Admin routes: require org:admin role
if (isAdminRoute(req)) {
await auth.protect({ role: 'org:admin' })
return
}
// All other routes: require authentication
await auth.protect()
})
export const config = {
matcher: [
'/((?!_next|[^?]*\\.(?:html?|css|js(?!on)|jpe?g|webp|png|gif|svg|ttf|woff2?|ico|csv|docx?|xlsx?|zip|webmanifest)).*)',
'/(api|trpc)(.*)',
],
}
Key behavior: clerkMiddleware() does NOT protect any routes by default. You must explicitly call auth.protect() for routes that require authentication. This is a design decision to avoid over-blocking.
Step 2: Protect API Routes with auth()
// app/api/data/route.ts
import { auth } from '@clerk/nextjs/server'
export async function GET() {
const { userId, orgId, has } = await auth()
if (!userId) {
return Response.json({ error: 'Unauthorized' }, { status: 401 })
}
// Permission-based authorization
if (!has({ permission: 'org:data:read' })) {
return Response.json({ error: 'Forbidden' }, { status: 403 })
}
const data = orgId
? await db.items.findMany({ where: { organizationId: orgId } })
: await db.items.findMany({ where: { ownerId: userId } })
return Response.json({ data, userId, orgId })
}
export async function POST(req: Request) {
const { userId, orgId, has } = await auth()
if (!userId) return Response.json({ error: 'Unauthorized' }, { status: 401 })
if (!has({ permission: 'org:data:write' })) {
return Response.json({ error: 'Forbidden' }, { status: 403 })
}
const body = await req.json(Optimize Clerk costs and understand pricing.
Clerk Cost Tuning
Overview
Understand Clerk pricing and optimize costs. Clerk charges by Monthly Active Users (MAU). Covers pricing tiers, MAU reduction strategies, caching to reduce API calls, and usage monitoring.
Prerequisites
- Clerk account active
- Understanding of MAU (Monthly Active Users)
- Application usage patterns known
Instructions
Step 1: Understand Clerk Pricing Model
| Plan | Price | MAU Included | Extra MAU |
|---|---|---|---|
| Free | $0/mo | 10,000 MAU | N/A |
| Pro | $25/mo | 10,000 MAU | $0.02/MAU |
| Enterprise | Custom | Custom | Custom |
Key pricing concepts:
- MAU = unique user who authenticates at least once per month
- Users who only visit public pages are not counted
- Bot/crawler sessions are not counted
- Test/development instances are free and unlimited
Step 2: Reduce MAU Count
// Strategy 1: Defer authentication — don't force sign-in until necessary
// middleware.ts
import { clerkMiddleware, createRouteMatcher } from '@clerk/nextjs/server'
const requiresAuth = createRouteMatcher([
'/dashboard(.*)',
'/settings(.*)',
'/api/protected(.*)',
])
export default clerkMiddleware(async (auth, req) => {
// Only require auth for specific routes (not entire site)
if (requiresAuth(req)) {
await auth.protect()
}
})
// Strategy 2: Use anonymous access for read-only features
// app/blog/[slug]/page.tsx
import { auth } from '@clerk/nextjs/server'
export default async function BlogPost({ params }: { params: { slug: string } }) {
const { userId } = await auth() // Check but don't require
const post = await db.post.findUnique({ where: { slug: params.slug } })
return (
<article>
<h1>{post?.title}</h1>
<div>{post?.content}</div>
{userId ? <CommentForm /> : <p>Sign in to comment</p>}
</article>
)
}
Step 3: Cache to Reduce API Calls
// lib/user-cache.ts
import { cache } from 'react'
import { currentUser } from '@clerk/nextjs/server'
// Deduplicate within single request (free)
export const getUser = cache(async () => {
return currentUser()
})
// Cross-request caching reduces Backend API calls
import { unstable_cache } from 'next/cache'
import { clerkClient } from '@clerk/nextjs/server'
export const getUserMetadata = unstable_cache(
async (userId: string) => {
const client = await clerkClient()
const user = await client.users.getUser(userId)
return user.publicMetadHandle user data, privacy, and GDPR compliance with Clerk.
Clerk Data Handling
Overview
Manage user data, implement privacy features, and ensure GDPR/CCPA compliance using the Clerk Backend API. Covers data export, right to be forgotten, consent management, and audit logging.
Prerequisites
- Clerk integration working
- Understanding of GDPR/CCPA requirements
- Database with user-related data linked by Clerk user IDs
Instructions
Step 1: User Data Export
// app/api/privacy/export/route.ts
import { auth, clerkClient } from '@clerk/nextjs/server'
export async function GET() {
const { userId } = await auth()
if (!userId) return Response.json({ error: 'Unauthorized' }, { status: 401 })
const client = await clerkClient()
const clerkUser = await client.users.getUser(userId)
// Gather data from Clerk
const clerkData = {
id: clerkUser.id,
emails: clerkUser.emailAddresses.map((e) => e.emailAddress),
firstName: clerkUser.firstName,
lastName: clerkUser.lastName,
createdAt: clerkUser.createdAt,
lastSignInAt: clerkUser.lastSignInAt,
publicMetadata: clerkUser.publicMetadata,
}
// Gather data from your database
const appData = await db.user.findUnique({
where: { clerkId: userId },
include: { posts: true, comments: true, preferences: true },
})
return Response.json({
exportDate: new Date().toISOString(),
clerkProfile: clerkData,
applicationData: appData,
})
}
Step 2: User Deletion (Right to be Forgotten)
// app/api/privacy/delete/route.ts
import { auth, clerkClient } from '@clerk/nextjs/server'
export async function DELETE() {
const { userId } = await auth()
if (!userId) return Response.json({ error: 'Unauthorized' }, { status: 401 })
const deletionLog: { step: string; status: string }[] = []
try {
// 1. Delete application data first
await db.comment.deleteMany({ where: { authorId: userId } })
deletionLog.push({ step: 'comments', status: 'deleted' })
await db.post.deleteMany({ where: { authorId: userId } })
deletionLog.push({ step: 'posts', status: 'deleted' })
await db.user.delete({ where: { clerkId: userId } })
deletionLog.push({ step: 'app_user', status: 'deleted' })
// 2. Delete from Clerk (this ends the session)
const client = await clerkClient()
await client.users.deleteUser(userId)
deletionLog.push({ step: 'clerk_user', status: 'deleted' })
// 3. Log deletion for compliance audit trail
await db.auditLog.create({
data: {
action: 'USER_DELETED',
subjectId: userId,
details: JSON.stringify(deletionLog),
timestamp: new Date(),
},
})
return Response.json({ deleted: true, log: deletionLog })
} catch (error) {
return Response.json({ error: 'Collect comprehensive debug information for Clerk issues.
Clerk Debug Bundle
Current State
!node --version 2>/dev/null || echo 'N/A'
!npm list @clerk/nextjs @clerk/clerk-react @clerk/express 2>/dev/null | grep clerk || echo 'No Clerk packages found'
Overview
Collect all necessary debug information for Clerk troubleshooting and support tickets. Generates an environment report, runtime health check, client-side debug panel, and support bundle.
Prerequisites
- Clerk SDK installed
- Access to application logs
- Browser with developer tools
Instructions
Step 1: Environment Debug Script
// scripts/clerk-debug.ts
import { createClerkClient } from '@clerk/backend'
async function collectDebugInfo() {
const info: Record<string, any> = {
timestamp: new Date().toISOString(),
nodeVersion: process.version,
platform: process.platform,
env: {
hasPK: !!process.env.NEXT_PUBLIC_CLERK_PUBLISHABLE_KEY,
hasSK: !!process.env.CLERK_SECRET_KEY,
pkPrefix: process.env.NEXT_PUBLIC_CLERK_PUBLISHABLE_KEY?.slice(0, 8) + '...',
nodeEnv: process.env.NODE_ENV,
},
}
// Test API connectivity
try {
const clerk = createClerkClient({ secretKey: process.env.CLERK_SECRET_KEY! })
const users = await clerk.users.getUserList({ limit: 1 })
info.apiConnectivity = { status: 'ok', userCount: users.totalCount }
} catch (err: any) {
info.apiConnectivity = { status: 'error', message: err.message, code: err.status }
}
// Check package versions
try {
const pkg = require('./package.json')
info.packages = Object.entries(pkg.dependencies || {})
.filter(([k]) => k.includes('clerk'))
.reduce((acc, [k, v]) => ({ ...acc, [k]: v }), {})
} catch {
info.packages = 'Could not read package.json'
}
console.log(JSON.stringify(info, null, 2))
return info
}
collectDebugInfo()
Run with:
npx tsx scripts/clerk-debug.ts
Step 2: Runtime Health Check Endpoint
// app/api/clerk-health/route.ts
import { auth, clerkClient } from '@clerk/nextjs/server'
export async function GET() {
const checks: Record<string, { status: string; detail?: string }> = {}
// Check 1: SDK loaded
checks.sdk = { status: 'ok', detail: 'Clerk SDK loaded' }
// Check 2: Auth function works
try {
const { userId } = await auth()
checks.auth = { status: 'ok', detail: userId ? `Authenticated as ${userId}` : 'Not authenticated (expected for health check)' }
} catch (err: any) {
checks.auth = { status: 'error', detail: err.message }
}
// Check 3: Backend API connectivity
try {
const client = await clerkClient()
await client.users.getUserList({ limit: 1 })
checks.backenConfigure Clerk for deployment on various platforms.
Clerk Deploy Integration
Overview
Deploy Clerk-authenticated applications to Vercel, Netlify, Railway, and other hosting platforms. Covers environment variable configuration, domain setup, and webhook endpoint configuration.
Prerequisites
- Clerk production instance with
pklive/sklivekeys - Production domain configured
- Hosting platform account
Instructions
Step 1: Vercel Deployment
# Add Clerk env vars to Vercel
vercel env add NEXT_PUBLIC_CLERK_PUBLISHABLE_KEY production
# Paste: pk_live_...
vercel env add CLERK_SECRET_KEY production
# Paste: sk_live_...
vercel env add CLERK_WEBHOOK_SECRET production
# Paste: whsec_...
# Add for preview deployments too
vercel env add NEXT_PUBLIC_CLERK_PUBLISHABLE_KEY preview
vercel env add CLERK_SECRET_KEY preview
Configure Clerk Dashboard for Vercel:
- Go to Dashboard > Domains and add your production domain
- Set Home URL:
https://myapp.com - Set Sign-in URL:
https://myapp.com/sign-in - Set Sign-up URL:
https://myapp.com/sign-up - Set After sign-in URL:
https://myapp.com/dashboard
Step 2: Netlify Deployment
# Add env vars via Netlify CLI
netlify env:set NEXT_PUBLIC_CLERK_PUBLISHABLE_KEY pk_live_...
netlify env:set CLERK_SECRET_KEY sk_live_...
For Netlify Functions (serverless API routes):
// netlify/functions/clerk-auth.ts
import { createClerkClient } from '@clerk/backend'
const clerk = createClerkClient({ secretKey: process.env.CLERK_SECRET_KEY! })
export async function handler(event: any) {
const token = event.headers.authorization?.replace('Bearer ', '')
if (!token) {
return { statusCode: 401, body: JSON.stringify({ error: 'No token' }) }
}
try {
const session = await clerk.sessions.verifySession(token, token)
return {
statusCode: 200,
body: JSON.stringify({ userId: session.userId }),
}
} catch {
return { statusCode: 401, body: JSON.stringify({ error: 'Invalid token' }) }
}
}
Step 3: Railway Deployment
# Set env vars via Railway CLI
railway variables set NEXT_PUBLIC_CLERK_PUBLISHABLE_KEY=pk_live_...
railway variables set CLERK_SECRET_KEY=sk_live_...
railway variables set CLERK_WEBHOOK_SECRET=whsec_...
Step 4: Docker Deployment
# Dockerfile
FROM node:20-alpine AS builder
WORKDIR /app
COPY package*.json ./
RUN npm ci
COPY . .
# Build-time env vars (public key only)
ARG NEXT_PUBLIC_CLERK_PUBLISHABLE_KEY
ENV NEXT_PUBLIC_CLERK_PUBLISHABLE_KEY=$NEXT_PUBLIC_CLERK_PUBLISConfigure enterprise SSO, role-based access control, and organization management.
Clerk Enterprise RBAC
Overview
Implement enterprise-grade role-based access control, organization management, and SSO with Clerk. Covers custom roles and permissions, organization lifecycle, multi-tenant access patterns, SAML/OIDC SSO, and the Backend API for programmatic role management (released Nov 2025).
Prerequisites
- Clerk Pro or Enterprise plan (Organizations + SSO require paid plan)
- Organizations feature enabled in Clerk Dashboard > Organizations > Settings
- Next.js 14+ with App Router (examples use
@clerk/nextjs)
Instructions
Step 1: Enable Organizations and Add UI Components
// app/org-selector/page.tsx
import { OrganizationSwitcher, OrganizationProfile } from '@clerk/nextjs'
export default function OrgPage() {
return (
<div className="p-8">
<h1>Select Organization</h1>
<OrganizationSwitcher
hidePersonal={false}
afterSelectOrganizationUrl="/dashboard"
afterCreateOrganizationUrl="/dashboard"
/>
<div className="mt-8">
<OrganizationProfile />
</div>
</div>
)
}
Step 2: Define Custom Roles and Permissions
Configure in Clerk Dashboard > Organizations > Roles and Permissions.
Default roles (built-in):
| Role | Key | Built-in Permissions |
|---|---|---|
| Admin | org:admin |
Full org management (members, settings, billing) |
| Member | org:member |
View org, read-only access |
Custom permissions (create in Dashboard > Organizations > Permissions):
| Permission | Key | Description |
|---|---|---|
| Read data | org:data:read |
View organization resources |
| Write data | org:data:write |
Create/update resources |
| Delete data | org:data:delete |
Delete resources |
| Manage billing | org:billing:manage |
Access billing settings |
| View analytics | org:analytics:read |
Access analytics dashboard |
Custom roles (create in Dashboard > Organizations > Roles):
| Role | Permissions | Use Case | |||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
org:manager |
data:read, data:write, analytics:read |
Content managers | |||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
org:viewer |
data:read |
Read-only stakeholder
Create your first authenticated request with Clerk.
ReadWriteEditBash(npm:*)Grep
Clerk Hello WorldOverviewMake your first authenticated requests using Clerk across server components, client components, API routes, and server actions. Validates your Clerk integration end-to-end. Prerequisites
InstructionsStep 1: Server Component — auth() and currentUser()
Key distinction: Step 2: Protected API Route
Step 3: Client Component with HooksManage incident response for Clerk authentication issues.
ReadWriteEditBash(npm:*)Bash(curl:*)Grep
Clerk Incident RunbookOverviewProcedures for responding to Clerk-related incidents in production. Covers triage, emergency auth bypass, recovery scripts, and post-incident review. Prerequisites
InstructionsStep 1: Triage — Identify Incident Category
Quick diagnostic:
Step 2: Emergency Auth Bypass (Clerk Outage Only)
A Install and configure Clerk SDK/CLI authentication.
ReadWriteEditBash(npm:*)Bash(pnpm:*)Grep
Clerk Install & AuthOverviewSet up Clerk SDK and configure authentication for Next.js, React, or Express. This skill covers SDK installation, environment variables, ClerkProvider, middleware, and initial auth verification. Prerequisites
InstructionsStep 1: Install SDK for Your Framework
Step 2: Configure Environment Variables
Ensure
Step 3: Add ClerkProvider (Next.js App Router)
Step 4: Add MiddlewareSet up local development workflow with Clerk.
ReadWriteEditBash(npm:*)Bash(pnpm:*)Grep
Clerk Local Dev LoopOverviewConfigure an efficient local development workflow with Clerk authentication, including test users, hot reload, and mock auth for unit tests. Prerequisites
InstructionsStep 1: Configure Development InstanceCreate a separate Clerk development instance to isolate test data from production.
Clerk development instances provide:
Step 2: Set Up Test Users
Run with:
Step 3: Configure Hot Reload
Step 4: Development Scripts
Step 5Migrate from other authentication providers to Clerk.
ReadWriteEditBash(npm:*)Grep
Clerk Migration Deep DiveCurrent State! OverviewComprehensive guide to migrating from Auth0, Firebase Auth, Supabase Auth, or NextAuth to Clerk. Covers user data export, bulk import, parallel running, and phased migration. Prerequisites
InstructionsStep 1: Export Users from Current ProviderAuth0 Export:
NextAuth (Prisma) Export:
Step 2: Import Users to ClerkConfigure Clerk for multiple environments (dev, staging, production).
ReadWriteEditBash(npm:*)Grep
Clerk Multi-Environment SetupOverviewConfigure Clerk across development, staging, and production environments with separate instances, environment-aware configuration, and safe promotion workflows. Prerequisites
InstructionsStep 1: Create Clerk InstancesCreate separate Clerk instances in the Dashboard for each environment:
Step 2: Environment Configuration Files
Step 3: Environment-Aware Configuration
Step 4: Startup ValidationImplement monitoring, logging, and observability for Clerk authentication.
ReadWriteEditBash(npm:*)Grep
Clerk ObservabilityOverviewImplement monitoring, logging, and observability for Clerk authentication. Covers structured auth logging, middleware performance tracking, webhook event monitoring, Sentry integration, and health check endpoints. Prerequisites
InstructionsStep 1: Structured Authentication Event Logging
Step 2: Middleware Performance Monitoring
Step 3: Webhook Event TrackingOptimize Clerk authentication performance.
ReadWriteEditGrep
Clerk Performance TuningOverviewOptimize Clerk authentication for best performance. Covers middleware optimization, user data caching, token handling, lazy loading, and edge runtime configuration. Prerequisites
InstructionsStep 1: Optimize Middleware (Skip Static Assets)
Step 2: Cache User Data
For cross-request caching with
Step 3: Optimize Token HandlingProduction readiness checklist for Clerk deployment.
ReadWriteEditGrepBash(npm:*)
Clerk Production ChecklistOverviewComplete checklist to ensure your Clerk integration is production-ready. Covers environment config, security hardening, monitoring, error handling, and compliance. Prerequisites
InstructionsStep 1: Environment Configuration Checklist
Step 2: Validation ScriptUnderstand and manage Clerk rate limits and quotas.
ReadWriteEditGrep
Clerk Rate LimitsOverviewUnderstand Clerk's rate limiting system and implement strategies to avoid hitting limits. Covers Backend API rate limits, retry logic, batching, caching, and monitoring. Prerequisites
InstructionsStep 1: Understand Rate LimitsClerk Backend API enforces rate limits per API key:
Rate limit headers returned on every response:
Step 2: Implement Rate Limit Handling with Retry
Step 3: Batch OperationsReference architecture patterns for Clerk authentication.
ReadWriteEditGrep
Clerk Reference ArchitectureOverviewReference architectures for implementing Clerk in common application patterns: Next.js full-stack, microservices with shared auth, multi-tenant SaaS, and mobile + web with shared backend. Prerequisites
InstructionsArchitecture 1: Next.js Full-Stack Application
Architecture 2: Microservices with Shared Auth
Common Clerk SDK patterns and best practices.
ReadWriteEditGrep
Clerk SDK PatternsOverviewCommon patterns and best practices for using the Clerk SDK effectively across server components, client components, API routes, and middleware. Prerequisites
InstructionsPattern 1: Server-Side Authentication
Pattern 2: Client-Side Hooks
Pattern 3: Protected Routes with Middleware
Pattern 4: Organization-Aware QuerieImplement security best practices with Clerk authentication.
ReadWriteEditGrep
Clerk Security BasicsOverviewImplement security best practices for Clerk authentication: environment variable protection, middleware hardening, API route defense, webhook verification, and session security. Prerequisites
InstructionsStep 1: Secure Environment Variables
Validate at startup that secret keys are not leaked:
Step 2: Hardened Middleware Configuration
Step 3: Secure API RoutesManage Clerk SDK version upgrades and handle breaking changes.
ReadWriteEditBash(npm:*)Bash(pnpm:*)Grep
Clerk Upgrade & MigrationCurrent State! OverviewSafely upgrade Clerk SDK versions and handle breaking changes. Covers version checking, upgrade procedures, common migration patterns, and rollback planning. Prerequisites
InstructionsStep 1: Check Current Version and Available Updates
Step 2: Review Breaking Changes
Key version milestones to watch for:
Step 3: Upgrade Process
Step 4: Handle Common Migration Patternsv5 to v6:
Find all affected files:
v5 to v6: Middleware migration
v5 t Configure Clerk webhooks and handle authentication events.
ReadWriteEditBash(npm:*)Grep
Clerk Webhooks & EventsOverviewConfigure and handle Clerk webhooks for user lifecycle events and data synchronization. Clerk uses Svix for webhook delivery with HMAC-SHA256 signature verification. As of 2025, Clerk provides a built-in Prerequisites
InstructionsStep 1: Install Dependencies
Step 2: Create Webhook Endpoint (verifyWebhook — Recommended)
Step 2 (Alternative): Manual Svix Verification
Step 3: Implement Event HReady to use clerk-pack?Related Pluginsaccess-control-auditorAudit access control implementations authentication-validatorValidate authentication implementations compliance-report-generatorGenerate compliance reports cors-policy-validatorValidate CORS policies csrf-protection-validatorValidate CSRF protection data-privacy-scannerScan for data privacy issues
Tags
clerkauthenticationauthusersidentityssoembeddable-uiuser-management
|