Install any skill in seconds. Free to start, no credit card required.
Get Started Free →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".
.claude/skills/jeremylongshore-clerk-performance-tuning/SKILL.md| Test case | Without → With | Effect | Δ tokens | Δ turns |
|---|---|---|---|---|
| case-01 | ✗→✓ | ▲ Improved | 25% | 0% |
| case-08 | ✗→✓ | ▲ Improved | 49% | 0% |
| case-09 | ✗→✓ | ▲ Improved | 30% | 0% |
| case-13 | ✗→✓ | ▲ Improved | 33% | 0% |
| case-17 | ✗→✓ | ▲ Improved | 170% | 0% |
Optimize Clerk authentication for best performance. Covers middleware optimization, user data caching, token handling, lazy loading, and edge runtime configuration.
typescript// middleware.ts — avoid running auth on static files import { clerkMiddleware, createRouteMatcher } from '@clerk/nextjs/server' const isPublicRoute = createRouteMatcher(['/', '/sign-in(.*)', '/sign-up(.*)', '/api/webhooks(.*)']) export default clerkMiddleware(async (auth, req) => { if (!isPublicRoute(req)) { await auth.protect() } }) // Restrict matcher to avoid processing static assets export const config = { matcher: [ // Skip _next, static files, and images '/((?!_next/static|_next/image|favicon.ico|.*\\.(?:svg|png|jpg|jpeg|gif|webp|ico)).*)', '/(api|trpc)(.*)', ], }
typescript// lib/cached-user.ts import { auth, currentUser } from '@clerk/nextjs/server' import { cache } from 'react' // React cache: deduplicates within a single request export const getAuthUser = cache(async () => { const { userId } = await auth() if (!userId) return null return currentUser() }) // Usage in multiple server components (only one Clerk API call per request): // const user = await getAuthUser()
For cross-request caching with unstable_cache:
typescriptimport { unstable_cache } from 'next/cache' import { clerkClient } from '@clerk/nextjs/server' export const getCachedUserProfile = unstable_cache( async (userId: string) => { const client = await clerkClient() const user = await client.users.getUser(userId) return { id: user.id, name: `${user.firstName} ${user.lastName}`, email: user.emailAddresses[0]?.emailAddress, imageUrl: user.imageUrl, } }, ['user-profile'], { revalidate: 300 } // Cache for 5 minutes )
typescript// lib/token-cache.ts let tokenCache: { token: string; expiresAt: number } | null = null export async function getOptimizedToken(getToken: () => Promise<string | null>) { // Reuse token if it has more than 30 seconds remaining if (tokenCache && tokenCache.expiresAt > Date.now() + 30_000) { return tokenCache.token } const token = await getToken() if (token) { const payload = JSON.parse(atob(token.split('.')[1])) tokenCache = { token, expiresAt: payload.exp * 1000 } } return token }
typescript// components/lazy-auth.tsx 'use client' import dynamic from 'next/dynamic' // Only load UserButton when needed (saves ~15KB) const UserButton = dynamic( () => import('@clerk/nextjs').then((mod) => mod.UserButton), { ssr: false, loading: () => <div className="w-8 h-8 rounded-full bg-gray-200 animate-pulse" /> } ) const SignInButton = dynamic( () => import('@clerk/nextjs').then((mod) => mod.SignInButton), { ssr: false } ) export { UserButton, SignInButton }
typescript// app/dashboard/page.tsx — parallel data fetching import { auth } from '@clerk/nextjs/server' import { Suspense } from 'react' export default async function Dashboard() { const { userId } = await auth() if (!userId) return null return ( <div> {/* Parallel loading with Suspense boundaries */} <Suspense fallback={<div>Loading profile...</div>}> <UserProfile userId={userId} /> </Suspense> <Suspense fallback={<div>Loading activity...</div>}> <RecentActivity userId={userId} /> </Suspense> </div> ) } async function UserProfile({ userId }: { userId: string }) { const profile = await getCachedUserProfile(userId) return <div>{profile.name}</div> } async function RecentActivity({ userId }: { userId: string }) { const activity = await db.activity.findMany({ where: { userId }, take: 10 }) return <ul>{activity.map((a) => <li key={a.id}>{a.description}</li>)}</ul> }
typescript// middleware.ts — runs on Vercel Edge (cold start <50ms vs ~250ms Node) import { clerkMiddleware } from '@clerk/nextjs/server' export default clerkMiddleware() // Clerk middleware is Edge-compatible by default on Vercel export const config = { matcher: ['/((?!_next/static|_next/image|favicon.ico).*)'], runtime: 'edge', // Explicitly opt into Edge Runtime }
cache() deduplicating user fetches within requests| Issue | Cause | Solution | |-------|-------|----------| | Slow initial page load | Blocking auth calls | Use Suspense boundaries for parallel loading | | High Clerk API latency | No caching | Use cache() and unstable_cache() | | Large JS bundle | All Clerk components loaded | Use dynamic() imports for auth UI components | | Slow middleware cold start | Node.js runtime | Switch to Edge Runtime on Vercel | | Stale cached user data | Cache not invalidated | Invalidate on user.updated webhook |
typescript// lib/perf-measure.ts export async function measureAuthTime() { const start = performance.now() const { userId } = await auth() const authMs = performance.now() - start console.log(`[Perf] auth() took ${authMs.toFixed(1)}ms, userId: ${userId}`) return { userId, authMs } }
Proceed to clerk-cost-tuning for cost optimization strategies.
| Case | Status | Duration (ms) | Turns | Tokens | Tool calls | ||||||||
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
| Without | With | Δ | Without | With | Δ | Without | With | Δ | Without | With | Δ | ||
case-01 | fail→pass | 16,994 | 12,367 | -27% | 1 | 1 | 0% | 3,297 | 4,136 | +25% | 0 | 0 | — |
case-02 | fail→fail | 18,939 | 13,532 | -29% | 1 | 1 | 0% | 3,830 | 4,408 | +15% | 0 | 0 | — |
case-03 | pass→pass | 13,361 | 8,830 | -34% | 1 | 1 | 0% | 2,651 | 3,438 | +30% | 0 | 0 | — |
case-04 | pass→pass | 8,785 | 4,771 | -46% | 1 | 1 | 0% | 1,712 | 2,585 | +51% | 0 | 0 | — |
case-05 | pass→pass | 8,995 | 6,026 | -33% | 1 | 1 | 0% | 1,790 | 2,810 | +57% | 0 | 0 | — |
case-06 | pass→pass | 22,721 | 4,264 | -81% | 1 | 1 | 0% | 1,725 | 2,424 | +41% | 0 | 0 | — |
case-07 | pass→pass | 28,483 | 7,593 | -73% | 1 | 1 | 0% | 2,031 | 2,934 | +44% | 0 | 0 | — |
case-08 | fail→pass | 10,928 | 6,805 | -38% | 1 | 1 | 0% | 1,919 | 2,865 | +49% | 0 | 0 | — |
case-09 | fail→pass | 12,464 | 6,485 | -48% | 1 | 1 | 0% | 2,137 | 2,777 | +30% | 0 | 0 | — |
case-10 | pass→pass | 7,979 | 4,809 | -40% | 1 | 1 | 0% | 1,306 | 2,420 | +85% | 0 | 0 | — |
case-11 | pass→pass | 14,575 | 9,538 | -35% | 1 | 1 | 0% | 2,566 | 3,523 | +37% | 0 | 0 | — |
case-12 | pass→pass | 6,423 | 2,428 | -62% | 1 | 1 | 0% | 985 | 2,028 | +106% | 0 | 0 | — |
case-13 | fail→pass | 16,225 | 10,209 | -37% | 1 | 1 | 0% | 2,594 | 3,459 | +33% | 0 | 0 | — |
case-14 | pass→pass | 8,261 | 8,106 | -2% | 1 | 1 | 0% | 1,394 | 3,239 | +132% | 0 | 0 | — |
case-15 | pass→pass | 12,380 | 6,498 | -48% | 1 | 1 | 0% | 2,126 | 2,797 | +32% | 0 | 0 | — |
case-16 | pass→pass | 10,002 | 6,986 | -30% | 1 | 1 | 0% | 1,704 | 2,980 | +75% | 0 | 0 | — |
case-17 | fail→pass | 6,720 | 7,117 | +6% | 1 | 1 | 0% | 1,155 | 3,113 | +170% | 0 | 0 | — |
case-18 | pass→pass | 8,173 | 4,044 | -51% | 1 | 1 | 0% | 1,445 | 2,351 | +63% | 0 | 0 | — |
case-19 | fail→pass | 12,197 | 11,187 | -8% | 1 | 1 | 0% | 2,349 | 3,895 | +66% | 0 | 0 | — |
case-20 | pass→pass | 10,751 | 10,509 | -2% | 1 | 1 | 0% | 1,874 | 3,456 | +84% | 0 | 0 | — |
case-21 | fail→pass | 15,878 | 12,274 | -23% | 1 | 1 | 0% | 2,677 | 3,829 | +43% | 0 | 0 | — |
case-22 | pass→pass | 14,691 | 14,191 | -3% | 1 | 1 | 0% | 2,458 | 3,999 | +63% | 0 | 0 | — |
DecimalAI ran this skill against gemini-3.6-flash twice over the same eval suite — once with the skill loaded and once without — and compared the two runs case by case. 22 cases were attempted. The headline lift of +32 percentage points is the difference between those two pass rates over the 22 comparable cases.
Without the skill loaded, the model failed this case. With it loaded, the same prompt on the same model passed. This is one improved case from the latest verified run; every case, including any that regressed, is in the table above.
Other measured skills in the registry, with their headline benchmark lift.