Skip to content
clerk-sdk-patterns logo

Clerk SDK Patterns

clerk-sdk-patterns

Common Clerk SDK patterns and best practices. Use when implementing authentication flows, accessing user data, or integrating Clerk SDK methods in your application. Trigger with phrases like "clerk SDK", "clerk patterns", "clerk best practices", "clerk API usage".

SKILL.md

Full skill instructions

Clerk SDK Patterns

Overview

Learn common patterns and best practices for using the Clerk SDK effectively.

Prerequisites

  • Clerk SDK installed and configured
  • Basic understanding of React/​Next.js
  • ClerkProvider wrapping application

Instructions

Pattern 1: Server-Side Authentication

// app/​api/​protected/​route.ts
import { auth, currentUser } from '@clerk/​nextjs/​server'

export async function GET() {
  // Quick auth check
  const { userId, sessionId, orgId } = await auth()

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

  // Full user data when needed
  const user = await currentUser()

  return Response.json({
    userId,
    sessionId,
    orgId,
    email: user?.primaryEmailAddress?.emailAddress
  })
}

Pattern 2: Client-Side Hooks

'use client'
import { useUser, useAuth, useClerk, useSession } from '@clerk/​nextjs'

export function AuthenticatedComponent() {
  // User data and loading state
  const { user, isLoaded, isSignedIn } = useUser()

  // Auth utilities
  const { userId, getToken, signOut } = useAuth()

  // Full Clerk instance
  const clerk = useClerk()

  // Session info
  const { session } = useSession()

  // Get JWT token for API calls
  const callExternalAPI = async () => {
    const token = await getToken({ template: 'supabase' }) // or custom template
    const res = await fetch('https://api.example.com', {
      headers: { Authorization: `Bearer ${token}` }
    })
  }

  if (!isLoaded) return <div>Loading...</​div>
  if (!isSignedIn) return <div>Please sign in</​div>

  return <div>Welcome, {user.firstName}</​div>
}

Pattern 3: Protected Routes with Middleware

// middleware.ts
import { clerkMiddleware, createRouteMatcher } from '@clerk/​nextjs/​server'

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

const isProtectedRoute = createRouteMatcher([
  '/​dashboard(.*)',
  '/​api/​protected(.*)'
])

export default clerkMiddleware(async (auth, request) => {
  if (isProtectedRoute(request)) {
    await auth.protect()
  }
})

export const config = {
  matcher: ['/((?!.*\\..*|_next).*)', '/', '/(api|trpc)(.*)']
}

Pattern 4: Organization-Aware Queries

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

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

  // Check organization membership
  if (!orgId) {
    return Response.json({ error: 'No organization selected' }, { status: 400 })
  }

  // Check role-based access
  if (orgRole !== 'org:admin') {
    return Response.json({ error: 'Admin access required' }, { status: 403 })
  }

  // Query with organization scope
  const data = await db.query.resources.findMany({
    where: eq(resources.organizationId, orgId)
  })

  return Response.json(data)
}

Pattern 5: Custom JWT Templates

// Use custom JWT claims for external services
const { getToken } = useAuth()

// Standard Clerk token
const clerkToken = await getToken()

// Custom template for Supabase
const supabaseToken = await getToken({ template: 'supabase' })

// Custom template for Hasura
const hasuraToken = await getToken({ template: 'hasura' })

Output

  • Server and client authentication patterns
  • Protected route middleware
  • Organization-aware queries
  • Custom JWT tokens for integrations

Error Handling

ErrorCauseSolution
auth() returns nullNot in server contextUse in Server Components or API routes
useUser() not updatingComponent not re-renderingCheck ClerkProvider placement
getToken() failsTemplate not configuredConfigure JWT template in dashboard
orgId is nullNo organization selectedPrompt user to select organization

Examples

Complete Protected Page Pattern

// app/​dashboard/​page.tsx
import { auth, currentUser } from '@clerk/​nextjs/​server'
import { redirect } from 'next/​navigation'

export default async function DashboardPage() {
  const { userId } = await auth()

  if (!userId) {
    redirect('/​sign-in')
  }

  const user = await currentUser()

  return (
    <main>
      <h1>Dashboard</​h1>
      <UserProfile user={user} />
      <DashboardContent userId={userId} />
    </​main>
  )
}

Typed User Metadata

// types/​clerk.d.ts
interface UserPublicMetadata {
  tier: 'free' | 'pro' | 'enterprise'
  onboarded: boolean
}

interface UserPrivateMetadata {
  stripeCustomerId?: string
}

// Usage
const user = await currentUser()
const tier = user?.publicMetadata?.tier ?? 'free'

Resources

Next Steps

Proceed to clerk-core-workflow-a for user sign-up and sign-in flows.

More skills from majiayu000

xiaohongshu logo
majiayu000/claude-arsenal

xiaohongshu

xiaohongshu

286 148
View
agent-task-conductor logo
majiayu000/claude-skill-registry

agent-task-conductor

Conduct multi-agent task orchestration and workflow coordination.

663 1
View
conductor-setup logo
majiayu000/claude-skill-registry

conductor-setup

Initialize project with Conductor artifacts (product definition,

663 1
View
animation-designer logo
majiayu000/claude-skill-registry

animation-designer

Expert in web animations, transitions, and motion design using Framer Motion and CSS

663 1
View
diagramming logo
majiayu000/claude-skill-registry

diagramming

Creates Mermaid and ASCII diagrams for flowcharts, architecture, ERDs, state machines, mindmaps, and more. Use when user mentions diagram, flowchart, mermaid, ASCII diagram, text diagram, terminal diagram, visualize, C4, mindmap, architecture diagram, sequence diagram, ERD, or needs visual docume...

663 1
View
h3-pg logo
majiayu000/claude-skill-registry-data

h3-pg

PostgreSQL bindings for H3 hexagonal grid system. Use when working with H3 cells in Postgres, including spatial indexing, geometry/geography integration, and raster analysis.

23 1
View
conductor-development logo
majiayu000/claude-skill-registry

conductor-development

Context-Driven Development skill for projects using Conductor. Use this skill when you detect a `conductor/` directory in the project, when working on tasks defined in a `plan.md` file, or when the user asks about tracks, specs, or plans. Automatically applies TDD workflow, tracks task completion...

663 1
View
conductor-status logo
majiayu000/claude-skill-registry

conductor-status

Display project status, active tracks, and next actions

663 1
View
dockerization logo
majiayu000/claude-skill-registry

dockerization

Official Stakpak application containerization standard operating procedure, a step-by-step guidline to properly dockerize applications. This is a rule book curated by the Stakpak Team.

663 1
View

Popular AI tools

Kaiber logo
Video

Kaiber

Generate, edit, and beat-sync AI video with leading models in one workspace.

Paid
View
Vimcal logo
Productivity

Vimcal

The world's fastest calendar for remote work

Free
View

Transform Your Design with AI Designer by ImgCreator.ai

Freemium
View
Akool AI logo
Content & writing

Akool AI

Revolutionizing Video Production with AI-Powered Creativity

Paid
View

Extend an image past the frame and let AI fill the new aspect ratio.

Freemium
View
StarByFace logo
Security

StarByFace

Discover your celebrity doppelgänger with StarByFace!

Free
View
C

ChainClarity explains 700+ crypto whitepapers in plain English, with layered summaries, comparisons, research tools, alerts, and a $4.99 Pro plan.

Freemium
View
Opus Clip logo
Coding & apps

Opus Clip

Opus.ai: Revolutionize Your Web Experience

Free
View