CL

clerk-common-errors

Diagnostic and fix instructions for Clerk authentication errors, including missing keys and provider configuration.

Install

mkdir -p .claude/skills/clerk-common-errors && curl -L -o skill.zip "https://agentskills.codes/api/skills/download/7088" && unzip -o skill.zip -d .claude/skills/clerk-common-errors && rm skill.zip

Installs to .claude/skills/clerk-common-errors

Activation

This is the description your AI agent reads to decide when to run this skill — the better it matches your request, the more reliably it fires.

Troubleshoot common Clerk errors and issues.
44 charsno explicit “when” trigger
Intermediate

Key capabilities

  • Diagnose Clerk configuration errors like missing publishable keys.
  • Resolve authentication errors such as 'form_identifier_not_found' or 'form_password_incorrect'.
  • Fix middleware issues, including infinite redirect loops and undetected middleware.
  • Address server/client component errors related to Clerk hooks and hydration mismatches.
  • Troubleshoot webhook errors like 'Invalid signature' by correcting body parsing.

How it works

The skill categorizes common Clerk errors and provides specific code fixes and diagnostic steps for each, covering configuration, authentication, middleware, server/client components, and webhooks.

Inputs & outputs

You give it
A Clerk-related error message or unexpected behavior in an application.
You get back
Identified error category, root cause, working fix code, and diagnostic steps.

When to use clerk-common-errors

  • Debugging Clerk provider errors
  • Fixing missing publishable key warnings
  • Troubleshooting form authentication failures
  • Validating environment variable setup for Clerk

About this skill

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

form_identifier_not_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: ['[email protected]'] })
console.log('User found:', users.totalCount > 0)

form_password_incorrect

// 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 '@clerk/nextjs/server'

const isPublicRoute = createRouteMatcher([
  '/sign-in(.*)',  // Must include sign-in
  '/sign-up(.*)',  // Must include sign-up
  '/',
  '/api/webhooks(.*)',
])

export default clerkMiddleware(async (auth, req) => {
  if (!isPublicRoute(req)) await auth.protect()
})

auth() was called but Clerk middleware was not detected

// Cause: middleware.ts not in correct location or matcher not matching
// Fix: Ensure middleware.ts is at project root (not inside app/ or src/)

// Verify matcher includes the route:
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)(.*)',
  ],
}

Error Category 4: Server/Client Component Errors

useUser() in Server Component

// Error: Hooks can only be called inside a Client Component
// Fix: Use auth()/currentUser() server-side, useUser() client-side

// Server Component (no 'use client'):
import { currentUser } from '@clerk/nextjs/server'
export default async function Page() {
  const user = await currentUser()
  return <div>{user?.firstName}</div>
}

// Client Component (with 'use client'):
'use client'
import { useUser } from '@clerk/nextjs'
export function Profile() {
  const { user } = useUser()
  return <div>{user?.firstName}</div>
}

Hydration mismatch with auth state

// Cause: Server renders unauthenticated, client has session
// Fix: Use ClerkLoaded or check isLoaded before rendering auth-dependent UI
'use client'
import { useUser } from '@clerk/nextjs'

export function SafeAuthUI() {
  const { user, isLoaded } = useUser()
  if (!isLoaded) return <div>Loading...</div> // Prevent hydration mismatch
  return <div>{user ? `Hello ${user.firstName}` : 'Not signed in'}</div>
}

Error Category 5: Webhook Errors

Invalid signature on webhook endpoint

// Cause: CLERK_WEBHOOK_SECRET mismatch or body parsing issue
// Fix 1: Verify secret matches Dashboard > Webhooks > Signing Secret
// Fix 2: Read raw body, don't use JSON middleware before verification

// Next.js App Router (correct):
export async function POST(req: Request) {
  const body = await req.text() // Use text(), not json()
  const wh = new Webhook(process.env.CLERK_WEBHOOK_SECRET!)
  const evt = wh.verify(body, { /* svix headers */ })
}

// Express (correct):
app.post('/webhooks', express.raw({ type: 'application/json' }), handler)
// NOT: app.post('/webhooks', express.json(), handler) // This breaks signature

Output

  • Identified error category and root cause
  • Working fix code for each common error
  • Diagnostic steps for verification

Error Handling

ErrorCauseQuick Fix
Missing publishableKeyEnv var not setAdd NEXT_PUBLIC_CLERK_PUBLISHABLE_KEY to .env.local
auth() not detectedMiddleware missing/misplacedMove middleware.ts to project root
Redirect loopAuth pages not publicAdd sign-in/sign-up to isPublicRoute matcher
Hydration mismatchServer/client state differsGuard with isLoaded check
Webhook invalid signatureBody parsed before verifyUse req.text() not req.json() before wh.verify()

Examples

Quick Diagnostic Checklist

# 1. Check Clerk packages are installed
npm list @clerk/nextjs 2>/dev/null

# 2. Verify env vars are set
node -e "console.log('PK:', !!process.env.NEXT_PUBLIC_CLERK_PUBLISHABLE_KEY, 'SK:', !!process.env.CLERK_SECRET_KEY)"

