clerk-common-errors
Compare original and translation side by side
🇺🇸
Original
English🇨🇳
Translation
ChineseClerk Common Errors
Clerk常见错误
Overview
概述
Diagnose and resolve common Clerk authentication errors and issues.
诊断并解决Clerk认证的常见错误与问题。
Prerequisites
前提条件
- Clerk SDK installed
- Access to Clerk dashboard for configuration checks
- Browser developer tools for debugging
- 已安装Clerk SDK
- 可访问Clerk控制台进行配置检查
- 可使用浏览器开发者工具进行调试
Instructions
操作步骤
Error Category 1: Configuration Errors
错误分类1:配置错误
Invalid API Key
无效API密钥
Error: Clerk: Invalid API keyCause: Publishable or secret key is incorrect or mismatched.
Solution:
bash
undefinedError: Clerk: Invalid API key**原因:**发布密钥或密钥不正确或不匹配。
解决方案:
bash
undefinedVerify keys in .env.local match Clerk dashboard
验证.env.local中的密钥与Clerk控制台中的一致
Publishable key starts with pk_test_ or pk_live_
发布密钥以pk_test_或pk_live_开头
Secret key starts with sk_test_ or sk_live_
密钥以sk_test_或sk_live_开头
Check for trailing whitespace
检查是否存在尾随空格
cat -A .env.local | grep CLERK
cat -A .env.local | grep CLERK
Ensure correct environment
确保环境正确
echo $NEXT_PUBLIC_CLERK_PUBLISHABLE_KEY
undefinedecho $NEXT_PUBLIC_CLERK_PUBLISHABLE_KEY
undefinedClerkProvider Not Found
未找到ClerkProvider
Error: useAuth can only be used within the <ClerkProvider /> componentCause: 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: useAuth can only be used within the <ClerkProvider /> component**原因:**使用Clerk钩子的组件位于ClerkProvider之外。
解决方案:
typescript
// 确保ClerkProvider在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
错误分类2:认证错误
Session Not Found
会话未找到
Error: Session not foundCause: User session expired or was revoked.
Solution:
typescript
// Handle gracefully in your app
const { userId } = await auth()
if (!userId) {
redirect('/sign-in')
}Error: Session not found**原因:**用户会话已过期或被撤销。
解决方案:
typescript
// 在应用中优雅处理
const { userId } = await auth()
if (!userId) {
redirect('/sign-in')
}Form Identifier Not Found
未找到表单标识符
Error: form_identifier_not_foundCause: 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.')
}
}Error: form_identifier_not_found**原因:**邮箱/用户名未注册。
解决方案:
typescript
// 向用户显示有用提示
catch (err: any) {
if (err.errors?.[0]?.code === 'form_identifier_not_found') {
setError('未找到该邮箱对应的账户,请注册。')
}
}Password Incorrect
密码错误
Error: form_password_incorrectCause: 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: form_password_incorrect**原因:**输入的密码错误。
解决方案:
typescript
catch (err: any) {
if (err.errors?.[0]?.code === 'form_password_incorrect') {
setError('密码错误,请重试或重置密码。')
}
}Error Category 3: Middleware Errors
错误分类3:中间件错误
Infinite Redirect Loop
无限重定向循环
Error: Too many redirectsCause: 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()
}
})Error: Too many redirects**原因:**中间件匹配器包含登录页面。
解决方案:
typescript
// middleware.ts
const isPublicRoute = createRouteMatcher([
'/sign-in(.*)', // 必须包含登录页面
'/sign-up(.*)',
'/'
])
export default clerkMiddleware(async (auth, request) => {
if (!isPublicRoute(request)) {
await auth.protect()
}
})Middleware Not Executing
中间件未执行
Error: Routes not protectedCause: 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: Routes not protected**原因:**匹配器未正确匹配路由。
解决方案:
typescript
export const config = {
matcher: [
// 跳过静态文件和_next目录
'/((?!_next|[^?]*\\.(?:html?|css|js|jpe?g|webp|png|gif|svg|ttf|woff2?|ico)).*)',
'/',
'/(api|trpc)(.*)'
]
}Error Category 4: Server/Client Errors
错误分类4:服务端/客户端错误
Hydration Mismatch
水合不匹配
Error: Text content does not match server-rendered HTMLCause: 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>
}Error: Text content does not match server-rendered HTML**原因:**服务端与客户端的认证状态不一致。
解决方案:
typescript
'use client'
import { useUser } from '@clerk/nextjs'
export function UserGreeting() {
const { user, isLoaded } = useUser()
// 等待加载完成以避免水合不匹配
if (!isLoaded) {
return <div>加载中...</div>
}
return <div>你好,{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: Cannot read properties of undefined (reading 'userId')**原因:**在客户端组件或非服务端上下文中使用auth()。
解决方案:
typescript
// 服务端组件 - 使用auth()
import { auth } from '@clerk/nextjs/server'
const { userId } = await auth()
// 客户端组件 - 使用useAuth()
'use client'
import { useAuth } from '@clerk/nextjs'
const { userId } = useAuth()Error Category 5: Webhook Errors
错误分类5:Webhook错误
Webhook Verification Failed
Webhook验证失败
Error: Webhook signature verification failedCause: 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
}Error: Webhook signature verification failed**原因:**Webhook密钥不正确或缺少请求头。
解决方案:
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!
})
// 处理事件
}Output
输出内容
- Identified error category
- Root cause analysis
- Working solution code
- 已识别的错误分类
- 根因分析
- 可运行的解决方案代码
Diagnostic Commands
诊断命令
bash
undefinedbash
undefinedCheck Clerk version
检查Clerk版本
npm list @clerk/nextjs
npm list @clerk/nextjs
Verify environment variables
验证环境变量
npx next info
npx next info
Check for multiple Clerk instances
检查是否存在多个Clerk实例
npm list | grep clerk
npm list | grep clerk
Clear Next.js cache
清除Next.js缓存
rm -rf .next && npm run dev
undefinedrm -rf .next && npm run dev
undefinedQuick Reference Table
快速参考表
| Error Code | Meaning | Quick Fix |
|---|---|---|
| User doesn't exist | Show sign-up link |
| Wrong password | Show reset link |
| Already logged in | Redirect to app |
| Code expired | Resend code |
| Too many attempts | Wait and retry |
| 错误代码 | 含义 | 快速修复方案 |
|---|---|---|
| 用户不存在 | 显示注册链接 |
| 密码错误 | 显示重置链接 |
| 已登录 | 重定向至应用 |
| 验证码过期 | 重新发送验证码 |
| 尝试次数过多 | 等待后重试 |
Resources
参考资源
Next Steps
下一步操作
Proceed to for comprehensive debugging tools.
clerk-debug-bundle使用获取全面的调试工具。
clerk-debug-bundle