Skip to content
clerk-performance-tuning logo

Clerk Performance Tuning

clerk-performance-tuning

Optimize Clerk authentication performance. Use when improving auth response times, reducing latency, or optimizing Clerk SDK usage. Trigger with phrases like "clerk performance", "clerk optimization", "clerk slow", "clerk latency", "optimize clerk".

SKILL.md

Full skill instructions

Clerk Performance Tuning

Overview

Optimize Clerk authentication for best performance and user experience.

Prerequisites

  • Clerk integration working
  • Performance monitoring in place
  • Understanding of application architecture

Instructions

Step 1: Optimize Middleware

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

// Pre-compile route matchers (done once at startup)
const isPublicRoute = createRouteMatcher([
  '/',
  '/​sign-in(.*)',
  '/​sign-up(.*)',
  '/​api/​public(.*)',
  '/​api/​webhooks(.*)'
])

// Exclude static files from middleware processing
export const config = {
  matcher: [
    // Skip all static files and images
    '/((?!_next|[^?]*\\.(?:html?|css|js(?!on)|jpe?g|webp|png|gif|svg|ttf|woff2?|ico|csv|docx?|xlsx?|zip|webmanifest)).*)',
    // Always run for API routes
    '/(api|trpc)(.*)'
  ]
}

export default clerkMiddleware(async (auth, request) => {
  // Quick return for public routes
  if (isPublicRoute(request)) {
    return
  }

  // Protect other routes
  await auth.protect()
})

Step 2: Implement User Data Caching

// lib/​cached-user.ts
import { unstable_cache } from 'next/​cache'
import { clerkClient, currentUser } from '@clerk/​nextjs/​server'

// Cache user data with Next.js cache
export const getCachedUser = unstable_cache(
  async (userId: string) => {
    const client = await clerkClient()
    return client.users.getUser(userId)
  },
  ['user-data'],
  {
    revalidate: 60, // 1 minute cache
    tags: ['users']
  }
)

// In-memory cache for very frequent lookups
const userCache = new Map<string, { data: any; expiry: number }>()

export async function getUserFast(userId: string) {
  const cached = userCache.get(userId)
  const now = Date.now()

  if (cached && cached.expiry > now) {
    return cached.data
  }

  const user = await getCachedUser(userId)
  userCache.set(userId, {
    data: user,
    expiry: now + 30000 // 30 seconds
  })

  return user
}

// Invalidate cache on user update
export function invalidateUserCache(userId: string) {
  userCache.delete(userId)
}

Step 3: Optimize Token Handling

// lib/​optimized-auth.ts
'use client'
import { useAuth } from '@clerk/​nextjs'
import { useRef } from 'react'

// Cache tokens to avoid repeated async calls
export function useOptimizedAuth() {
  const { getToken, userId, isLoaded } = useAuth()
  const tokenCache = useRef<{
    token: string | null
    expiry: number
  } | null>(null)

  const getCachedToken = async () => {
    const now = Date.now()

    // Return cached token if still valid (with 5 min buffer)
    if (tokenCache.current &&
        tokenCache.current.token &&
        tokenCache.current.expiry > now + 300000) {
      return tokenCache.current.token
    }

    // Get fresh token
    const token = await getToken()

    if (token) {
      // Parse expiry from JWT
      const payload = JSON.parse(atob(token.split('.')[1]))
      tokenCache.current = {
        token,
        expiry: payload.exp * 1000
      }
    }

    return token
  }

  return { getCachedToken, userId, isLoaded }
}

// Optimized fetch with token
export function useAuthFetch() {
  const { getCachedToken } = useOptimizedAuth()

  return async (url: string, options: RequestInit = {}) => {
    const token = await getCachedToken()

    return fetch(url, {
      ...options,
      headers: {
        ...options.headers,
        Authorization: `Bearer ${token}`,
        'Content-Type': 'application/​json'
      }
    })
  }
}

Step 4: Lazy Load Auth Components

// components/​lazy-auth.tsx
'use client'
import dynamic from 'next/​dynamic'
import { Suspense } from 'react'

// Lazy load heavy auth components
const UserButton = dynamic(
  () => import('@clerk/​nextjs').then(mod => mod.UserButton),
  {
    loading: () => <div className="w-8 h-8 bg-gray-200 rounded-full animate-pulse" />,
    ssr: false
  }
)

const SignInButton = dynamic(
  () => import('@clerk/​nextjs').then(mod => mod.SignInButton),
  {
    loading: () => <button className="btn" disabled>Sign In</​button>,
    ssr: false
  }
)

export function LazyUserButton() {
  return (
    <Suspense fallback={<div className="w-8 h-8 bg-gray-200 rounded-full" />}>
      <UserButton afterSignOutUrl="/" />
    </​Suspense>
  )
}

Step 5: Optimize Server Components

// app/​dashboard/​page.tsx
import { auth } from '@clerk/​nextjs/​server'
import { Suspense } from 'react'

// Use streaming for auth-dependent content
export default async function DashboardPage() {
  return (
    <div>
      <h1>Dashboard</​h1>

      {/​* Stream user-specific content */​}
      <Suspense fallback={<UserDataSkeleton />}>
        <UserData />
      </​Suspense>

      {/​* Non-auth content renders immediately */​}
      <StaticContent />
    </​div>
  )
}

async function UserData() {
  const { userId } = await auth()

  // Parallel data fetching
  const [user, stats, notifications] = await Promise.all([
    getUser(userId!),
    getUserStats(userId!),
    getNotifications(userId!)
  ])

  return (
    <div>
      <UserProfile user={user} />
      <UserStats stats={stats} />
      <Notifications items={notifications} />
    </​div>
  )
}

Step 6: Edge Runtime Optimization

