rachit-sharma08/coding-agent-skills/clerk-nextjs-patterns
Claude Code and agent skill by rachit-sharma08/coding-agent-skills
- community
Checking that the SKILL.md file is still in the repository.
Advanced Next.js patterns - middleware, Server Actions, caching with
Install
npx vskill@latest install rachit-sharma08/coding-agent-skills/clerk-nextjs-patternsSKILL.md
The same SKILL.md was published earlier as rachit-sharma08/coding-agent-skills/clerk-nextjs-patterns.
Next.js Patterns
Version: Checkpackage.jsonfor the SDK version — seeclerkskill for the version table. Core 2 differences are noted inline with> **Core 2 ONLY (skip if current SDK):**callouts.
For basic setup, see clerk-setup skill.
Route protection: callawait auth.protect()in each page, Route Handler, and Server Function. KeepclerkMiddleware()bare.createRouteMatcheris deprecated in@clerk/nextjs7 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.
What Do You Need?
| Task | Reference | |
|---|---|---|
Server vs client auth (auth() vs hooks) | references/server-vs-client.md | |
| Protect routes (check in each page, handler, and Server Function) | references/middleware-strategies.md | |
| Protect Server Actions | references/server-actions.md | |
| API route auth (401 vs 403) | references/api-routes.md | |
| Cache auth data (user-scoped caching) | references/caching-auth.md |
References
| Reference | Description | |
|---|---|---|
references/server-vs-client.md | await auth() vs hooks | |
references/middleware-strategies.md | auth.protect() in each resource, bare clerkMiddleware() in proxy.ts (Next.js <=15: middleware.ts) | |
references/server-actions.md | Protect mutations | |
references/api-routes.md | 401 vs 403 | |
references/caching-auth.md | User-scoped caching |
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.
Key properties from auth():
isAuthenticated— boolean, replaces the!!userIdpatternsessionStatus—'active'|'pending', for detecting incomplete session tasksuserId,orgId,orgSlug,has(),protect()— unchanged
Core 2 ONLY (skip if current SDK):isAuthenticatedandsessionStatusare not available. Check!!userIdinstead.
Minimal Pattern
Core 2 ONLY (skip if current SDK):isAuthenticatedis not available. Useif (!userId)instead.
Conditional Rendering with <Show>
For client-side conditional rendering based on auth state. <Show> covers both authentication checks and authorization (feature, plan, role, permission) in one component.
Authentication check:
Authorization checks (B2B):
Callback for complex logic:
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. Seeclerk-custom-uiskill,core-3/show-component.mdfor the full migration table.
Common Pitfalls
| Symptom | Cause | Fix | ||
|---|---|---|---|---|
undefined userId in Server Component | Missing await | await auth() not auth() | ||
| Auth not working on API routes | Missing matcher | Add `'/(api | trpc)(.*)' to proxy.ts (Next.js <=15: middleware.ts`) | |
| Cache returns wrong user's data | Missing userId in key | Include userId in unstable_cache key | ||
| Mutations bypass auth | Unprotected Server Action | Check auth() at start of action | ||
| 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 | ||
| Wrong HTTP error code | Confused 401/403 | 401 = not signed in, 403 = no permission |
Session Tokens & Custom JWTs
getToken() for external APIs
Pass a custom JWT to third-party services (Hasura, Supabase, etc.) using JWT templates defined in the Clerk dashboard.
Server-side (Server Component or Route Handler):
Client-side (Client Component):
getToken() returns null when the user is not authenticated — always null-check before use.
useSession() for session data
Access session metadata in client components:
Manual JWT verification (no Clerk middleware)
For standalone API servers that receive Clerk session tokens from the Authorization header or the __session cookie (same-origin).
Using `@clerk/backend` `verifyToken` (recommended):
Using `jsonwebtoken` (when you can't use @clerk/backend):
Token sources:
- Same-origin requests:
__sessioncookie (Clerk sets this automatically) - Cross-origin / mobile / API-to-API:
Authorization: Bearer <token>header
CRITICAL: Always checkexpandnbfclaims.verifyTokenfrom@clerk/backendhandles this automatically; with rawjsonwebtoken, setignoreExpiration: false(default) and ensureclockToleranceis minimal.
See Also
clerk-setup- Initial Clerk installclerk-orgs- B2B patterns (active org, role/permission gating)clerk-billing- Plan and feature entitlements withhas()clerk-webhooks- Sync user/org events to your databaseclerk-custom-ui- Theming and customization for built-in components
Docs
Security
- Security scanPassed, 100 of 100Pattern checks on the skill's files.
- Model reviewNot runA model review is scheduled for the next rescan.
Quality evaluation
- Task evaluationNot runNo evaluation yet. Run one in Skill Studio.
Source
- SKILL.md in the repositoryCheckingskills/clerk-nextjs-patterns/SKILL.md
Popularity
- 7-day trend score
- 0
Not refreshed yet.
Works with
Any agent vskill installs to: 56 targets in all. These 39 have a page on this site.
- Claude Code
- Cursor
- GitHub Copilot
- Windsurf
- Codex
- Gemini CLI
- Cline
- Amp
- Roo Code
- Goose
- Continue
- Kilo Code
- Junie
- Trae
- OpenHands
- Qwen Code
- AI Agent
- Tabnine Chat
- Sourcegraph Cody
- Amazon Q
- Firebase Genkit
- Sweep
- Devin
- Phind
- Mentat
- Claude Desktop
- Aider
- GPT Pilot
- Plandex
- bolt.new
- v0
- Replit Agent
- Anse
- TypingMind
- BetterChatGPT
- LibreChat
- Warp AI
- Pieces
- Fig AI
Embed badge
[](https://verified-skill.com/skills/rachit-sharma08/coding-agent-skills/clerk-nextjs-patterns)