Agent skill

Clerk Nextjs Patterns

by geekskai in geekskai/blog

Advanced Next.js patterns - middleware, Server Actions, caching with Clerk.

MITAuto-check passedBackend & APIs

Install Clerk Nextjs Patterns

skills CLI
$ npx skills add geekskai/blog --skill clerk-nextjs-patterns -a claude-code

Project install by default; add -g for ~/.claude/skills/.

GitHub CLI
$ gh skill install geekskai/blog clerk-nextjs-patterns --agent claude-code

Project scope by default; add --scope user for a personal install. Needs GitHub CLI 2.90.0 or later (public preview).

Manual copy
$ git clone --depth 1 https://github.com/geekskai/blog.git skills-src && mkdir -p .claude/skills && cp -r skills-src/.agents/skills/clerk-nextjs-patterns .claude/skills/clerk-nextjs-patterns && rm -rf skills-src

Use ~/.claude/skills/ instead of .claude/skills for a personal install. The folder must contain SKILL.md.

Claude Code skills documentation · loads skills from .claude/skills/

Facts

Skill name
clerk-nextjs-patterns
GitHub stars
103
Used in
2 other repos
Token cost
~2.1k tokens
SKILL.md length
513 words
Files
12 (incl. references)
Skills in repo
20
Repo updated
First seen
Licence
MIT

At a glance

Advanced Next.js patterns - middleware, Server Actions, caching with Clerk.

  • Tasks that involve Caching
  • SKILL.md covers What Do You Need?, References, Mental Model and Minimal Pattern, plus 4 more sections
  • Runs TypeScript scripts from its folder; needs CLERK_JWT_KEY and CLERK_PEM_PUBLIC_KEY
  • Tasks that involve Authentication

What it does

Clerk Nextjs Patterns is an agent skill from geekskai/blog. Advanced Next.js patterns - middleware, Server Actions, caching with Clerk.

Its SKILL.md is about 2.1k tokens, which your agent loads only when the skill is triggered. The skill folder holds 16 other files, including reference files (for example `evals/evals.json`, `references/api-routes.md` and `references/caching-auth.md`). Compatibility notes: Requires NEXTPUBLICCLERKPUBLISHABLEKEY and CLERKSECRETKEY. For manual JWT verification (standalone API servers without Clerk middleware), additionally…

It sits in Backend & APIs, covering Caching and Authentication. It works with Clerk and Next.js. The repository describes itself as: 🚀 2026 Most Popular FREE Blog Template! Next.js 14, Zero Code - Just Write & Deploy | 2026最火免费博客模板!支持Markdown,一键部署,极致性能!⚡️ ✨ Write in Markdown, get your professional blog in…. The licence is MIT.

When your agent uses it

  • Tasks that involve Caching
  • Tasks that involve Authentication

Example prompts

  • “/clerk-nextjs-patterns”

Requirements

  • Node.js
  • A credential in NEXT_PUBLIC_CLERK_PUBLISHABLE_KEY
  • A credential in CLERK_SECRET_KEY
  • Compatibility (from SKILL.md): 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.
  • Pre-approved tools (allowed-tools): WebFetch

What it can do on your machine

Read from SKILL.md and the folder at commit 347e8ab. It shows what the files ask for, not the result of running them.

  • Tool permissions

    Pre-approves these tools, so the agent can use them without asking each time:

    • WebFetch

    From allowed-tools in the SKILL.md frontmatter.

  • Runs code

    Ships script files (TypeScript), which the agent can run.

    From the folder's file list and the shell code blocks in SKILL.md.

  • Network

    Links to these hosts (documentation or services it may open):

    • clerk.com

    From URLs in SKILL.md, links to its own repository left out.

  • Credentials

    Names these keys or tokens, usually read from environment variables:

    • CLERK_JWT_KEY
    • CLERK_PEM_PUBLIC_KEY

    From names ending in _API_KEY, _TOKEN, _SECRET, _KEY or _PASSWORD in SKILL.md.

  • Compatibility

    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.

    From compatibility in the SKILL.md frontmatter.