// app/​api/​fast-auth/​route.ts
import { auth } from '@clerk/​nextjs/​server'

// Use Edge runtime for faster cold starts
export const runtime = 'edge'

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

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

  // Edge-compatible response
  return Response.json({ userId })
}

Performance Metrics

OperationTargetOptimization
Middleware check< 10msRoute matcher pre-compilation
Token validation< 50msJWT caching
User fetch< 100msMulti-level caching
Page load (auth)< 200msStreaming + lazy load

Monitoring

// lib/​performance-monitor.ts
export function measureAuthPerformance<T>(
  name: string,
  operation: () => Promise<T>
): Promise<T> {
  const start = performance.now()

  return operation().finally(() => {
    const duration = performance.now() - start
    console.log(`[Clerk Perf] ${name}: ${duration.toFixed(2)}ms`)

    // Send to monitoring (DataDog, etc.)
    if (duration > 100) {
      console.warn(`[Clerk Perf] Slow operation: ${name}`)
    }
  })
}

// Usage
const user = await measureAuthPerformance('getUser', () =>
  clerkClient.users.getUser(userId)
)

Output

  • Optimized middleware configuration
  • Multi-level caching strategy
  • Token management optimization
  • Lazy loading for auth components

Error Handling

IssueCauseSolution
Slow page loadsBlocking auth callsUse Suspense boundaries
High latencyNo cachingImplement token/​user cache
Bundle sizeAll components loadedLazy load auth components
Cold startsNode runtimeUse Edge runtime

Resources

Next Steps

Proceed to clerk-cost-tuning for cost optimization strategies.

More skills from Dicklesworthstone

environment-setup-guide logo
Dicklesworthstone/pi_agent_rust

environment-setup-guide

Guide developers through setting up development environments with proper tools, dependencies, and configurations

1.8K 0
View
exa-policy-guardrails logo
Dicklesworthstone/pi_agent_rust

exa-policy-guardrails

Implement Exa lint rules, policy enforcement, and automated guardrails. Use when setting up code quality rules for Exa integrations, implementing pre-commit hooks, or configuring CI policy checks for Exa best practices. Trigger with phrases like "exa policy", "exa lint", "exa guardrails", "exa be...

1.8K 0
View
documenso-ci-integration logo
Dicklesworthstone/pi_agent_rust

documenso-ci-integration

Configure CI/CD pipelines for Documenso integrations. Use when setting up automated testing, deployment pipelines, or continuous integration for Documenso projects. Trigger with phrases like "documenso CI", "documenso GitHub Actions", "documenso pipeline", "documenso automated testing".

1.8K 0
View
openrouter-model-availability logo
Dicklesworthstone/pi_agent_rust

openrouter-model-availability

Build check model availability and implement fallback chains. Use when building resilient systems or handling model outages. Trigger with phrases like 'openrouter availability', 'openrouter fallback', 'openrouter model down', 'openrouter health check'.

1.8K 0
View
langfuse-enterprise-rbac logo
Dicklesworthstone/pi_agent_rust

langfuse-enterprise-rbac

Configure Langfuse enterprise organization management and access control. Use when implementing team access controls, configuring organization settings, or setting up role-based permissions for Langfuse projects. Trigger with phrases like "langfuse RBAC", "langfuse teams", "langfuse organization"...

1.8K 0
View
cursor-compliance-audit logo
Dicklesworthstone/pi_agent_rust

cursor-compliance-audit

Execute compliance and security auditing for Cursor usage. Triggers on "cursor compliance", "cursor audit", "cursor security review", "cursor soc2", "cursor gdpr". Use when analyzing or auditing cursor compliance audit. Trigger with phrases like "cursor compliance audit", "cursor audit", "cursor".

1.8K 0
View
apollo-ci-integration logo
Dicklesworthstone/pi_agent_rust

apollo-ci-integration

Configure Apollo.io CI/CD integration. Use when setting up automated testing, continuous integration, or deployment pipelines for Apollo integrations. Trigger with phrases like "apollo ci", "apollo github actions", "apollo pipeline", "apollo ci/cd", "apollo automated tests".

1.8K 0
View
python-script logo
Dicklesworthstone/pi_agent_rust

python-script

Create robust Python automation with full logging and safety checks. Use when tasks need complex data processing, authenticated API work, conditional file operations, or error handling beyond simple shell commands.

1.8K 0
View
posthog-multi-env-setup logo
Dicklesworthstone/pi_agent_rust

posthog-multi-env-setup

Configure PostHog across development, staging, and production environments. Use when setting up multi-environment deployments, configuring per-environment secrets, or implementing environment-specific PostHog configurations. Trigger with phrases like "posthog environments", "posthog staging", "po...

1.8K 0
View
ai-agents-architect logo
Dicklesworthstone/pi_agent_rust

ai-agents-architect

Expert in designing and building autonomous AI agents. Masters tool use, memory systems, planning strategies, and multi-agent orchestration. Use when: build agent, AI agent, autonomous agent, tool use, function calling.

1.8K 0
View
insecure-deserialization-checker logo
Dicklesworthstone/pi_agent_rust

insecure-deserialization-checker

Validate insecure deserialization checker operations. Auto-activating skill for Security Fundamentals. Triggers on: insecure deserialization checker, insecure deserialization checker Part of the Security Fundamentals skill category. Use when working with insecure deserialization checker functiona...

1.8K 0
View
path-traversal-finder logo
Dicklesworthstone/pi_agent_rust

path-traversal-finder

Manage path traversal finder operations. Auto-activating skill for Security Fundamentals. Triggers on: path traversal finder, path traversal finder Part of the Security Fundamentals skill category. Use when working with path traversal finder functionality. Trigger with phrases like "path traversa...

1.8K 0
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