clerk-core-workflow-b

Implement session management and middleware with Clerk. Use when managing user sessions, configuring route protection, or implementing token refresh and custom JWT templates. Trigger with phrases like "clerk session", "clerk middleware", "clerk route protection", "clerk token", "clerk JWT".

25 stars

Best use case

clerk-core-workflow-b is best used when you need a repeatable AI agent workflow instead of a one-off prompt.

Implement session management and middleware with Clerk. Use when managing user sessions, configuring route protection, or implementing token refresh and custom JWT templates. Trigger with phrases like "clerk session", "clerk middleware", "clerk route protection", "clerk token", "clerk JWT".

Teams using clerk-core-workflow-b should expect a more consistent output, faster repeated execution, less prompt rewriting.

When to use this skill

  • You want a reusable workflow that can be run more than once with consistent structure.

When not to use this skill

  • You only need a quick one-off answer and do not need a reusable workflow.
  • You cannot install or maintain the underlying files, dependencies, or repository context.

Installation

Claude Code / Cursor / Codex

$curl -o ~/.claude/skills/clerk-core-workflow-b/SKILL.md --create-dirs "https://raw.githubusercontent.com/ComeOnOliver/skillshub/main/skills/jeremylongshore/claude-code-plugins-plus-skills/clerk-core-workflow-b/SKILL.md"

Manual Installation

  1. Download SKILL.md from GitHub
  2. Place it in .claude/skills/clerk-core-workflow-b/SKILL.md inside your project
  3. Restart your AI agent — it will auto-discover the skill

How clerk-core-workflow-b Compares

Feature / Agentclerk-core-workflow-bStandard Approach
Platform SupportNot specifiedLimited / Varies
Context Awareness High Baseline
Installation ComplexityUnknownN/A

Frequently Asked Questions

What does this skill do?

Implement session management and middleware with Clerk. Use when managing user sessions, configuring route protection, or implementing token refresh and custom JWT templates. Trigger with phrases like "clerk session", "clerk middleware", "clerk route protection", "clerk token", "clerk JWT".

Where can I find the source code?

You can find the source code on GitHub using the link provided at the top of the page.

SKILL.md Source

# Clerk Core Workflow B: Session & Middleware

## Overview
Implement session management and route protection with Clerk middleware. Covers `clerkMiddleware()` configuration, `auth()` patterns, custom session claims, JWT templates for external services, organization-scoped sessions, and session token v2.

## Prerequisites
- `@clerk/nextjs` installed with ClerkProvider wrapping the app
- Next.js 14+ with App Router
- Sign-in/sign-up flows working (`clerk-core-workflow-a` completed)

## Instructions

### Step 1: Configure clerkMiddleware with Route Matchers
```typescript
// middleware.ts (project root)
import { clerkMiddleware, createRouteMatcher } from '@clerk/nextjs/server'

const isPublicRoute = createRouteMatcher([
  '/',
  '/sign-in(.*)',
  '/sign-up(.*)',
  '/api/webhooks(.*)',
  '/pricing',
  '/blog(.*)',
])

const isAdminRoute = createRouteMatcher(['/admin(.*)'])
const isApiRoute = createRouteMatcher(['/api(.*)'])

export default clerkMiddleware(async (auth, req) => {
  // Public routes: no auth required
  if (isPublicRoute(req)) return

  // Admin routes: require org:admin role
  if (isAdminRoute(req)) {
    await auth.protect({ role: 'org:admin' })
    return
  }

  // All other routes: require authentication
  await auth.protect()
})

export const config = {
  matcher: [
    '/((?!_next|[^?]*\\.(?:html?|css|js(?!on)|jpe?g|webp|png|gif|svg|ttf|woff2?|ico|csv|docx?|xlsx?|zip|webmanifest)).*)',
    '/(api|trpc)(.*)',
  ],
}
```

