C

Clerk Auth Studio

All-in-one skill covering expert, patterns, clerk, auth. Includes structured workflows, validation checks, and reusable patterns for development.

SkillClipticsdevelopmentv1.0.0MIT
0 views0 copies

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

ComponentPurposeUsage
<SignIn />Sign-in form with email, social, SSOPlace on /sign-in page
<SignUp />Registration form with configurable fieldsPlace on /sign-up page
<UserButton />Avatar dropdown with account managementPlace in header/navbar
<UserProfile />Full profile management pageDedicated profile route
<OrganizationSwitcher />Switch between organizationsMulti-tenant apps
<Protect />Conditional rendering by auth stateWrap 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

ParameterTypeDefaultDescription
NEXT_PUBLIC_CLERK_PUBLISHABLE_KEYstringClerk publishable key (required)
CLERK_SECRET_KEYstringClerk secret key for server-side operations (required)
NEXT_PUBLIC_CLERK_SIGN_IN_URLstring"/sign-in"Custom sign-in page route
NEXT_PUBLIC_CLERK_SIGN_UP_URLstring"/sign-up"Custom sign-up page route
CLERK_WEBHOOK_SECRETstringWebhook signing secret for verifying events
NEXT_PUBLIC_CLERK_AFTER_SIGN_IN_URLstring"/"Redirect after successful sign-in
NEXT_PUBLIC_CLERK_AFTER_SIGN_UP_URLstring"/"Redirect after successful sign-up

Best Practices

  1. 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.

  2. Sync Clerk users with your database via webhooks — don't rely solely on Clerk for user data; set up the user.created webhook to create a corresponding record in your database with the Clerk user ID as a foreign key.

  3. Use auth() in server components and API routes — prefer the server-side auth() function over client-side hooks for security-sensitive operations; it runs on the server where tokens cannot be tampered with.

  4. Configure public routes explicitly — use createRouteMatcher to whitelist public routes rather than trying to protect individual routes; this default-deny approach prevents accidentally exposing protected content.

  5. Handle the webhook verification correctly — always verify webhook signatures using svix and the CLERK_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.

Community

Reviews

Write a review

No reviews yet. Be the first to review this template!

Similar Templates