clerk-performance-tuning
Clerk認証のパフォーマンスを最適化します。 認証レスポンス時間の改善、レイテンシーの削減、またはClerk SDKの使用最適化に活用できます。「clerk performance」「clerk optimization」「clerk slow」「clerk latency」「optimize clerk」といったフレーズで起動します。
description の原文を見る
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 本文
Clerk パフォーマンスチューニング
概要
最高のパフォーマンスとユーザー体験のために Clerk 認証を最適化します。
前提条件
- Clerk 統合が正常に動作している
- パフォーマンス監視が配置されている
- アプリケーション アーキテクチャの理解
手順
ステップ 1: ミドルウェアの最適化
// 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()
})
ステップ 2: ユーザーデータキャッシング の実装
// 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)
}
ステップ 3: トークン処理の最適化
// 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'
}
})
}
}
ステップ 4: 認証コンポーネントの遅延読み込み
// 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>
)
}
ステップ 5: サーバーコンポーネントの最適化
// 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>
)
}
ステップ 6: Edge ランタイムの最適化
// 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 })
}
パフォーマンス メトリクス
| 操作 | ターゲット | 最適化 |
|---|---|---|
| ミドルウェアチェック | < 10ms | ルートマッチャーの事前コンパイル |
| トークン検証 | < 50ms | JWT キャッシング |
| ユーザーフェッチ | < 100ms | 複数レベルキャッシング |
| ページロード(認証) | < 200ms | ストリーミング + 遅延読み込み |
監視
// 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)
)
出力
- 最適化されたミドルウェア構成
- 複数レベルキャッシング戦略
- トークン管理の最適化
- 認証コンポーネントの遅延読み込み
エラー処理
| 問題 | 原因 | ソリューション |
|---|---|---|
| ページロードが遅い | 認証呼び出しがブロックしている | Suspense 境界線を使用する |
| レイテンシが高い | キャッシングがない | トークン/ユーザーキャッシュを実装する |
| バンドルサイズ | すべてのコンポーネントが読み込まれている | 認証コンポーネントを遅延読み込みする |
| コールドスタート | Node ランタイム | Edge ランタイムを使用する |
リソース
次のステップ
コスト最適化戦略については clerk-cost-tuning に進みます。
ライセンス: MIT(寛容ライセンスのため全文を引用しています) · 原本リポジトリ
詳細情報
- 作者
- Brmbobo
- リポジトリ
- Brmbobo/Web2podcast
- ライセンス
- MIT
- 最終更新
- 2026/1/26
Source: https://github.com/Brmbobo/Web2podcast / ライセンス: MIT
関連スキル
superpowers-streamer-cli
SuperPowers デスクトップストリーマーの npm パッケージをインストール、ログイン、実行、トラブルシューティングできます。ユーザーが npm から `superpowers-ai` をセットアップしたい場合、メールまたは電話でサインインもしくはアカウント作成を行いたい場合、ストリーマーを起動したい場合、表示されたコントロールリンクを開きたい場合、後で停止したい場合、またはソースコードへのアクセスなしに npm やランタイムの一般的な問題から復旧したい場合に使用します。
catc-client-ops
Catalyst Centerのクライアント操作・監視機能 - 有線・無線クライアントのリスト表示・フィルタリング、MACアドレスによる詳細なクライアント検索、クライアント数分析、時間軸での分析、SSIDおよび周波数帯によるフィルタリング、無線トラブルシューティング機能を提供します。MACアドレスやIPアドレスでのクライアント検索、サイト別やSSID別のクライアント数集計、無線周波数帯の分布分析、Wi-Fi信号の問題調査が必要な場合に活用できます。
ci-cd-and-automation
CI/CDパイプラインの設定を自動化します。ビルドおよびデプロイメントパイプラインの構築または変更時に使用できます。品質ゲートの自動化、CI内のテストランナー設定、またはデプロイメント戦略の確立が必要な場合に活用します。
shipping-and-launch
本番環境へのリリース準備を行います。本番環境へのデプロイ準備が必要な場合、リリース前チェックリストが必要な場合、監視機能の設定を行う場合、段階的なロールアウトを計画する場合、またはロールバック戦略が必要な場合に使用します。
linear-release-setup
Linear Releaseに向けたCI/CD設定を生成します。リリース追跡の設定、LinearのCIパイプライン構築、またはLinearリリースとのデプロイメント連携を実施する際に利用できます。GitHub Actions、GitLab CI、CircleCIなど複数のプラットフォームに対応しています。
tracking-application-response-times
API エンドポイント、データベースクエリ、サービスコール全体にわたるアプリケーションのレスポンスタイムを追跡・最適化できます。パフォーマンス監視やボトルネック特定の際に活用してください。「レスポンスタイムを追跡する」「API パフォーマンスを監視する」「遅延を分析する」といった表現で呼び出せます。