clerk-common-errors
Troubleshoot common Clerk errors and issues. Use when encountering authentication errors, SDK issues, or configuration problems with Clerk. Trigger with phrases like "clerk error", "clerk not working", "clerk authentication failed", "clerk issue", "fix clerk".
What this skill does
# 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`**
```typescript
// 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`**
```typescript
// 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`**
```typescript
// 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`**
```typescript
// 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)**
```typescript
// 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**
```typescript
// 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`**
```typescript
// 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**
```typescript
// 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**
```typescript
// 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**
```typescript
// 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
| Error | Cause | Quick Fix |
|-------|-------|-----------|
| `Missing publishableKey` | Env var not set | Add `NEXT_PUBLIC_CLERK_PUBLISHABLE_KEY` to `.env.local` |
| `auth() not detected` | Middleware missing/misplaced | Move `middleware.ts` to project root |
| Redirect loop | Auth pages not public | Add sign-in/sign-up to `isPublicRoute` matcher |
| Hydration mismatch | Server/client state differs | Guard with `isLoaded` check |
| Webhook invalid signature | Body parsed before verify | Use `req.text()` not `req.json()` before `wh.verify()` |
## Examples
### Quick Diagnostic Checklist
```bash
# 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
- [Clerk Error Reference](https://clerk.com/docs/errors/overview)
- [Clerk Debugging Guide](https://clerk.com/docs/troubleshooting/overview)
- [Clerk Discord Community](https://clerk.com/discord)
## Next Steps
Proceed to `clerk-debug-bundle` for comprehensive debugging tools.
Related in Backend & APIs
jfrog
IncludedInteract with the JFrog Platform via the JFrog CLI and REST/GraphQL APIs. Use this skill when the user wants to manage Artifactory repositories, upload or download artifacts, manage builds, configure permissions, manage users and groups, work with access tokens, configure JFrog CLI servers, search artifacts, manage properties, set up replication, manage JFrog Projects, run security audits or scans, look up CVE details, query exposures scan results from JFrog Advanced Security, manage release bundles and lifecycle operations, aggregate or export platform data, or perform any JFrog Platform administration task. Also use when the user mentions jf, jfrog, artifactory, xray, distribution, evidence, apptrust, onemodel, graphql, workers, mission control, curation, advanced security, exposures, or any JFrog product name.
cupynumeric-migration-readiness
IncludedPre-migration readiness assessor for porting NumPy to cuPyNumeric. Use BEFORE substantial porting work begins when the user asks whether code will scale on GPU, whether they should migrate to cuPyNumeric, which NumPy patterns transfer cleanly, what must be refactored before porting, or mentions pre-port assessment, scaling analysis, or refactor planning. Inspect the user's source code, look up NumPy usage, cross-reference the cuPyNumeric API support manifest, and distinguish distributed-scaling-friendly patterns from blockers such as unsupported APIs, scalar synchronization, host round-trips, Python/object-heavy control flow, shape/data-dependent branching, and in-place mutation hazards. Produce a verdict of READY, LIGHT REFACTOR, SIGNIFICANT REFACTOR, or NOT RECOMMENDED, with concrete refactor pointers.
alibabacloud-data-agent-skill
IncludedInvoke Alibaba Cloud Apsara Data Agent for Analytics via CLI to perform natural language-driven data analysis on enterprise databases. Data Agent for Analytics is an intelligent data analysis agent developed by Alibaba Cloud Database team for enterprise users. It automatically completes requirement analysis, data understanding, analysis insights, and report generation based on natural language descriptions. This tool supports: discovering data resources (instances/databases/tables) managed in DMS, initiating query or deep analysis sessions, real-time progress tracking, and retrieving analysis conclusions and generated reports. Use this Skill when users need to query databases, analyze data trends, generate data reports, ask questions in natural language, or mention "Data Agent", "data analysis", "database query", "SQL analysis", "data insights".
token-optimizer
IncludedReduce OpenClaw token usage and API costs through smart model routing, heartbeat optimization, budget tracking, and native 2026.2.15 features (session pruning, bootstrap size limits, cache TTL alignment). Use when token costs are high, API rate limits are being hit, or hosting multiple agents at scale. The 4 executable scripts (context_optimizer, model_router, heartbeat_optimizer, token_tracker) are local-only — no network requests, no subprocess calls, no system modifications. Reference files (PROVIDERS.md, config-patches.json) document optional multi-provider strategies that require external API keys and network access if you choose to use them. See SECURITY.md for full breakdown.
resend-cli
IncludedUse this skill when the task is specifically about operating Resend from an AI agent, terminal session, or CI job via the official resend CLI: installing/authenticating the CLI, sending/listing/updating/cancelling emails, batch sends, domains and DNS, webhooks and local listeners, inbound receiving, contacts, topics, segments, broadcasts, templates, API keys, profiles, or debugging Resend CLI/API failures. Trigger on mentions of Resend CLI, `resend`, `resend doctor`, `resend emails send`, `resend domains`, `resend webhooks listen`, `resend emails receiving`, or agent-friendly terminal automation.
alibabacloud-odps-maxframe-coding
IncludedUse this skill for MaxFrame SDK development and documentation navigation on Alibaba Cloud MaxCompute (ODPS). Helps answer MaxFrame API, concept, official example, and supported pandas API questions; create data processing programs; read/write MaxCompute tables; debug jobs (remote or local); and build custom DPE runtime images. Trigger when users mention MaxFrame, MaxCompute with MaxFrame, ODPS table processing, DPE runtime, MaxFrame docs/examples, DataFrame/Tensor operations, or GPU runtime setup. Works for both English and Chinese queries about Alibaba Cloud data processing with MaxFrame.