**Key behavior:** `clerkMiddleware()` does NOT protect any routes by default. You must explicitly call `auth.protect()` for routes that require authentication. This is a design decision to avoid over-blocking.

### Step 2: Protect API Routes with auth()
```typescript
// app/api/data/route.ts
import { auth } from '@clerk/nextjs/server'

export async function GET() {
  const { userId, orgId, has } = await auth()

  if (!userId) {
    return Response.json({ error: 'Unauthorized' }, { status: 401 })
  }

  // Permission-based authorization
  if (!has({ permission: 'org:data:read' })) {
    return Response.json({ error: 'Forbidden' }, { status: 403 })
  }

  const data = orgId
    ? await db.items.findMany({ where: { organizationId: orgId } })
    : await db.items.findMany({ where: { ownerId: userId } })

  return Response.json({ data, userId, orgId })
}

export async function POST(req: Request) {
  const { userId, orgId, has } = await auth()
  if (!userId) return Response.json({ error: 'Unauthorized' }, { status: 401 })
  if (!has({ permission: 'org:data:write' })) {
    return Response.json({ error: 'Forbidden' }, { status: 403 })
  }

  const body = await req.json()
  const item = await db.items.create({
    data: { ...body, ownerId: userId, organizationId: orgId },
  })
  return Response.json({ item }, { status: 201 })
}
```

### Step 3: Server Component Auth Patterns
```typescript
// app/dashboard/page.tsx
import { auth, currentUser } from '@clerk/nextjs/server'
import { redirect } from 'next/navigation'

export default async function DashboardPage() {
  const { userId, orgId, orgRole, has, sessionClaims } = await auth()
  if (!userId) redirect('/sign-in')

  // auth() is free (JWT parsing) — use for lightweight checks
  const isAdmin = has({ role: 'org:admin' })

  // currentUser() costs a Backend API call — use only when you need full profile
  const user = await currentUser()

  return (
    <div>
      <h1>Welcome, {user?.firstName}</h1>
      <p>Organization: {orgId || 'Personal account'}</p>
      <p>Role: {orgRole || 'N/A'}</p>
      {isAdmin && <a href="/admin">Admin Panel</a>}
    </div>
  )
}
```

### Step 4: Custom Session Claims
Customize in **Dashboard > Sessions > Customize session token:**

```json
{
  "metadata": "{{user.public_metadata}}",
  "email": "{{user.primary_email_address}}"
}
```

Then declare types and access in code:
```typescript
// types/clerk.d.ts
declare global {
  interface CustomJwtSessionClaims {
    metadata?: {
      role?: string
      plan?: string
    }
    email?: string
  }
}
export {}
```

```typescript
// Access custom claims (no API call needed — embedded in JWT)
import { auth } from '@clerk/nextjs/server'

export async function GET() {
  const { sessionClaims } = await auth()

  const userPlan = sessionClaims?.metadata?.plan || 'free'
  const userEmail = sessionClaims?.email

  return Response.json({ plan: userPlan, email: userEmail })
}
```

**Warning:** Session token cookie limit is 4KB. Custom claims should be under 1.2KB. Store large data in your database, not in session claims.

### Step 5: JWT Templates for External Services
```typescript
// app/api/supabase-data/route.ts
import { auth } from '@clerk/nextjs/server'
import { createClient } from '@supabase/supabase-js'

export async function GET() {
  const { userId, getToken } = await auth()
  if (!userId) return Response.json({ error: 'Unauthorized' }, { status: 401 })

  // Get a JWT with Supabase-compatible claims
  // Configure the template in Dashboard > JWT Templates
  const supabaseToken = await getToken({ template: 'supabase' })

  const supabase = createClient(
    process.env.NEXT_PUBLIC_SUPABASE_URL!,
    process.env.NEXT_PUBLIC_SUPABASE_ANON_KEY!,
    { global: { headers: { Authorization: `Bearer ${supabaseToken}` } } }
  )

  const { data } = await supabase.from('items').select('*')
  return Response.json({ data })
}
```

