Clerk Auth Studio
All-in-one skill covering expert, patterns, clerk, auth. Includes structured workflows, validation checks, and reusable patterns for development.
Clerk Authentication Skill
A Claude Code skill for implementing Clerk authentication in Next.js applications, covering provider setup, protected routes, user management, middleware configuration, and webhook handling.
When to Use This Skill
Choose this skill when:
- Adding authentication to a new or existing Next.js application
- Implementing sign-in, sign-up, and user profile flows
- Protecting API routes and pages with authentication middleware
- Handling Clerk webhooks for user lifecycle events
- Integrating Clerk with your backend user database
- Setting up multi-tenant or organization-based access control
Consider alternatives when:
- You need a self-hosted auth solution (use NextAuth/Auth.js)
- You need authentication for non-JavaScript frameworks (check Clerk's framework support)
- You need simple API key authentication without user accounts
Quick Start
# Install Clerk SDK npm install @clerk/nextjs # Set environment variables echo 'NEXT_PUBLIC_CLERK_PUBLISHABLE_KEY=pk_test_...' >> .env.local echo 'CLERK_SECRET_KEY=sk_test_...' >> .env.local
// app/layout.tsx - Wrap your app with ClerkProvider import { ClerkProvider } from '@clerk/nextjs'; export default function RootLayout({ children }: { children: React.ReactNode }) { return ( <ClerkProvider> <html lang="en"> <body>{children}</body> </html> </ClerkProvider> ); }
// middleware.ts - Protect routes import { clerkMiddleware, createRouteMatcher } from '@clerk/nextjs/server'; const isPublicRoute = createRouteMatcher([ '/', '/sign-in(.*)', '/sign-up(.*)', '/api/webhooks(.*)' ]); export default clerkMiddleware(async (auth, request) => { if (!isPublicRoute(request)) { await auth.protect(); } }); export const config = { matcher: ['/((?!.*\\..*|_next).*)', '/', '/(api|trpc)(.*)'] };
Core Concepts
Authentication Components
| Component | Purpose | Usage |
|---|---|---|
<SignIn /> | Sign-in form with email, social, SSO | Place on /sign-in page |
<SignUp /> | Registration form with configurable fields | Place on /sign-up page |
<UserButton /> | Avatar dropdown with account management | Place in header/navbar |
<UserProfile /> | Full profile management page | Dedicated profile route |
<OrganizationSwitcher /> | Switch between organizations | Multi-tenant apps |
<Protect /> | Conditional rendering by auth state | Wrap protected UI sections |
Server-Side Auth
// App Router - Server Component import { currentUser, auth } from '@clerk/nextjs/server'; export default async function DashboardPage() { const user = await currentUser(); if (!user) redirect('/sign-in'); return <h1>Welcome, {user.firstName}</h1>; } // API Route import { auth } from '@clerk/nextjs/server'; import { NextResponse } from 'next/server'; export async function GET() { const { userId } = await auth(); if (!userId) { return NextResponse.json({ error: 'Unauthorized' }, { status: 401 }); } const data = await fetchUserData(userId); return NextResponse.json(data); }
Configuration
| Parameter | Type | Default | Description |
|---|---|---|---|
NEXT_PUBLIC_CLERK_PUBLISHABLE_KEY | string | — | Clerk publishable key (required) |
CLERK_SECRET_KEY | string | — | Clerk secret key for server-side operations (required) |
NEXT_PUBLIC_CLERK_SIGN_IN_URL | string | "/sign-in" | Custom sign-in page route |
NEXT_PUBLIC_CLERK_SIGN_UP_URL | string | "/sign-up" | Custom sign-up page route |
CLERK_WEBHOOK_SECRET | string | — | Webhook signing secret for verifying events |
NEXT_PUBLIC_CLERK_AFTER_SIGN_IN_URL | string | "/" | Redirect after successful sign-in |
NEXT_PUBLIC_CLERK_AFTER_SIGN_UP_URL | string | "/" | Redirect after successful sign-up |
Best Practices
-
Always use middleware for route protection — client-side checks can be bypassed; Clerk middleware runs at the edge before the page loads, providing reliable server-side protection for all routes.
-
Sync Clerk users with your database via webhooks — don't rely solely on Clerk for user data; set up the
user.createdwebhook to create a corresponding record in your database with the Clerk user ID as a foreign key. -
Use
auth()in server components and API routes — prefer the server-sideauth()function over client-side hooks for security-sensitive operations; it runs on the server where tokens cannot be tampered with. -
Configure public routes explicitly — use
createRouteMatcherto whitelist public routes rather than trying to protect individual routes; this default-deny approach prevents accidentally exposing protected content. -
Handle the webhook verification correctly — always verify webhook signatures using
svixand theCLERK_WEBHOOK_SECRET; process events idempotently since webhooks can be delivered more than once.
Common Issues
Middleware redirect loop — This occurs when your sign-in page is not listed as a public route, causing unauthenticated users to be redirected to sign-in, which then redirects again. Add /sign-in(.*) and /sign-up(.*) to your public route matcher.
Missing environment variables in production — Clerk keys must be set in your production environment, not just .env.local. Check your deployment platform's environment variable settings and ensure both the publishable key and secret key are configured.
Webhook events arriving out of order — Clerk may send user.updated before user.created in rare cases. Make your webhook handler upsert users (create if not exists, update if exists) rather than assuming events arrive in order.
Reviews
No reviews yet. Be the first to review this template!
Similar Templates
Full-Stack Code Reviewer
Comprehensive code review skill that checks for security vulnerabilities, performance issues, accessibility, and best practices across frontend and backend code.
Test Suite Generator
Generates comprehensive test suites with unit tests, integration tests, and edge cases. Supports Jest, Vitest, Pytest, and Go testing.
Pro Architecture Workspace
Battle-tested skill for architectural, decision, making, framework. Includes structured workflows, validation checks, and reusable patterns for development.