← ClerkCONTENT HISTORYWHAT CHANGED · RULE-BASED ANALYSIS
Update to Clerk
Snapshot Sep 30, 2026 · 23:09 UTC · version 0.1.0
Collection source: not recorded for this historical snapshot.
First saved snapshot
No earlier snapshot is available to establish a change.
Compare saved observations
Download comparison JSONFull technical diff · 0 changed fields
Full snapshot data
{
"name": "clerk-nextjs-patterns",
"description": "Advanced Next.js patterns - middleware, Server Actions, caching with Clerk.",
"included_files": [
{
"relative_path": "evals/evals.json",
"size_in_bytes": 4871
},
{
"relative_path": "references/api-routes.md",
"size_in_bytes": 1462
},
{
"relative_path": "references/caching-auth.md",
"size_in_bytes": 1373
},
{
"relative_path": "references/middleware-strategies.md",
"size_in_bytes": 3742
},
{
"relative_path": "references/server-actions.md",
"size_in_bytes": 1588
},
{
"relative_path": "references/server-vs-client.md",
"size_in_bytes": 2379
},
{
"relative_path": "templates/nextjs-basic-auth/app/layout.tsx",
"size_in_bytes": 565
},
{
"relative_path": "templates/nextjs-basic-auth/app/page.tsx",
"size_in_bytes": 58
},
{
"relative_path": "templates/nextjs-basic-auth/package.json",
"size_in_bytes": 353
},
{
"relative_path": "templates/nextjs-basic-auth/proxy.ts",
"size_in_bytes": 280
},
{
"relative_path": "templates/nextjs-basic-auth/tsconfig.json",
"size_in_bytes": 576
}
],
"skill_md_contents": "---\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## What Do You Need?\n\n| Task | Reference |\n|------|-----------|\n| Server vs client auth (`auth()` vs hooks) | references/server-vs-client.md |\n| Configure middleware (public-first vs protected-first) | references/middleware-strategies.md |\n| Protect Server Actions | references/server-actions.md |\n| API route auth (401 vs 403) | references/api-routes.md |\n| Cache auth data (user-scoped caching) | references/caching-auth.md |\n\n## References\n\n| Reference | Description |\n|-----------|-------------|\n| `references/server-vs-client.md` | `await auth()` vs hooks |\n| `references/middleware-strategies.md` | Public-first vs protected-first, `proxy.ts` (Next.js <=15: `middleware.ts`) |\n| `references/server-actions.md` | Protect mutations |\n| `references/api-routes.md` | 401 vs 403 |\n| `references/caching-auth.md` | User-scoped caching |\n\n## Mental Model\n\nServer vs Client = different auth APIs:\n- **Server**: `await auth()` from `@clerk/nextjs/server` (async!)\n- **Client**: `useAuth()` hook from `@clerk/nextjs` (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```typescript\n// Server Component\nimport { auth } from '@clerk/nextjs/server'\n\nexport default async function Page() {\n const { isAuthenticated, userId } = await auth() // MUST await!\n if (!isAuthenticated) return <p>Not signed in</p>\n return <p>Hello {userId}</p>\n}\n```\n\n> **Core 2 ONLY (skip if current SDK):** `isAuthenticated` is not available. Use `if (!userId)` instead.\n\n### Conditional Rendering with `<Show>`\n\nFor client-side conditional rendering based on auth state. `<Show>` covers both authentication checks and authorization (feature, plan, role, permission) in one component.\n\n**Authentication check:**\n\n```tsx\nimport { Show } from '@clerk/nextjs'\n\n<Show when=\"signed-in\" fallback={<p>Please sign in</p>}>\n <Dashboard />\n</Show>\n```\n\n**Authorization checks (B2B):**\n\n```tsx\n// Feature-based (preferred — features can move between plans without redeploy)\n<Show when={{ feature: 'analytics' }} fallback={<UpgradePrompt />}>\n <AnalyticsDashboard />\n</Show>\n\n// Permission-based (preferred over role-based for granular access)\n<Show when={{ permission: 'org:invoices:create' }}>\n <NewInvoiceButton />\n</Show>\n\n// Plan-based (tier-level gating)\n<Show when={{ plan: 'pro' }}>\n <ProFeatures />\n</Show>\n\n// Role-based (use sparingly — prefer permission)\n<Show when={{ role: 'org:admin' }}>\n <AdminPanel />\n</Show>\n```\n\n**Callback for complex logic:**\n\n```tsx\n<Show when={(has) => has({ role: 'org:admin' }) || has({ role: 'org:billing_manager' })}>\n <BillingActions />\n</Show>\n```\n\n> **Core 2 ONLY (skip if current SDK):** `<Show>` does not exist. For authentication, use `<SignedIn>` and `<SignedOut>`. For authorization (role / permission), use `<Protect>` with the same prop names (`role`, `permission`, `condition`). Feature- and plan-based variants require Core 3. See `clerk-custom-ui` skill, `core-3/show-component.md` for the full migration table.\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 `'/(api|trpc)(.*)'` to `proxy.ts` (Next.js <=15: `middleware.ts`) |\n| Cache returns wrong user's data | Missing userId in key | Include `userId` in `unstable_cache` key |\n| Mutations bypass auth | Unprotected Server Action | Check `auth()` at start of action |\n| Wrong HTTP error code | Confused 401/403 | 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```typescript\nimport { auth } from '@clerk/nextjs/server'\n\nexport default async function Page() {\n const { getToken } = await auth()\n const token = await getToken({ template: 'hasura' })\n if (!token) return <p>Not authenticated</p>\n\n const res = await fetch('https://api.example.com/graphql', {\n headers: { Authorization: `Bearer ${token}` },\n })\n const data = await res.json()\n return <pre>{JSON.stringify(data)}</pre>\n}\n```\n\n**Client-side (Client Component)**:\n\n```typescript\n'use client'\nimport { useAuth } from '@clerk/nextjs'\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://api.example.com/data', {\n headers: { Authorization: `Bearer ${token}` },\n })\n return res.json()\n }\n\n return <button onClick={fetchData}>Fetch</button>\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/nextjs'\n\nexport function SessionInfo() {\n const { session } = useSession()\n if (!session) return null\n\n return (\n <p>\n Session {session.id} — last active: {session.lastActiveAt.toISOString()}\n </p>\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/backend` `verifyToken`** (recommended):\n\n```typescript\nimport { verifyToken } from '@clerk/backend'\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 // 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/backend`):\n\n```typescript\nimport jwt from 'jsonwebtoken'\n\nconst publicKey = process.env.CLERK_PEM_PUBLIC_KEY!.replace(/\\\\n/g, '\\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 // Manually check exp and nbf (jsonwebtoken does this automatically, but verify azp if needed)\n // 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 / mobile / API-to-API**: `Authorization: Bearer <token>` header\n\n> **CRITICAL**: Always check `exp` and `nbf` claims. `verifyToken` from `@clerk/backend` 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/permission gating)\n- `clerk-billing` - Plan and feature entitlements with `has()`\n- `clerk-webhooks` - Sync user/org events to your database\n- `clerk-custom-ui` - Theming and customization for built-in components\n\n## Docs\n\n[Next.js SDK](https://clerk.com/docs/reference/nextjs/overview)\n"
}SHA-256: 8713abfce0340976cbdf7e3a147dd4b435b0095da561b3ffb80c9610750e49b3