Configure JWT template in **Dashboard > JWT Templates > New template**:
```json
{
  "sub": "{{user.id}}",
  "email": "{{user.primary_email_address}}",
  "role": "authenticated",
  "aud": "authenticated"
}
```

### Step 6: Organization-Scoped Sessions
```typescript
'use client'
import { useOrganizationList, useOrganization, useAuth } from '@clerk/nextjs'

export function OrgSwitcher() {
  const { organizationList, setActive, isLoaded } = useOrganizationList({
    userMemberships: { infinite: true },
  })
  const { organization } = useOrganization()

  if (!isLoaded) return <div>Loading orgs...</div>

  return (
    <div>
      <p>Active: {organization?.name || 'Personal account'}</p>
      <ul>
        {organizationList?.map(({ organization: org, membership }) => (
          <li key={org.id}>
            <button onClick={() => setActive({ organization: org.id })}>
              {org.name} ({membership.role})
            </button>
          </li>
        ))}
        <li>
          <button onClick={() => setActive({ organization: null })}>
            Personal account
          </button>
        </li>
      </ul>
    </div>
  )
}
```

### Step 7: Server Action Permission Guards
```typescript
'use server'
import { auth } from '@clerk/nextjs/server'

export async function deleteItem(itemId: string) {
  const { userId, orgId, has } = await auth()
  if (!userId) throw new Error('Unauthorized')
  if (!has({ permission: 'org:data:delete' })) {
    throw new Error('You do not have permission to delete items')
  }

  await db.items.delete({ where: { id: itemId, organizationId: orgId } })
  return { success: true }
}

export async function updateOrgSettings(settings: Record<string, any>) {
  const { orgId, has } = await auth()
  if (!orgId) throw new Error('No organization selected')
  if (!has({ role: 'org:admin' })) {
    throw new Error('Only admins can update organization settings')
  }

  await db.orgSettings.upsert({
    where: { orgId },
    update: settings,
    create: { orgId, ...settings },
  })
  return { success: true }
}
```

## Error Handling
| Issue | Cause | Solution |
|-------|-------|----------|
| Middleware redirect loop | Sign-in page not in `isPublicRoute` | Add `/sign-in(.*)` to public route matcher |
| 401 on API route | Token not forwarded | Include credentials in fetch or use server-side `auth()` |
| `orgId` is null | No active organization | Prompt user with `<OrganizationSwitcher />` |
| `has()` always false | Permission not assigned to role | Check Dashboard > Organizations > Roles |
| Session expired | Token TTL exceeded | Clerk auto-refreshes; if stuck, clear cookies |
| `auth() was called but clerkMiddleware() not detected` | Middleware missing or wrong location | Ensure `middleware.ts` at project root |

## Enterprise Considerations
- Session token v2 (default since April 2025) is more compact -- if your downstream services parse JWTs, verify they handle the new format
- `auth.protect()` in middleware returns a 401/redirect before reaching your route handler -- this is more efficient than checking `userId` in every route
- For permission-based access, prefer `has({ permission: '...' })` over `has({ role: '...' })` -- permissions decouple authorization from role names
- JWT templates support custom `iss`, `aud`, and `exp` claims for integrating with Hasura, Supabase, Convex, Neon, and other services
- Organization switching changes the active session scope instantly -- no page reload needed