# 3. Test API connectivity
curl -s -o /dev/null -w "%{http_code}" -H "Authorization: Bearer $CLERK_SECRET_KEY" https://api.clerk.com/v1/users?limit=1

# 4. Check middleware exists at root
ls middleware.ts 2>/dev/null && echo "Found" || echo "Missing - create middleware.ts at project root"

Resources

Next Steps

Proceed to clerk-debug-bundle for comprehensive debugging tools.

When not to use it

  • When the issue is not related to Clerk authentication or SDK usage.
  • When the problem is outside of Clerk's configuration, authentication, middleware, or component interactions.

Prerequisites

Clerk SDK installedAccess to Clerk Dashboard for configuration verificationBrowser developer tools for client-side debugging

Limitations

  • The skill focuses only on Clerk-related errors.
  • The skill does not cover issues beyond configuration, authentication, middleware, component, or webhook problems.

How it compares

This skill offers targeted code examples and diagnostic commands for specific Clerk errors, unlike general debugging that requires manual investigation of error messages and documentation.

Compared to similar skills

clerk-common-errors side by side with the closest alternatives in the catalog.

SkillInstallsUpdatedSafetyDifficulty
clerk-common-errors (this skill)127dCautionIntermediate
nextjs-supabase-auth126moNo flagsIntermediate
better-auth59moReviewIntermediate
auth-patterns77moReviewIntermediate

Try saying

Example prompts that trigger this skill in your AI assistant.

More by jeremylongshore

View all by jeremylongshore

analyzing-logs

jeremylongshore

Analyze application logs to detect performance issues, identify error patterns, and improve stability by extracting key insights.

14123

ollama-setup

jeremylongshore

Configure auto-configure Ollama when user needs local LLM deployment, free AI alternatives, or wants to eliminate hosted API costs. Trigger phrases: "install ollama", "local AI", "free LLM", "self-hosted AI", "replace OpenAI", "no API costs". Use when appropriate context detected. Trigger with relevant phrases based on skill purpose.

1167

backtesting-trading-strategies

jeremylongshore

Backtest crypto and traditional trading strategies against historical data. Calculates performance metrics (Sharpe, Sortino, max drawdown), generates equity curves, and optimizes strategy parameters. Use when user wants to test a trading strategy, validate signals, or compare approaches. Trigger with phrases like "backtest strategy", "test trading strategy", "historical performance", "simulate trades", "optimize parameters", or "validate signals".

1071

generating-database-seed-data

jeremylongshore

Process this skill enables AI assistant to generate realistic test data and database seed scripts for development and testing environments. it uses faker libraries to create realistic data, maintains relational integrity, and allows configurable data volumes. u... Use when working with databases or data models. Trigger with phrases like 'database', 'query', or 'schema'.

1033

cursor-codebase-indexing

jeremylongshore

Execute set up and optimize Cursor codebase indexing. Triggers on "cursor index setup", "codebase indexing", "index codebase", "cursor semantic search". Use when working with cursor codebase indexing functionality. Trigger with phrases like "cursor codebase indexing", "cursor indexing", "cursor".

885

testing-mobile-apps

jeremylongshore

Execute mobile app testing on iOS and Android devices/simulators. Use when performing specialized testing. Trigger with phrases like "test mobile app", "run iOS tests", or "validate Android functionality".

810

You might also like

nextjs-supabase-auth

davila7

Expert integration of Supabase Auth with Next.js App Router Use when: supabase auth next, authentication next.js, login supabase, auth middleware, protected route.

1259

better-auth

mrgoonie

Implement authentication and authorization with Better Auth - a framework-agnostic TypeScript authentication framework. Features include email/password authentication with verification, OAuth providers (Google, GitHub, Discord, etc.), two-factor authentication (TOTP, SMS), passkeys/WebAuthn support, session management, role-based access control (RBAC), rate limiting, and database adapters. Use when adding authentication to applications, implementing OAuth flows, setting up 2FA/MFA, managing user sessions, configuring authorization rules, or building secure authentication systems for web applications.

527

auth-patterns

davepoon

This skill should be used when the user asks about "authentication in Next.js", "NextAuth", "Auth.js", "middleware auth", "protected routes", "session management", "JWT", "login flow", or needs guidance on implementing authentication and authorization in Next.js applications.

720

clerk-enterprise-rbac

jeremylongshore

Configure enterprise SSO, role-based access control, and organization management. Use when implementing SSO integration, configuring role-based permissions, or setting up organization-level controls. Trigger with phrases like "clerk SSO", "clerk RBAC", "clerk enterprise", "clerk roles", "clerk permissions", "clerk SAML".

14

clerk-performance-tuning

jeremylongshore

Optimize Clerk authentication performance. Use when improving auth response times, reducing latency, or optimizing Clerk SDK usage. Trigger with phrases like "clerk performance", "clerk optimization", "clerk slow", "clerk latency", "optimize clerk".

14

clerk-sdk-patterns

jeremylongshore

Common Clerk SDK patterns and best practices. Use when implementing authentication flows, accessing user data, or integrating Clerk SDK methods in your application. Trigger with phrases like "clerk SDK", "clerk patterns", "clerk best practices", "clerk API usage".

22

Search skills

Search the agent skills registry