Context cost

Clerk Nextjs Patterns loads about 2.1k tokens when it runs, and up to ~4.7k if it reads all its reference files. Until then it costs about 24 tokens; SKILL.md has 513 words of instructions outside code blocks.

Always · name and description, kept in context so the agent knows when to use it
~24
When it runs · the whole SKILL.md, loaded when a task matches
~2.1k
With references · SKILL.md plus every file in references/, read only if the agent opens them
~4.7k

Estimates: characters ÷ 4, the usual rule of thumb; real counts depend on the model's tokenizer. Scripts and assets cost tokens only if the agent reads them.

Safety

Auto-check passed

The automated check found no risky patterns in SKILL.md.

Automated static check — not a guarantee. Review scripts before installing. It scans the text of SKILL.md for risky patterns (piping downloads into a shell, reading credential files, hidden Unicode, destructive commands); files beside SKILL.md are not scanned.

SKILL.md

The full file from geekskai/blog at commit 347e8ab, republished under its MIT licence (© geekskai). 513 words, ~2,072 tokens.

Download SKILL.mdSave it as .claude/skills/clerk-nextjs-patterns/SKILL.md (or your agent's skills folder). This skill also uses 11 other files; get the full folder from GitHub.
name
clerk-nextjs-patterns
description
Advanced Next.js patterns - middleware, Server Actions, caching with Clerk.
allowed-tools
WebFetch
compatibility
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.
license
MIT
metadata.author
clerk
metadata.version
2.2.0

Next.js Patterns

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.

For basic setup, see clerk-setup skill.

What Do You Need?

TaskReference
Server vs client auth (auth() vs hooks)references/server-vs-client.md
Configure middleware (public-first vs protected-first)references/middleware-strategies.md
Protect Server Actionsreferences/server-actions.md
API route auth (401 vs 403)references/api-routes.md
Cache auth data (user-scoped caching)references/caching-auth.md

References

ReferenceDescription
references/server-vs-client.mdawait auth() vs hooks
references/middleware-strategies.mdPublic-first vs protected-first, proxy.ts (Next.js <=15: middleware.ts)
references/server-actions.mdProtect mutations
references/api-routes.md401 vs 403
references/caching-auth.mdUser-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 !!userId pattern
  • sessionStatus — 'active' | 'pending', for detecting incomplete session tasks
  • userId, orgId, orgSlug, has(), protect() — unchanged

Core 2 ONLY (skip if current SDK): isAuthenticated and sessionStatus are not available. Check !!userId instead.

Minimal Pattern

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

export default async function Page() {
  const { isAuthenticated, userId } = await auth()  // MUST await!
  if (!isAuthenticated) return <p>Not signed in</p>
  return <p>Hello {userId}</p>
}

Core 2 ONLY (skip if current SDK): isAuthenticated is not available. Use if (!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:

tsx
import { Show } from '@clerk/nextjs'

<Show when="signed-in" fallback={<p>Please sign in</p>}>
  <Dashboard />
</Show>

Authorization checks (B2B):

tsx
// Feature-based (preferred — features can move between plans without redeploy)
<Show when={{ feature: 'analytics' }} fallback={<UpgradePrompt />}>
  <AnalyticsDashboard />
</Show>

// Permission-based (preferred over role-based for granular access)
<Show when={{ permission: 'org:invoices:create' }}>
  <NewInvoiceButton />
</Show>

// Plan-based (tier-level gating)
<Show when={{ plan: 'pro' }}>
  <ProFeatures />
</Show>

// Role-based (use sparingly — prefer permission)
<Show when={{ role: 'org:admin' }}>
  <AdminPanel />
</Show>

Callback for complex logic:

tsx
<Show when={(has) => has({ role: 'org:admin' }) || has({ role: 'org:billing_manager' })}>
  <BillingActions />
</Show>

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.

Common Pitfalls

SymptomCauseFix
undefined userId in Server ComponentMissing awaitawait 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
Show full SKILL.md (172 more words)Show less

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):

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

export default async function Page() {
  const { getToken } = await auth()
  const token = await getToken({ template: 'hasura' })
  if (!token) return <p>Not authenticated</p>

  const res = await fetch('https://api.example.com/graphql', {
    headers: { Authorization: `Bearer ${token}` },
  })
  const data = await res.json()
  return <pre>{JSON.stringify(data)}</pre>
}

Client-side (Client Component):

typescript
'use client'
import { useAuth } from '@clerk/nextjs'

export function DataFetcher() {
  const { getToken } = useAuth()

  async function fetchData() {
    const token = await getToken({ template: 'supabase' })
    if (!token) return

    const res = await fetch('https://api.example.com/data', {
      headers: { Authorization: `Bearer ${token}` },
    })
    return res.json()
  }

  return <button onClick={fetchData}>Fetch</button>
}

getToken() returns null when the user is not authenticated — always null-check before use.

useSession() for session data

Access session metadata in client components:

typescript
'use client'
import { useSession } from '@clerk/nextjs'

export function SessionInfo() {
  const { session } = useSession()
  if (!session) return null

  return (
    <p>
      Session {session.id} — last active: {session.lastActiveAt.toISOString()}
    </p>
  )
}
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):