## Resources
- [clerkMiddleware() Reference](https://clerk.com/docs/reference/nextjs/clerk-middleware)
- [auth() Reference](https://clerk.com/docs/reference/nextjs/app-router/auth)
- [Custom Session Tokens](https://clerk.com/docs/guides/sessions/customize-session-tokens)
- [JWT Templates](https://clerk.com/docs/guides/sessions/jwt-templates)

## Next Steps
Proceed to `clerk-webhooks-events` for webhook and event handling.

Related Skills

step-functions-workflow

25
from ComeOnOliver/skillshub

Step Functions Workflow - Auto-activating skill for AWS Skills. Triggers on: step functions workflow, step functions workflow Part of the AWS Skills skill category.

sprint-workflow

25
from ComeOnOliver/skillshub

Execute this skill should be used when the user asks about "how sprints work", "sprint phases", "iteration workflow", "convergent development", "sprint lifecycle", "when to use sprints", or wants to understand the sprint execution model and its convergent diffusion approach. Use when appropriate context detected. Trigger with relevant phrases based on skill purpose.

scorecard-marketing

25
from ComeOnOliver/skillshub

Build quiz and assessment funnels that generate qualified leads at 30-50% conversion. Use when the user mentions "lead magnet", "quiz funnel", "assessment tool", "lead generation", or "score-based segmentation". Covers question design, dynamic results by tier, and automated follow-up sequences. For landing page conversion, see cro-methodology. For full marketing plans, see one-page-marketing. Trigger with 'scorecard', 'marketing'.

n8n-workflow-generator

25
from ComeOnOliver/skillshub

N8N Workflow Generator - Auto-activating skill for Business Automation. Triggers on: n8n workflow generator, n8n workflow generator Part of the Business Automation skill category.

jira-workflow-creator

25
from ComeOnOliver/skillshub

Jira Workflow Creator - Auto-activating skill for Enterprise Workflows. Triggers on: jira workflow creator, jira workflow creator Part of the Enterprise Workflows skill category.

building-gitops-workflows

25
from ComeOnOliver/skillshub

This skill enables Claude to construct GitOps workflows using ArgoCD and Flux. It is designed to generate production-ready configurations, implement best practices, and ensure a security-first approach for Kubernetes deployments. Use this skill when the user explicitly requests "GitOps workflow", "ArgoCD", "Flux", or asks for help with setting up a continuous delivery pipeline using GitOps principles. The skill will generate the necessary configuration files and setup code based on the user's specific requirements and infrastructure.

git-workflow-manager

25
from ComeOnOliver/skillshub

Git Workflow Manager - Auto-activating skill for DevOps Basics. Triggers on: git workflow manager, git workflow manager Part of the DevOps Basics skill category.

fathom-core-workflow-b

25
from ComeOnOliver/skillshub

Sync Fathom meeting data to CRM and build automated follow-up workflows. Use when integrating Fathom with Salesforce, HubSpot, or custom CRMs, or creating automated post-meeting email summaries. Trigger with phrases like "fathom crm sync", "fathom salesforce", "fathom follow-up", "fathom post-meeting workflow".

fathom-core-workflow-a

25
from ComeOnOliver/skillshub

Build a meeting analytics pipeline with Fathom transcripts and summaries. Use when extracting insights from meetings, building CRM sync, or creating automated meeting follow-up workflows. Trigger with phrases like "fathom analytics", "fathom meeting pipeline", "fathom transcript analysis", "fathom action items sync".

exa-core-workflow-b

25
from ComeOnOliver/skillshub

Execute Exa findSimilar, getContents, answer, and streaming answer workflows. Use when finding pages similar to a URL, retrieving content for known URLs, or getting AI-generated answers with citations. Trigger with phrases like "exa find similar", "exa get contents", "exa answer", "exa similarity search", "findSimilarAndContents".

exa-core-workflow-a

25
from ComeOnOliver/skillshub

Execute Exa neural search with contents, date filters, and domain scoping. Use when building search features, implementing RAG context retrieval, or querying the web with semantic understanding. Trigger with phrases like "exa search", "exa neural search", "search with exa", "exa searchAndContents", "exa query".

evernote-core-workflow-b

25
from ComeOnOliver/skillshub

Execute Evernote secondary workflow: Search and Retrieval. Use when implementing search features, finding notes, filtering content, or building search interfaces. Trigger with phrases like "search evernote", "find evernote notes", "evernote search", "query evernote".