Skill站外收录 @skilllib/skill-2117939930272412931
clerk-common-errors
诊断并解决 Clerk 认证过程中常见的配置、会话、中间件及服务端错误,提供从密钥验证到 Webhook 签名处理的完整排查方案,适用于身份验证失败、重定向循环与跨环境状态不一致等场景。
文档处理 AI 技能
Skills.MD
# Clerk Common Errors
## Overview
Diagnose and resolve common Clerk authentication errors and issues.
## Prerequisites
- Clerk SDK installed
- Access to Clerk dashboard for configuration checks
- Browser developer tools for debugging
## Instructions
### Error Category 1: Configuration Errors
#### Invalid API Key
```
Error: Clerk: Invalid API key
```
**Cause:** Publishable or secret key is incorrect or mismatched.
**Solution:**
```bash
# Verify keys in .env.local match Clerk dashboard
# Publishable key starts with pk_test_ or pk_live_
# Secret key starts with sk_test_ or sk_live_
# Check for trailing whitespace
cat -A .env.local | grep CLERK
# Ensure correct environment
echo $NEXT_PUBLIC_CLERK_PUBLISHABLE_KEY
```
#### ClerkProvider Not Found
```
Error: useAuth can only be used within the <ClerkProvider /> component
```
**Cause:** Component using Clerk hooks is outside ClerkProvider.
**Solution:**
```typescript
// Ensure ClerkProvider wraps entire app in layout.tsx
import { ClerkProvider } from '@clerk/nextjs'
export default function RootLayout({ children }) {
return (
<ClerkProvider>
<html><body>{children}</body></html>
</ClerkProvider>
)
}
```
### Error Category 2: Authentication Errors
#### Session Not Found
```
Error: Session not found
```
**Cause:** User session expired or was revoked.
**Solution:**
```typescript
// Handle gracefully in your app
const { userId } = await auth()
if (!userId) {
redirect('/sign-in')
}
```
#### Form Identifier Not Found
```
Error: form_identifier_not_found
```
**Cause:** Email/username not registered.
**Solution:**
```typescript
// Show helpful message to user
catch (err: any) {
if (err.errors?.[0]?.code === 'form_identifier_not_found') {
setError('No account found with this email. Please sign up.')
}
}
```
#### Password Incorrect
```
Error: form_password_incorrect
```
**Cause:** Wrong password entered.
**Solution:**
```typescript
catch (err: any) {
if (err.errors?.[0]?.code === 'form_password_incorrect') {
setError('Incorrect password. Try again or reset your password.')
}
}
```
### Error Category 3: Middleware Errors
#### Infinite Redirect Loop
```
Error: Too many redirects
```
**Cause:** Middleware matcher includes sign-in page.
**Solution:**
```typescript
// middleware.ts
const isPublicRoute = createRouteMatcher([
'/sign-in(.*)', // Must include sign-in pages
'/sign-up(.*)',
'/'
])
export default clerkMiddleware(async (auth, request) => {
if (!isPublicRoute(request)) {
await auth.protect()
}
})
```
#### Middleware Not Executing
```
Error: Routes not protected
```
**Cause:** Matcher not matching routes correctly.
**Solution:**
```typescript
export const config = {
matcher: [
// Skip static files and _next
'/((?!_next|[^?]*\\.(?:html?|css|js|jpe?g|webp|png|gif|svg|ttf|woff2?|ico)).*)',
'/',
'/(api|trpc)(.*)'
]
}
```
### Error Category 4: Server/Client Errors
#### Hydration Mismatch
```
Error: Text content does not match server-rendered HTML
```
**Cause:** Auth state differs between server and client.
**Solution:**
```typescript
'use client'
import { useUser } from '@clerk/nextjs'
export function UserGreeting() {
const { user, isLoaded } = useUser()
// Prevent hydration mismatch by waiting for load
if (!isLoaded) {
return <div>Loading...</div>
}
return <div>Hello, {user?.firstName}</div>
}
```
#### Cannot Read Properties of Undefined
```
Error: Cannot read properties of undefined (reading 'userId')
```
**Cause:** Using auth() in client component or non-server context.
**Solution:**
```typescript
// Server Component - use auth()
import { auth } from '@clerk/nextjs/server'
const { userId } = await auth()
// Client Component - use useAuth()
'use client'
import { useAuth } from '@clerk/nextjs'
const { userId } = useAuth()
```
### Error Category 5: Webhook Errors
#### Webhook Verification Failed
```
Error: Webhook signature verification failed
```
**Cause:** Incorrect webhook secret or missing headers.
**Solution:**
```typescript
// app/api/webhooks/clerk/route.ts
import { Webhook } from 'svix'
import { headers } from 'next/headers'
export async function POST(req: Request) {
const WEBHOOK_SECRET = process.env.CLERK_WEBHOOK_SECRET!
const headerPayload = await headers()
const svix_id = headerPayload.get('svix-id')
const svix_timestamp = headerPayload.get('svix-timestamp')
const svix_signature = headerPayload.get('svix-signature')
const body = await req.text()
const wh = new Webhook(WEBHOOK_SECRET)
const evt = wh.verify(body, {
'svix-id': svix_id!,
'svix-timestamp': svix_timestamp!,
'svix-signature': svix_signature!
})
// Process event
}
```
## Output
- Identified error category
- Root cause analysis
- Working solution code
## Diagnostic Commands
```bash
# Check Clerk version
npm list @clerk/nextjs
# Verify environment variables
npx next info
# Check for multiple Clerk instances
npm list | grep clerk
# Clear Next.js cache
rm -rf .next && npm run dev
```
## Quick Reference Table
| Error Code | Meaning | Quick Fix |
|------------|---------|-----------|
| `form_identifier_not_found` | User doesn't exist | Show sign-up link |
| `form_password_incorrect` | Wrong password | Show reset link |
| `session_exists` | Already logged in | Redirect to app |
| `verification_expired` | Code expired | Resend code |
| `rate_limit_exceeded` | Too many attempts | Wait and retry |
## Resources
- [Clerk Error Codes](https://clerk.com/docs/errors/overview)
- [Debugging Guide](https://clerk.com/docs/debugging)
- [Discord Community](https://clerk.com/discord)
## Next Steps
Proceed to `clerk-debug-bundle` for comprehensive debugging tools.
评论 0
还没有评论,来抢沙发。
相关内容
同类或同场景的收录内容
building-with-kafka-strimzi
在 Kubernetes 上构建基于 Apache Kafka 的事件驱动系统,支持高可靠的消息传递、事务性处理与精确一次语义,结合 Strimzi 运营商实现集群自动化管理,利用 Schema Registry 保障事件模式演进,适用于微服务间解耦通信与实时数据流处理场景。
站外数据与分析
609 0.0
personal-tool-builder
专注于从个人真实痛点出发快速构建实用工具,涵盖命令行程序、本地优先应用和自动化脚本的开发与演进,强调先满足自身需求再逐步扩展,通过持续自用打磨功能,避免过度设计,确保工具简洁有效且长期可维护。
站外商业与营销
196 0.0
threejs-lighting
实现三维场景中的光照与阴影控制,支持多种光源类型及环境光照明,提供从基础布光到高级阴影优化的完整方案,适用于需要真实感渲染或性能平衡的可视化项目。
站外效率工具
442 0.0
aggregation-helper
提供数据聚合场景的自动化辅助能力,涵盖 SQL 查询编写、统计分析建模、可视化方案设计及商业智能配置,支持从需求理解到生产级代码生成的全流程指导。
站外效率工具数据与分析
217 0.0
举报「clerk-common-errors」
举报信息仅审核团队可见,同一资产 24 小时内仅可举报一次