clerk-nextjs-patterns

Compare original and translation side by side

🇺🇸

Original

English
🇨🇳

Translation

Chinese

Next.js Patterns

Next.js 模式

For basic setup, see
setup/
.
基础设置请查看
setup/
目录。

Impact Levels

影响等级

  • CRITICAL - Breaking bugs, security holes
  • HIGH - Common mistakes
  • MEDIUM - Optimization
  • CRITICAL(严重) - 破坏性bug、安全漏洞
  • HIGH(高) - 常见错误
  • MEDIUM(中等) - 优化项

References

参考资料

ReferenceImpact
references/server-vs-client.md
CRITICAL -
await auth()
vs hooks
references/middleware-strategies.md
HIGH - Public-first vs protected-first
references/server-actions.md
HIGH - Protect mutations
references/api-routes.md
HIGH - 401 vs 403
references/caching-auth.md
MEDIUM - User-scoped caching
参考文档影响等级
references/server-vs-client.md
CRITICAL -
await auth()
与 hooks 的对比
references/middleware-strategies.md
HIGH - 优先公开 vs 优先保护
references/server-actions.md
HIGH - 保护突变操作
references/api-routes.md
HIGH - 401 与 403 的区别
references/caching-auth.md
MEDIUM - 用户范围的缓存

Mental Model

思维模型

Server vs Client = different auth APIs:
  • Server:
    await auth()
    from
    @clerk/nextjs/server
    (async!)
  • Client:
    useAuth()
    hook from
    @clerk/nextjs
    (sync)
Never mix them. Server Components use server imports, Client Components use hooks.
服务器端 vs 客户端 = 不同的身份验证API:
  • 服务器端:来自
    @clerk/nextjs/server
    await auth()
    (异步!)
  • 客户端:来自
    @clerk/nextjs
    useAuth()
    钩子(同步)
切勿混用。服务器组件使用服务器端导入,客户端组件使用钩子。

Minimal Pattern

最简模式

typescript
// Server Component
import { auth } from '@clerk/nextjs/server'

export default async function Page() {
  const { userId } = await auth()  // MUST await!
  if (!userId) return <p>Not signed in</p>
  return <p>Hello {userId}</p>
}
typescript
// Server Component
import { auth } from '@clerk/nextjs/server'

export default async function Page() {
  const { userId } = await auth()  // 必须使用await!
  if (!userId) return <p>未登录</p>
  return <p>你好 {userId}</p>
}

Common Pitfalls

常见陷阱

SymptomCauseFix
undefined
userId in Server Component
Missing
await
await auth()
not
auth()
Auth not working on API routesMissing matcherAdd `'/(api
Cache returns wrong user's dataMissing userId in keyInclude
userId
in
unstable_cache
key
Mutations bypass authUnprotected Server ActionCheck
auth()
at start of action
Wrong HTTP error codeConfused 401/403401 = not signed in, 403 = no permission
症状原因修复方案
服务器组件中
userId
undefined
缺少
await
使用
await auth()
而非
auth()
API路由中身份验证不生效缺少匹配规则在中间件中添加`'/(api
缓存返回错误用户的数据缓存键中缺少userId
unstable_cache
键中包含
userId
突变操作绕过身份验证Server Action未受保护在Action开头检查
auth()
HTTP错误代码使用错误混淆401/403401 = 未登录,403 = 无权限

See Also

另请参阅

  • setup/
  • managing-orgs/
  • setup/
  • managing-orgs/

Docs

文档