[{"data":1,"prerenderedAt":-1},["ShallowReactive",2],{"skill:01M7CSFB3KAEDM9T41JB23N0VE":3,"skill-same:01M7CSFB3KAEDM9T41JB23N0VE":105},{"skillNo":4,"name":5,"nameZh":6,"description":7,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":16,"categories":17,"keywords":18,"publishedAt":19,"linkOnly":20,"markdownContent":21,"markdownBody":22,"frontMatter":23,"refName":29,"commitSha":30,"skillDirectory":31,"forksCount":14,"repositoryHtmlUrl":32,"repositoryHomepageUrl":6,"ownerHtmlUrl":33,"ownerBlogUrl":34,"ownerDescription":35,"updatedAt":36,"install":37,"resources":50},"01M7CSFB3KAEDM9T41JB23N0VE","clerk-nextjs-patterns",null,"Advanced Next.js patterns - middleware, Server Actions, caching with Clerk.","Henrique1601\u002FSkiilsToIAs","Henrique1601","https:\u002F\u002Favatars.githubusercontent.com\u002Fu\u002F92006691?v=4","01M7CRXVT0GVXVK80JT1GR687S","Henrique Bezerra Dos Santos","01M7CRXVTN5Y8TMWJ1MDSKCQ1T",0,"MIT","https:\u002F\u002Fgithub.com\u002FHenrique1601\u002FSkiilsToIAs\u002Fblob\u002Fmain\u002Fbackend-database\u002Fclerk-nextjs-patterns\u002FSKILL.md",[],[],"2026-11-15 14:19:17",false,"---\nname: clerk-nextjs-patterns\ndescription: Advanced Next.js patterns - middleware, Server Actions, caching with\n  Clerk.\nlicense: MIT\nallowed-tools: WebFetch\ncompatibility: Requires NEXT_PUBLIC_CLERK_PUBLISHABLE_KEY and CLERK_SECRET_KEY. For manual JWT verification (standalone API servers without Clerk middleware), additionally requires CLERK_JWT_KEY or CLERK_PEM_PUBLIC_KEY.\nmetadata:\n  author: clerk\n  version: 2.2.0\n---\n\n# Next.js Patterns\n\n> **Version**: Check `package.json` for the SDK version — see `clerk` skill for the version table. Core 2 differences are noted inline with `> **Core 2 ONLY (skip if current SDK):**` callouts.\n\nFor basic setup, see `clerk-setup` skill.\n\n> **Route protection:** call `await auth.protect()` in each page, Route Handler, and Server Function. Keep `clerkMiddleware()` bare. `createRouteMatcher` is deprecated in `@clerk\u002Fnextjs` 7 and will be removed in the next major version. Don't add it. If a project already uses it, leave it working and point the user to the [migration guide](https:\u002F\u002Fclerk.com\u002Fdocs\u002Fguides\u002Fdevelopment\u002Fupgrading\u002Fupgrade-guides\u002Fmigrate-from-create-route-matcher).\n\n## What Do You Need?\n\n| Task | Reference |\n|------|-----------|\n| Server vs client auth (`auth()` vs hooks) | references\u002Fserver-vs-client.md |\n| Protect routes (check in each page, handler, and Server Function) | references\u002Fmiddleware-strategies.md |\n| Protect Server Actions | references\u002Fserver-actions.md |\n| API route auth (401 vs 403) | references\u002Fapi-routes.md |\n| Cache auth data (user-scoped caching) | references\u002Fcaching-auth.md |\n| Fix `next build` errors under Cache Components | [Cache Components](#cache-components) |\n\n## References\n\n| Reference | Description |\n|-----------|-------------|\n| `references\u002Fserver-vs-client.md` | `await auth()` vs hooks |\n| `references\u002Fmiddleware-strategies.md` | `auth.protect()` in each resource, bare `clerkMiddleware()` in `proxy.ts` (Next.js \u003C=15: `middleware.ts`) |\n| `references\u002Fserver-actions.md` | Protect mutations |\n| `references\u002Fapi-routes.md` | 401 vs 403 |\n| `references\u002Fcaching-auth.md` | User-scoped caching with `'use cache'` |\n\n## Mental Model\n\nServer vs Client = different auth APIs:\n- **Server**: `await auth()` from `@clerk\u002Fnextjs\u002Fserver` (async!)\n- **Client**: `useAuth()` hook from `@clerk\u002Fnextjs` (sync)\n\nNever mix them. Server Components use server imports, Client Components use hooks.\n\nKey properties from `auth()`:\n- `isAuthenticated` — boolean, replaces the `!!userId` pattern\n- `sessionStatus` — `'active'` | `'pending'`, for detecting incomplete session tasks\n- `userId`, `orgId`, `orgSlug`, `has()`, `protect()` — unchanged\n\n> **Core 2 ONLY (skip if current SDK):** `isAuthenticated` and `sessionStatus` are not available. Check `!!userId` instead.\n\n## Minimal Pattern\n\n```tsx\n\u002F\u002F Server Component\nimport { auth } from '@clerk\u002Fnextjs\u002Fserver'\nimport { Suspense } from 'react'\n\nasync function Greeting() {\n  const { isAuthenticated, userId } = await auth()  \u002F\u002F MUST await!\n  if (!isAuthenticated) return \u003Cp>Not signed in\u003C\u002Fp>\n  return \u003Cp>Hello {userId}\u003C\u002Fp>\n}\n\nexport default function Page() {\n  return (\n    \u003CSuspense>\n      \u003CGreeting \u002F>\n    \u003C\u002FSuspense>\n  )\n}\n```\n\n`auth()` reads the request, so it runs in an async child inside `\u003CSuspense>`, not in the page itself. See [Cache Components](#cache-components).\n\n> **Core 2 ONLY (skip if current SDK):** `isAuthenticated` is not available. Use `if (!userId)` instead.\n\n### Conditional Rendering with `\u003CShow>`\n\n`\u003CShow>` renders its children based on auth state. It covers both authentication checks and authorization (feature, plan, role, permission) in one component. In a Server Component, it reads the session from the request on the server, so wrap it in `\u003CSuspense>`. In a Client Component, it reads client-side auth state and needs no boundary.\n\n**Authentication check:**\n\n```tsx\nimport { Show } from '@clerk\u002Fnextjs'\nimport { Suspense } from 'react'\n\n\u003CSuspense>\n  \u003CShow when=\"signed-in\" fallback={\u003Cp>Please sign in\u003C\u002Fp>}>\n    \u003CDashboard \u002F>\n  \u003C\u002FShow>\n\u003C\u002FSuspense>\n```\n\n**Authorization checks (B2B)** (wrap in `\u003CSuspense>` the same way when rendered in a Server Component):\n\n```tsx\n\u002F\u002F Feature-based (preferred — features can move between plans without redeploy)\n\u003CShow when={{ feature: 'analytics' }} fallback={\u003CUpgradePrompt \u002F>}>\n  \u003CAnalyticsDashboard \u002F>\n\u003C\u002FShow>\n\n\u002F\u002F Permission-based (preferred over role-based for granular access)\n\u003CShow when={{ permission: 'org:invoices:create' }}>\n  \u003CNewInvoiceButton \u002F>\n\u003C\u002FShow>\n\n\u002F\u002F Plan-based (tier-level gating)\n\u003CShow when={{ plan: 'pro' }}>\n  \u003CProFeatures \u002F>\n\u003C\u002FShow>\n\n\u002F\u002F Role-based (use sparingly — prefer permission)\n\u003CShow when={{ role: 'org:admin' }}>\n  \u003CAdminPanel \u002F>\n\u003C\u002FShow>\n```\n\n**Callback for complex logic:**\n\n```tsx\n\u003CShow when={(has) => has({ role: 'org:admin' }) || has({ role: 'org:billing_manager' })}>\n  \u003CBillingActions \u002F>\n\u003C\u002FShow>\n```\n\n> **Core 2 ONLY (skip if current SDK):** `\u003CShow>` does not exist. For authentication, use `\u003CSignedIn>` and `\u003CSignedOut>`. For authorization (role \u002F permission), use `\u003CProtect>` with the same prop names (`role`, `permission`, `condition`). Feature- and plan-based variants require Core 3. See `clerk-custom-ui` skill, `core-3\u002Fshow-component.md` for the full migration table.\n\n## Cache Components\n\nNew Next.js apps set `cacheComponents: true` in `next.config` (the `create-next-app` default since Next.js 16.4). With it, `next build` fails on request data read outside a `\u003CSuspense>` boundary: `Next.js encountered uncached or runtime data during prerendering`. See [Cache Components](https:\u002F\u002Fclerk.com\u002Fdocs\u002Fguides\u002Fdevelopment\u002Frendering-modes#cache-components) in Clerk's rendering modes guide.\n\n- Wrap `\u003CShow>` rendered in a Server Component, and any Server Component that calls `auth()` or `currentUser()`, in `\u003CSuspense>`, as close to the auth-dependent UI as possible. Keep `\u003CClerkProvider>` and static layout outside the boundary so Next.js can prerender them.\n- In a layout header, put one `\u003CSuspense>` inside `\u003Cheader>` around both the `signed-out` and `signed-in` `\u003CShow>` blocks.\n- A page that calls `auth()` or `currentUser()` to render data: move the read into an async child inside `\u003CSuspense>` and keep the default-export page synchronous.\n- A page that gates its whole render with `auth.protect()`, `redirectToSignIn()`, or `redirect()`: leave the page as is and add a `loading.tsx` next to it. See [Read auth data inside Suspense](https:\u002F\u002Fclerk.com\u002Fdocs\u002Fguides\u002Fdevelopment\u002Frendering-modes#read-auth-data-inside-suspense).\n- Wrap catch-all `\u003CSignIn \u002F>`, `\u003CSignUp \u002F>`, `\u003CUserProfile \u002F>`, and `\u003COrganizationProfile \u002F>` pages in `\u003CSuspense>`. They read the URL with `usePathname()`, even in a Client Component. See [Prebuilt components on catch-all routes](https:\u002F\u002Fclerk.com\u002Fdocs\u002Fguides\u002Fdevelopment\u002Frendering-modes#prebuilt-components-on-catch-all-routes).\n- Never call `auth()` inside `'use cache'`. Read the ID outside and pass it in. See `references\u002Fcaching-auth.md` and [Cache data per user with `'use cache'`](https:\u002F\u002Fclerk.com\u002Fdocs\u002Fguides\u002Fdevelopment\u002Frendering-modes#cache-data-per-user-with-use-cache).\n\nUse `next build --debug-prerender` to list every failing route. A plain `next build` stops at the first.\n\n## Common Pitfalls\n\n| Symptom | Cause | Fix |\n|---------|-------|-----|\n| `undefined` userId in Server Component | Missing `await` | `await auth()` not `auth()` |\n| Auth not working on API routes | Missing matcher | Add `'\u002F(api|trpc)(.*)'` to `proxy.ts` (Next.js \u003C=15: `middleware.ts`) |\n| `next build` fails with \"uncached or runtime data during prerendering\" | `auth()`, `currentUser()`, or server `\u003CShow>` outside `\u003CSuspense>` | Wrap the auth-dependent UI in `\u003CSuspense>` (see [Cache Components](#cache-components)) |\n| Cache returns wrong user's data | `userId` not part of the cache key | Pass `userId` into the `'use cache'` function as an argument |\n| Mutations bypass auth | Unprotected Server Action | Check `auth()` at start of action |\n| Protected page returns 200, not 307, while signed out | The redirect happened after streaming started (e.g. under a `loading.tsx`) | Confirm the body redirects to sign-in and has no protected data. Keep the check in the page |\n| Wrong HTTP error code | Confused 401\u002F403 | 401 = not signed in, 403 = no permission |\n\n## Session Tokens & Custom JWTs\n\n### getToken() for external APIs\n\nPass a custom JWT to third-party services (Hasura, Supabase, etc.) using JWT templates defined in the Clerk dashboard.\n\n**Server-side (Server Component or Route Handler)**:\n\n```tsx\nimport { auth } from '@clerk\u002Fnextjs\u002Fserver'\n\nexport async function ExternalData() {\n  const { getToken } = await auth()\n  const token = await getToken({ template: 'hasura' })\n  if (!token) return \u003Cp>Not authenticated\u003C\u002Fp>\n\n  const res = await fetch('https:\u002F\u002Fapi.example.com\u002Fgraphql', {\n    headers: { Authorization: `Bearer ${token}` },\n  })\n  const data = await res.json()\n  return \u003Cpre>{JSON.stringify(data)}\u003C\u002Fpre>\n}\n```\n\nRender `\u003CExternalData \u002F>` inside `\u003CSuspense>`.\n\n**Client-side (Client Component)**:\n\n```typescript\n'use client'\nimport { useAuth } from '@clerk\u002Fnextjs'\n\nexport function DataFetcher() {\n  const { getToken } = useAuth()\n\n  async function fetchData() {\n    const token = await getToken({ template: 'supabase' })\n    if (!token) return\n\n    const res = await fetch('https:\u002F\u002Fapi.example.com\u002Fdata', {\n      headers: { Authorization: `Bearer ${token}` },\n    })\n    return res.json()\n  }\n\n  return \u003Cbutton onClick={fetchData}>Fetch\u003C\u002Fbutton>\n}\n```\n\n`getToken()` returns `null` when the user is not authenticated — always null-check before use.\n\n### useSession() for session data\n\nAccess session metadata in client components:\n\n```typescript\n'use client'\nimport { useSession } from '@clerk\u002Fnextjs'\n\nexport function SessionInfo() {\n  const { session } = useSession()\n  if (!session) return null\n\n  return (\n    \u003Cp>\n      Session {session.id} — last active: {session.lastActiveAt.toISOString()}\n    \u003C\u002Fp>\n  )\n}\n```\n\n### Manual JWT verification (no Clerk middleware)\n\nFor standalone API servers that receive Clerk session tokens from the `Authorization` header or the `__session` cookie (same-origin).\n\n**Using `@clerk\u002Fbackend` `verifyToken`** (recommended):\n\n```typescript\nimport { verifyToken } from '@clerk\u002Fbackend'\n\nconst token = req.headers.authorization?.replace('Bearer ', '')\nif (!token) return res.status(401).json({ error: 'No token' })\n\ntry {\n  const claims = await verifyToken(token, {\n    jwtKey: process.env.CLERK_JWT_KEY,\n  })\n  \u002F\u002F claims.sub = userId\n} catch {\n  return res.status(401).json({ error: 'Invalid token' })\n}\n```\n\n**Using `jsonwebtoken`** (when you can't use `@clerk\u002Fbackend`):\n\n```typescript\nimport jwt from 'jsonwebtoken'\n\nconst publicKey = process.env.CLERK_PEM_PUBLIC_KEY!.replace(\u002F\\\\n\u002Fg, '\\n')\nconst token = req.headers.authorization?.replace('Bearer ', '')\nif (!token) return res.status(401).json({ error: 'No token' })\n\ntry {\n  const claims = jwt.verify(token, publicKey, { algorithms: ['RS256'] }) as jwt.JwtPayload\n  \u002F\u002F Manually check exp and nbf (jsonwebtoken does this automatically, but verify azp if needed)\n  \u002F\u002F claims.sub = userId\n} catch {\n  return res.status(401).json({ error: 'Invalid or expired token' })\n}\n```\n\nToken sources:\n- **Same-origin requests**: `__session` cookie (Clerk sets this automatically)\n- **Cross-origin \u002F mobile \u002F API-to-API**: `Authorization: Bearer \u003Ctoken>` header\n\n> **CRITICAL**: Always check `exp` and `nbf` claims. `verifyToken` from `@clerk\u002Fbackend` handles this automatically; with raw `jsonwebtoken`, set `ignoreExpiration: false` (default) and ensure `clockTolerance` is minimal.\n\n## See Also\n\n- `clerk-setup` - Initial Clerk install\n- `clerk-orgs` - B2B patterns (active org, role\u002Fpermission gating)\n- `clerk-billing` - Plan and feature entitlements with `has()`\n- `clerk-webhooks` - Sync user\u002Forg events to your database\n- `clerk-custom-ui` - Theming and customization for built-in components\n\n## Docs\n\n[Next.js SDK](https:\u002F\u002Fclerk.com\u002Fdocs\u002Freference\u002Fnextjs\u002Foverview)\n","# Next.js Patterns\n\n> **Version**: Check `package.json` for the SDK version — see `clerk` skill for the version table. Core 2 differences are noted inline with `> **Core 2 ONLY (skip if current SDK):**` callouts.\n\nFor basic setup, see `clerk-setup` skill.\n\n> **Route protection:** call `await auth.protect()` in each page, Route Handler, and Server Function. Keep `clerkMiddleware()` bare. `createRouteMatcher` is deprecated in `@clerk\u002Fnextjs` 7 and will be removed in the next major version. Don't add it. If a project already uses it, leave it working and point the user to the [migration guide](https:\u002F\u002Fclerk.com\u002Fdocs\u002Fguides\u002Fdevelopment\u002Fupgrading\u002Fupgrade-guides\u002Fmigrate-from-create-route-matcher).\n\n## What Do You Need?\n\n| Task | Reference |\n|------|-----------|\n| Server vs client auth (`auth()` vs hooks) | references\u002Fserver-vs-client.md |\n| Protect routes (check in each page, handler, and Server Function) | references\u002Fmiddleware-strategies.md |\n| Protect Server Actions | references\u002Fserver-actions.md |\n| API route auth (401 vs 403) | references\u002Fapi-routes.md |\n| Cache auth data (user-scoped caching) | references\u002Fcaching-auth.md |\n| Fix `next build` errors under Cache Components | [Cache Components](#cache-components) |\n\n## References\n\n| Reference | Description |\n|-----------|-------------|\n| `references\u002Fserver-vs-client.md` | `await auth()` vs hooks |\n| `references\u002Fmiddleware-strategies.md` | `auth.protect()` in each resource, bare `clerkMiddleware()` in `proxy.ts` (Next.js \u003C=15: `middleware.ts`) |\n| `references\u002Fserver-actions.md` | Protect mutations |\n| `references\u002Fapi-routes.md` | 401 vs 403 |\n| `references\u002Fcaching-auth.md` | User-scoped caching with `'use cache'` |\n\n## Mental Model\n\nServer vs Client = different auth APIs:\n- **Server**: `await auth()` from `@clerk\u002Fnextjs\u002Fserver` (async!)\n- **Client**: `useAuth()` hook from `@clerk\u002Fnextjs` (sync)\n\nNever mix them. Server Components use server imports, Client Components use hooks.\n\nKey properties from `auth()`:\n- `isAuthenticated` — boolean, replaces the `!!userId` pattern\n- `sessionStatus` — `'active'` | `'pending'`, for detecting incomplete session tasks\n- `userId`, `orgId`, `orgSlug`, `has()`, `protect()` — unchanged\n\n> **Core 2 ONLY (skip if current SDK):** `isAuthenticated` and `sessionStatus` are not available. Check `!!userId` instead.\n\n## Minimal Pattern\n\n```tsx\n\u002F\u002F Server Component\nimport { auth } from '@clerk\u002Fnextjs\u002Fserver'\nimport { Suspense } from 'react'\n\nasync function Greeting() {\n  const { isAuthenticated, userId } = await auth()  \u002F\u002F MUST await!\n  if (!isAuthenticated) return \u003Cp>Not signed in\u003C\u002Fp>\n  return \u003Cp>Hello {userId}\u003C\u002Fp>\n}\n\nexport default function Page() {\n  return (\n    \u003CSuspense>\n      \u003CGreeting \u002F>\n    \u003C\u002FSuspense>\n  )\n}\n```\n\n`auth()` reads the request, so it runs in an async child inside `\u003CSuspense>`, not in the page itself. See [Cache Components](#cache-components).\n\n> **Core 2 ONLY (skip if current SDK):** `isAuthenticated` is not available. Use `if (!userId)` instead.\n\n### Conditional Rendering with `\u003CShow>`\n\n`\u003CShow>` renders its children based on auth state. It covers both authentication checks and authorization (feature, plan, role, permission) in one component. In a Server Component, it reads the session from the request on the server, so wrap it in `\u003CSuspense>`. In a Client Component, it reads client-side auth state and needs no boundary.\n\n**Authentication check:**\n\n```tsx\nimport { Show } from '@clerk\u002Fnextjs'\nimport { Suspense } from 'react'\n\n\u003CSuspense>\n  \u003CShow when=\"signed-in\" fallback={\u003Cp>Please sign in\u003C\u002Fp>}>\n    \u003CDashboard \u002F>\n  \u003C\u002FShow>\n\u003C\u002FSuspense>\n```\n\n**Authorization checks (B2B)** (wrap in `\u003CSuspense>` the same way when rendered in a Server Component):\n\n```tsx\n\u002F\u002F Feature-based (preferred — features can move between plans without redeploy)\n\u003CShow when={{ feature: 'analytics' }} fallback={\u003CUpgradePrompt \u002F>}>\n  \u003CAnalyticsDashboard \u002F>\n\u003C\u002FShow>\n\n\u002F\u002F Permission-based (preferred over role-based for granular access)\n\u003CShow when={{ permission: 'org:invoices:create' }}>\n  \u003CNewInvoiceButton \u002F>\n\u003C\u002FShow>\n\n\u002F\u002F Plan-based (tier-level gating)\n\u003CShow when={{ plan: 'pro' }}>\n  \u003CProFeatures \u002F>\n\u003C\u002FShow>\n\n\u002F\u002F Role-based (use sparingly — prefer permission)\n\u003CShow when={{ role: 'org:admin' }}>\n  \u003CAdminPanel \u002F>\n\u003C\u002FShow>\n```\n\n**Callback for complex logic:**\n\n```tsx\n\u003CShow when={(has) => has({ role: 'org:admin' }) || has({ role: 'org:billing_manager' })}>\n  \u003CBillingActions \u002F>\n\u003C\u002FShow>\n```\n\n> **Core 2 ONLY (skip if current SDK):** `\u003CShow>` does not exist. For authentication, use `\u003CSignedIn>` and `\u003CSignedOut>`. For authorization (role \u002F permission), use `\u003CProtect>` with the same prop names (`role`, `permission`, `condition`). Feature- and plan-based variants require Core 3. See `clerk-custom-ui` skill, `core-3\u002Fshow-component.md` for the full migration table.\n\n## Cache Components\n\nNew Next.js apps set `cacheComponents: true` in `next.config` (the `create-next-app` default since Next.js 16.4). With it, `next build` fails on request data read outside a `\u003CSuspense>` boundary: `Next.js encountered uncached or runtime data during prerendering`. See [Cache Components](https:\u002F\u002Fclerk.com\u002Fdocs\u002Fguides\u002Fdevelopment\u002Frendering-modes#cache-components) in Clerk's rendering modes guide.\n\n- Wrap `\u003CShow>` rendered in a Server Component, and any Server Component that calls `auth()` or `currentUser()`, in `\u003CSuspense>`, as close to the auth-dependent UI as possible. Keep `\u003CClerkProvider>` and static layout outside the boundary so Next.js can prerender them.\n- In a layout header, put one `\u003CSuspense>` inside `\u003Cheader>` around both the `signed-out` and `signed-in` `\u003CShow>` blocks.\n- A page that calls `auth()` or `currentUser()` to render data: move the read into an async child inside `\u003CSuspense>` and keep the default-export page synchronous.\n- A page that gates its whole render with `auth.protect()`, `redirectToSignIn()`, or `redirect()`: leave the page as is and add a `loading.tsx` next to it. See [Read auth data inside Suspense](https:\u002F\u002Fclerk.com\u002Fdocs\u002Fguides\u002Fdevelopment\u002Frendering-modes#read-auth-data-inside-suspense).\n- Wrap catch-all `\u003CSignIn \u002F>`, `\u003CSignUp \u002F>`, `\u003CUserProfile \u002F>`, and `\u003COrganizationProfile \u002F>` pages in `\u003CSuspense>`. They read the URL with `usePathname()`, even in a Client Component. See [Prebuilt components on catch-all routes](https:\u002F\u002Fclerk.com\u002Fdocs\u002Fguides\u002Fdevelopment\u002Frendering-modes#prebuilt-components-on-catch-all-routes).\n- Never call `auth()` inside `'use cache'`. Read the ID outside and pass it in. See `references\u002Fcaching-auth.md` and [Cache data per user with `'use cache'`](https:\u002F\u002Fclerk.com\u002Fdocs\u002Fguides\u002Fdevelopment\u002Frendering-modes#cache-data-per-user-with-use-cache).\n\nUse `next build --debug-prerender` to list every failing route. A plain `next build` stops at the first.\n\n## Common Pitfalls\n\n| Symptom | Cause | Fix |\n|---------|-------|-----|\n| `undefined` userId in Server Component | Missing `await` | `await auth()` not `auth()` |\n| Auth not working on API routes | Missing matcher | Add `'\u002F(api|trpc)(.*)'` to `proxy.ts` (Next.js \u003C=15: `middleware.ts`) |\n| `next build` fails with \"uncached or runtime data during prerendering\" | `auth()`, `currentUser()`, or server `\u003CShow>` outside `\u003CSuspense>` | Wrap the auth-dependent UI in `\u003CSuspense>` (see [Cache Components](#cache-components)) |\n| Cache returns wrong user's data | `userId` not part of the cache key | Pass `userId` into the `'use cache'` function as an argument |\n| Mutations bypass auth | Unprotected Server Action | Check `auth()` at start of action |\n| Protected page returns 200, not 307, while signed out | The redirect happened after streaming started (e.g. under a `loading.tsx`) | Confirm the body redirects to sign-in and has no protected data. Keep the check in the page |\n| Wrong HTTP error code | Confused 401\u002F403 | 401 = not signed in, 403 = no permission |\n\n## Session Tokens & Custom JWTs\n\n### getToken() for external APIs\n\nPass a custom JWT to third-party services (Hasura, Supabase, etc.) using JWT templates defined in the Clerk dashboard.\n\n**Server-side (Server Component or Route Handler)**:\n\n```tsx\nimport { auth } from '@clerk\u002Fnextjs\u002Fserver'\n\nexport async function ExternalData() {\n  const { getToken } = await auth()\n  const token = await getToken({ template: 'hasura' })\n  if (!token) return \u003Cp>Not authenticated\u003C\u002Fp>\n\n  const res = await fetch('https:\u002F\u002Fapi.example.com\u002Fgraphql', {\n    headers: { Authorization: `Bearer ${token}` },\n  })\n  const data = await res.json()\n  return \u003Cpre>{JSON.stringify(data)}\u003C\u002Fpre>\n}\n```\n\nRender `\u003CExternalData \u002F>` inside `\u003CSuspense>`.\n\n**Client-side (Client Component)**:\n\n```typescript\n'use client'\nimport { useAuth } from '@clerk\u002Fnextjs'\n\nexport function DataFetcher() {\n  const { getToken } = useAuth()\n\n  async function fetchData() {\n    const token = await getToken({ template: 'supabase' })\n    if (!token) return\n\n    const res = await fetch('https:\u002F\u002Fapi.example.com\u002Fdata', {\n      headers: { Authorization: `Bearer ${token}` },\n    })\n    return res.json()\n  }\n\n  return \u003Cbutton onClick={fetchData}>Fetch\u003C\u002Fbutton>\n}\n```\n\n`getToken()` returns `null` when the user is not authenticated — always null-check before use.\n\n### useSession() for session data\n\nAccess session metadata in client components:\n\n```typescript\n'use client'\nimport { useSession } from '@clerk\u002Fnextjs'\n\nexport function SessionInfo() {\n  const { session } = useSession()\n  if (!session) return null\n\n  return (\n    \u003Cp>\n      Session {session.id} — last active: {session.lastActiveAt.toISOString()}\n    \u003C\u002Fp>\n  )\n}\n```\n\n### Manual JWT verification (no Clerk middleware)\n\nFor standalone API servers that receive Clerk session tokens from the `Authorization` header or the `__session` cookie (same-origin).\n\n**Using `@clerk\u002Fbackend` `verifyToken`** (recommended):\n\n```typescript\nimport { verifyToken } from '@clerk\u002Fbackend'\n\nconst token = req.headers.authorization?.replace('Bearer ', '')\nif (!token) return res.status(401).json({ error: 'No token' })\n\ntry {\n  const claims = await verifyToken(token, {\n    jwtKey: process.env.CLERK_JWT_KEY,\n  })\n  \u002F\u002F claims.sub = userId\n} catch {\n  return res.status(401).json({ error: 'Invalid token' })\n}\n```\n\n**Using `jsonwebtoken`** (when you can't use `@clerk\u002Fbackend`):\n\n```typescript\nimport jwt from 'jsonwebtoken'\n\nconst publicKey = process.env.CLERK_PEM_PUBLIC_KEY!.replace(\u002F\\\\n\u002Fg, '\\n')\nconst token = req.headers.authorization?.replace('Bearer ', '')\nif (!token) return res.status(401).json({ error: 'No token' })\n\ntry {\n  const claims = jwt.verify(token, publicKey, { algorithms: ['RS256'] }) as jwt.JwtPayload\n  \u002F\u002F Manually check exp and nbf (jsonwebtoken does this automatically, but verify azp if needed)\n  \u002F\u002F claims.sub = userId\n} catch {\n  return res.status(401).json({ error: 'Invalid or expired token' })\n}\n```\n\nToken sources:\n- **Same-origin requests**: `__session` cookie (Clerk sets this automatically)\n- **Cross-origin \u002F mobile \u002F API-to-API**: `Authorization: Bearer \u003Ctoken>` header\n\n> **CRITICAL**: Always check `exp` and `nbf` claims. `verifyToken` from `@clerk\u002Fbackend` handles this automatically; with raw `jsonwebtoken`, set `ignoreExpiration: false` (default) and ensure `clockTolerance` is minimal.\n\n## See Also\n\n- `clerk-setup` - Initial Clerk install\n- `clerk-orgs` - B2B patterns (active org, role\u002Fpermission gating)\n- `clerk-billing` - Plan and feature entitlements with `has()`\n- `clerk-webhooks` - Sync user\u002Forg events to your database\n- `clerk-custom-ui` - Theming and customization for built-in components\n\n## Docs\n\n[Next.js SDK](https:\u002F\u002Fclerk.com\u002Fdocs\u002Freference\u002Fnextjs\u002Foverview)\n",{"name":5,"license":15,"metadata":24,"description":7,"allowed-tools":27,"compatibility":28},{"author":25,"version":26},"clerk","2.2.0","WebFetch","Requires NEXT_PUBLIC_CLERK_PUBLISHABLE_KEY and CLERK_SECRET_KEY. For manual JWT verification (standalone API servers without Clerk middleware), additionally requires CLERK_JWT_KEY or CLERK_PEM_PUBLIC_KEY.","main","a73152352c0612252131e5cf84e91312a6cf17dc","backend-database\u002Fclerk-nextjs-patterns","https:\u002F\u002Fgithub.com\u002FHenrique1601\u002FSkiilsToIAs","https:\u002F\u002Fgithub.com\u002FHenrique1601","https:\u002F\u002Fbezerraportifolio.netlify.app\u002F","Full Stack Developer | React, Next.js, TypeScript, Node.js & IA | Construindo produtos digitais e soluções SaaS","2026-11-15 02:56:04",{"source":8,"skillName":5,"commands":38,"prompt":48,"zipAvailable":49},[39,42,45],{"tool":40,"command":41},"npx","npx skills add Henrique1601\u002FSkiilsToIAs --skill clerk-nextjs-patterns",{"tool":43,"command":44},"bunx","bunx skills add Henrique1601\u002FSkiilsToIAs --skill clerk-nextjs-patterns",{"tool":46,"command":47},"pnpm","pnpm dlx skills add Henrique1601\u002FSkiilsToIAs --skill clerk-nextjs-patterns","安装技能，技能地址：https:\u002F\u002Fgithub.com\u002FHenrique1601\u002FSkiilsToIAs\u002Fblob\u002Fmain\u002Fbackend-database\u002Fclerk-nextjs-patterns\u002FSKILL.md",true,[51,57,61,65,69,73,77,83,87,93,97,101],{"path":52,"resourceType":53,"resourceTypeDesc":54,"sizeBytes":55,"sourceHtmlUrl":56},"evals\u002Fevals.json","REFERENCE","参考文档",5452,"https:\u002F\u002Fgithub.com\u002FHenrique1601\u002FSkiilsToIAs\u002Fblob\u002Fmain\u002Fbackend-database\u002Fclerk-nextjs-patterns\u002Fevals\u002Fevals.json",{"path":58,"resourceType":53,"resourceTypeDesc":54,"sizeBytes":59,"sourceHtmlUrl":60},"references\u002Fapi-routes.md",1462,"https:\u002F\u002Fgithub.com\u002FHenrique1601\u002FSkiilsToIAs\u002Fblob\u002Fmain\u002Fbackend-database\u002Fclerk-nextjs-patterns\u002Freferences\u002Fapi-routes.md",{"path":62,"resourceType":53,"resourceTypeDesc":54,"sizeBytes":63,"sourceHtmlUrl":64},"references\u002Fcaching-auth.md",3093,"https:\u002F\u002Fgithub.com\u002FHenrique1601\u002FSkiilsToIAs\u002Fblob\u002Fmain\u002Fbackend-database\u002Fclerk-nextjs-patterns\u002Freferences\u002Fcaching-auth.md",{"path":66,"resourceType":53,"resourceTypeDesc":54,"sizeBytes":67,"sourceHtmlUrl":68},"references\u002Fmiddleware-strategies.md",7946,"https:\u002F\u002Fgithub.com\u002FHenrique1601\u002FSkiilsToIAs\u002Fblob\u002Fmain\u002Fbackend-database\u002Fclerk-nextjs-patterns\u002Freferences\u002Fmiddleware-strategies.md",{"path":70,"resourceType":53,"resourceTypeDesc":54,"sizeBytes":71,"sourceHtmlUrl":72},"references\u002Fserver-actions.md",1588,"https:\u002F\u002Fgithub.com\u002FHenrique1601\u002FSkiilsToIAs\u002Fblob\u002Fmain\u002Fbackend-database\u002Fclerk-nextjs-patterns\u002Freferences\u002Fserver-actions.md",{"path":74,"resourceType":53,"resourceTypeDesc":54,"sizeBytes":75,"sourceHtmlUrl":76},"references\u002Fserver-vs-client.md",3071,"https:\u002F\u002Fgithub.com\u002FHenrique1601\u002FSkiilsToIAs\u002Fblob\u002Fmain\u002Fbackend-database\u002Fclerk-nextjs-patterns\u002Freferences\u002Fserver-vs-client.md",{"path":78,"resourceType":79,"resourceTypeDesc":80,"sizeBytes":81,"sourceHtmlUrl":82},"templates\u002Fnextjs-basic-auth\u002Fapp\u002Flayout.tsx","OTHER","其他",659,"https:\u002F\u002Fgithub.com\u002FHenrique1601\u002FSkiilsToIAs\u002Fblob\u002Fmain\u002Fbackend-database\u002Fclerk-nextjs-patterns\u002Ftemplates\u002Fnextjs-basic-auth\u002Fapp\u002Flayout.tsx",{"path":84,"resourceType":79,"resourceTypeDesc":80,"sizeBytes":85,"sourceHtmlUrl":86},"templates\u002Fnextjs-basic-auth\u002Fapp\u002Fpage.tsx",58,"https:\u002F\u002Fgithub.com\u002FHenrique1601\u002FSkiilsToIAs\u002Fblob\u002Fmain\u002Fbackend-database\u002Fclerk-nextjs-patterns\u002Ftemplates\u002Fnextjs-basic-auth\u002Fapp\u002Fpage.tsx",{"path":88,"resourceType":89,"resourceTypeDesc":90,"sizeBytes":91,"sourceHtmlUrl":92},"templates\u002Fnextjs-basic-auth\u002Fnext.config.ts","SCRIPT","脚本",155,"https:\u002F\u002Fgithub.com\u002FHenrique1601\u002FSkiilsToIAs\u002Fblob\u002Fmain\u002Fbackend-database\u002Fclerk-nextjs-patterns\u002Ftemplates\u002Fnextjs-basic-auth\u002Fnext.config.ts",{"path":94,"resourceType":53,"resourceTypeDesc":54,"sizeBytes":95,"sourceHtmlUrl":96},"templates\u002Fnextjs-basic-auth\u002Fpackage.json",392,"https:\u002F\u002Fgithub.com\u002FHenrique1601\u002FSkiilsToIAs\u002Fblob\u002Fmain\u002Fbackend-database\u002Fclerk-nextjs-patterns\u002Ftemplates\u002Fnextjs-basic-auth\u002Fpackage.json",{"path":98,"resourceType":89,"resourceTypeDesc":90,"sizeBytes":99,"sourceHtmlUrl":100},"templates\u002Fnextjs-basic-auth\u002Fproxy.ts",280,"https:\u002F\u002Fgithub.com\u002FHenrique1601\u002FSkiilsToIAs\u002Fblob\u002Fmain\u002Fbackend-database\u002Fclerk-nextjs-patterns\u002Ftemplates\u002Fnextjs-basic-auth\u002Fproxy.ts",{"path":102,"resourceType":53,"resourceTypeDesc":54,"sizeBytes":103,"sourceHtmlUrl":104},"templates\u002Fnextjs-basic-auth\u002Ftsconfig.json",612,"https:\u002F\u002Fgithub.com\u002FHenrique1601\u002FSkiilsToIAs\u002Fblob\u002Fmain\u002Fbackend-database\u002Fclerk-nextjs-patterns\u002Ftemplates\u002Fnextjs-basic-auth\u002Ftsconfig.json",[106,113,120,128,135,142],{"skillNo":107,"name":108,"nameZh":6,"description":109,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":110,"categories":111,"keywords":112,"publishedAt":19},"01M7E2ANBW9V6AVX5JXNCEAWF8","rag-architect-agent","Agente Arquiteto de RAG, Embeddings & Busca Vetorial. Especialista em design e implementação de pipelines de Retrieval-Augmented Generation de alta fidelidade: chunking semântico, modelagem pgvector no PostgreSQL (Neon\u002FSupabase), busca híbrida (cosseno + BM25), reranking, validação via TypeSafe AI e filosofia Ponytail (anti-overengineering).","https:\u002F\u002Fgithub.com\u002FHenrique1601\u002FSkiilsToIAs\u002Fblob\u002Fmain\u002Fcustom-agents\u002Frag-architect-agent\u002FSKILL.md",[],[],{"skillNo":114,"name":115,"nameZh":6,"description":116,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":117,"categories":118,"keywords":119,"publishedAt":19},"01M7E29KKF8R02ZRGYE2MJM67G","rag-architecture-patterns","Padrões arquiteturais e implementação de pipelines RAG (Retrieval-Augmented Generation) de alta fidelidade para qualquer projeto ou sistema. Cobre chunking semântico, embeddings, busca híbrida (pgvector + BM25), reranking, validação via TypeSafe AI e filosofia Ponytail (anti-overengineering).","https:\u002F\u002Fgithub.com\u002FHenrique1601\u002FSkiilsToIAs\u002Fblob\u002Fmain\u002Fai-agents\u002Frag-architecture-patterns\u002FSKILL.md",[],[],{"skillNo":121,"name":122,"nameZh":6,"description":123,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":124,"licenseFileUrl":6,"sourceHtmlUrl":125,"categories":126,"keywords":127,"publishedAt":19},"01M7CWRA8E3BJ7CPY8N8EG28J1","skill-repair","Use this to fix and re-install agent skills that have failed installation.\nThis skill provides the necessary context and permissions to surgically update\nthe `manifest.json` after a fix has been applied.","Apache-2.0","https:\u002F\u002Fgithub.com\u002FHenrique1601\u002FSkiilsToIAs\u002Fblob\u002Fmain\u002Futilities\u002Fskill-repair\u002FSKILL.md",[],[],{"skillNo":129,"name":130,"nameZh":6,"description":131,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":132,"categories":133,"keywords":134,"publishedAt":19},"01M7CWR66FZP8FA47WVZ4Z2EXC","security-scan","Scan your Claude Code configuration (.claude\u002F directory) for security vulnerabilities, misconfigurations, and injection risks using AgentShield. Checks CLAUDE.md, settings.json, MCP servers, hooks, and agent definitions.","https:\u002F\u002Fgithub.com\u002FHenrique1601\u002FSkiilsToIAs\u002Fblob\u002Fmain\u002Futilities\u002Fsecurity-scan\u002FSKILL.md",[],[],{"skillNo":136,"name":137,"nameZh":6,"description":138,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":139,"categories":140,"keywords":141,"publishedAt":19},"01M7CWR0QPY58QPTR1P759TFNG","security-review","Use this skill when adding authentication, handling user input, working with secrets, creating API endpoints, or implementing payment\u002Fsensitive features. Provides comprehensive security checklist and patterns.","https:\u002F\u002Fgithub.com\u002FHenrique1601\u002FSkiilsToIAs\u002Fblob\u002Fmain\u002Futilities\u002Fsecurity-review\u002FSKILL.md",[],[],{"skillNo":143,"name":144,"nameZh":6,"description":145,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":146,"categories":147,"keywords":148,"publishedAt":19},"01M7CWQXCE40XWT4FZ3VWZFGDP","security-bounty-hunter","Hunt for exploitable, bounty-worthy security issues in repositories. Focuses on remotely reachable vulnerabilities that qualify for real reports instead of noisy local-only findings.","https:\u002F\u002Fgithub.com\u002FHenrique1601\u002FSkiilsToIAs\u002Fblob\u002Fmain\u002Futilities\u002Fsecurity-bounty-hunter\u002FSKILL.md",[],[]]