typescript
import { verifyToken } from '@clerk/backend'

const token = req.headers.authorization?.replace('Bearer ', '')
if (!token) return res.status(401).json({ error: 'No token' })

try {
  const claims = await verifyToken(token, {
    jwtKey: process.env.CLERK_JWT_KEY,
  })
  // claims.sub = userId
} catch {
  return res.status(401).json({ error: 'Invalid token' })
}

Using jsonwebtoken (when you can't use @clerk/backend):

typescript
import jwt from 'jsonwebtoken'

const publicKey = process.env.CLERK_PEM_PUBLIC_KEY!.replace(/\\n/g, '\n')
const token = req.headers.authorization?.replace('Bearer ', '')
if (!token) return res.status(401).json({ error: 'No token' })

try {
  const claims = jwt.verify(token, publicKey, { algorithms: ['RS256'] }) as jwt.JwtPayload
  // Manually check exp and nbf (jsonwebtoken does this automatically, but verify azp if needed)
  // claims.sub = userId
} catch {
  return res.status(401).json({ error: 'Invalid or expired token' })
}

Token sources:

  • Same-origin requests: __session cookie (Clerk sets this automatically)
  • Cross-origin / mobile / API-to-API: Authorization: Bearer <token> header

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.

See Also

  • clerk-setup - Initial Clerk install
  • clerk-orgs - B2B patterns (active org, role/permission gating)
  • clerk-billing - Plan and feature entitlements with has()
  • clerk-webhooks - Sync user/org events to your database
  • clerk-custom-ui - Theming and customization for built-in components

Docs

Next.js SDK

© geekskai, MIT. Rendered from Markdown: HTML in the file is shown as text, images as links, and headings moved down two levels. Raw file

Files

SKILL.md and 11 other files (references) in .agents/skills/clerk-nextjs-patterns of geekskai/blog.

  • SKILL.md
  • evals/evals.json
  • references/api-routes.md
  • references/caching-auth.md
  • references/middleware-strategies.md
  • references/server-actions.md
  • references/server-vs-client.md
  • templates/nextjs-basic-auth/app/layout.tsx
  • templates/nextjs-basic-auth/app/page.tsx
  • templates/nextjs-basic-auth/package.json
  • templates/nextjs-basic-auth/proxy.ts
  • templates/nextjs-basic-auth/tsconfig.json

Open the folder on GitHubat commit 347e8ab

Used in 2 other repositories

We found 3 copies of this SKILL.md (exact, near-identical or edited) in other folders, from 2 other GitHub owners. This page covers the copy in geekskai/blog, which our catalogue first saw on October 7, 2026.

Compare with similar skills

Clerk Nextjs Patterns next to the 5 skills that share the most tags, products or categories with it. Stars are the repository's; “used in” counts other GitHub owners with a copy.

Clerk Nextjs Patterns compared with similar skills
SkillStarsUsed inTokensAuto-checkLicenceRepo updated
Clerk Nextjs Patterns this skillgeekskai/blog1032 repos~2.1kAutomated safety check: PassMIT
Wp Headless And Wpgraphqljorgerosal/wordpress-skills100—~1.7kAutomated safety check: PassMIT
Clerk AuthLeoYeAI/openclaw-master-skills2.2k—~6.1kAutomated safety check: NotesMIT
Clerkvvedantb/eva101—~510Automated safety check: PassMIT
Supabase Development and Debuggingsupabase/agent-skills2.7k3 repos~3.6kAutomated safety check: PassMIT
Supabasecurvenote/curvenote1695 repos~2.2kAutomated safety check: PassCustom licence

Similar skills

  • Wp Headless And Wpgraphql

    jorgerosal/wordpress-skills

    Headless WordPress and WPGraphQL review guidance. An agent skill from jorgerosal/wordpress-skills.

    100 GitHub stars~1.7k tokensUpdated 4 mo ago
    Backend & APIsAuto-check passed
  • Clerk Auth

    LeoYeAI/openclaw-master-skills

    Clerk auth with API Keys beta (Dec 2025), Next.js 16 proxy.ts (March 2025 CVE context), API version 2025-11-10 breaking changes, clerkMiddleware() options, webhooks, production considerations (GCP…

    2.2k GitHub stars~6.1k tokensUpdated 2 mo ago
    Backend & APIsAuto-check: notes
  • Clerk

    vvedantb/eva

    Clerk authentication router. An agent skill from vvedantb/eva.

    101 GitHub stars~510 tokensUpdated today
    Backend & APIsAuto-check passed
  • Official

    General Supabase skill for database, auth, Edge Functions, Realtime and storage work, plus client libraries, migrations, security audits, debugging and reading logs.

    2.7k GitHub starsUsed in 3 repos~3.6k tokens
    Backend & APIsAuto-check passed
  • Supabase

    curvenote/curvenote

    A skill your agent uses when doing ANY task involving Supabase.

    169 GitHub starsUsed in 5 repos~2.2k tokens
    Backend & APIsAuto-check passed
  • Apollo Client

    apollographql/skills

    Guide for building React applications with Apollo Client 4.x.

    116 GitHub stars~1.9k tokensUpdated today
    Backend & APIsAuto-check passed

More from geekskai/blog

All 20 skills in this repo
  • Clerk Android

    geekskai/blog

    Implement Clerk authentication for native Android apps using Kotlin and Jetpack Compose with clerk-android source-guided patterns.

    103 GitHub starsUsed in 1 repo~2.1k tokens
    Auto-check passed
  • React SPA auth patterns with @clerk/react for Vite/CRA - ClerkProvider setup, useAuth/useUser/useClerk hooks, React Router protected routes, custom sign-in flows.

    103 GitHub starsUsed in 1 repo~1k tokens
    Auto-check: notes
  • React Router v7/v8 patterns with Clerk — rootAuthLoader, getAuth in loaders, clerkMiddleware, protected routes, SSR user data, org switching.

    103 GitHub starsUsed in 1 repo~1.8k tokens
    Auto-check passed
  • TanStack React Start auth patterns with @clerk/tanstack-react-start - createServerFn, beforeLoad guards, loaders, Vinxi server.

    103 GitHub starsUsed in 1 repo~875 tokens
    Auto-check: notes
  • Astro patterns with Clerk — middleware, SSR pages, island components, API routes, static vs SSR rendering.

    103 GitHub stars~822 tokensUpdated yesterday
    Auto-check: notes
  • Clerk Billing

    geekskai/blog

    Clerk Billing for subscription management - render Clerk's PricingTable and in-app checkout drawer, configure subscription plans, seat-limit plans for B2B, feature entitlements with has(), and…

    103 GitHub stars~5.1k tokensUpdated yesterday
    Auto-check passed

Works with

Categories

Questions about Clerk Nextjs Patterns

What does Clerk Nextjs Patterns do?

Advanced Next.js patterns - middleware, Server Actions, caching with Clerk. Clerk Nextjs Patterns is an agent skill from geekskai/blog.js patterns - middleware, Server Actions, caching with Clerk.

When should I use Clerk Nextjs Patterns?

Clerk Nextjs Patterns fits situations like: tasks that involve Caching; tasks that involve Authentication.

How do I install Clerk Nextjs Patterns in Claude Code?

Run `npx skills add geekskai/blog --skill clerk-nextjs-patterns -a claude-code`. Or copy the skill folder (.agents/skills/clerk-nextjs-patterns in geekskai/blog) into .claude/skills/clerk-nextjs-patterns in your project. Claude Code loads it when a task matches its description.

How do I install Clerk Nextjs Patterns in Codex?

Run `npx skills add geekskai/blog --skill clerk-nextjs-patterns -a codex`. Or copy the skill folder (.agents/skills/clerk-nextjs-patterns in geekskai/blog) into .agents/skills/clerk-nextjs-patterns in your project. Codex loads it when a task matches its description.

Can I use Clerk Nextjs Patterns in Cursor, Gemini CLI or GitHub Copilot?

Cursor, Gemini CLI, GitHub Copilot and OpenCode also load SKILL.md folders. With the skills CLI, run `npx skills add geekskai/blog --skill clerk-nextjs-patterns -a cursor` (or -a gemini-cli, github-copilot or opencode for the others). To copy it by hand, put the folder in .cursor/skills/clerk-nextjs-patterns, .gemini/skills/clerk-nextjs-patterns, .github/skills/clerk-nextjs-patterns and .opencode/skills/clerk-nextjs-patterns in your project.

What does Clerk Nextjs Patterns need to run?

Going by SKILL.md and its folder, Clerk Nextjs Patterns needs TypeScript for the scripts in its folder and credentials named CLERK_JWT_KEY and CLERK_PEM_PUBLIC_KEY. Our summary lists: Node.js; A credential in NEXT_PUBLIC_CLERK_PUBLISHABLE_KEY; A credential in CLERK_SECRET_KEY. Its frontmatter pre-approves these tools: WebFetch. Compatibility (from SKILL.md): 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..

Does Clerk Nextjs Patterns access the network?

SKILL.md names 1 domain. As links in the text: clerk.com. This is read from the text; nothing was executed.

Is Clerk Nextjs Patterns safe to install?

Our automated static check of SKILL.md found no risky patterns, such as piping downloads into a shell, reading credential files or hidden Unicode. It is not a guarantee. Review the folder before installing.

What licence does Clerk Nextjs Patterns use?

Clerk Nextjs Patterns is published under the MIT licence (declared in SKILL.md). It allows redistribution, so the full SKILL.md is shown on this page.

How many tokens does Clerk Nextjs Patterns use?

About 2.1k tokens (SKILL.md is roughly 8.3k characters). Agents keep only the skill's name and description in context until a task matches; then they load SKILL.md in full. Its references folder adds about 2.6k tokens, read only when the agent opens those files.

What are the alternatives to Clerk Nextjs Patterns?

Skills that share tags, products or a category with Clerk Nextjs Patterns: Wp Headless And Wpgraphql (jorgerosal/wordpress-skills, 100 stars), Clerk Auth (LeoYeAI/openclaw-master-skills, 2.2k stars), Clerk (vvedantb/eva, 101 stars) and Supabase Development and Debugging (supabase/agent-skills, 2.7k stars). The comparison table on this page puts their stars, adoption, token cost, safety result and licence side by side.

Who maintains Clerk Nextjs Patterns?

geekskai (a GitHub user) maintains it in geekskai/blog, which has 103 GitHub stars. The repository holds 20 skills in this directory. The repository was last updated on October 6, 2026.

Source: geekskai/blog on GitHub. Facts on this page come from the repository at the commit we read; the author's words are quoted as theirs.