environment-setup-guide
Guide developers through setting up development environments with proper tools, dependencies, and configurations
clerk-cost-tuning
Optimize Clerk costs and understand pricing. Use when planning budget, reducing costs, or understanding Clerk pricing model. Trigger with phrases like "clerk cost", "clerk pricing", "reduce clerk cost", "clerk billing", "clerk budget".
Full skill instructions
Understand Clerk pricing and optimize costs for your application.
| Tier | MAU Included | Price | Features |
|---|---|---|---|
| Free | 10,000 | $0 | Basic auth, 5 social providers |
| Pro | 10,000 | $25/mo | Custom domain, priority support |
| Enterprise | Custom | Custom | SSO, SLA, dedicated support |
// lib/session-optimization.ts
import { auth } from '@clerk/nextjs/server'
// Use session efficiently - avoid creating multiple sessions
export async function getOrCreateSession() {
const { userId, sessionId } = await auth()
// Prefer existing session over creating new ones
if (sessionId) {
return { userId, sessionId, isNew: false }
}
// Only create session when absolutely needed
return { userId, sessionId: null, isNew: true }
}
// Configure session lifetime appropriately
// Clerk Dashboard > Configure > Sessions
// Longer sessions = fewer re-authentications
// lib/guest-users.ts
// Use guest mode for non-essential features to reduce MAU
export function useGuestOrAuth() {
const { userId, isLoaded, isSignedIn } = useUser()
// Allow limited functionality without sign-in
const guestId = useMemo(() => {
if (typeof window === 'undefined') return null
let id = localStorage.getItem('guest_id')
if (!id) {
id = crypto.randomUUID()
localStorage.setItem('guest_id', id)
}
return id
}, [])
return {
userId: isSignedIn ? userId : null,
guestId: !isSignedIn ? guestId : null,
isGuest: !isSignedIn && !!guestId,
isLoaded
}
}
// Use guest ID for features that don't require auth
export async function savePreference(key: string, value: any) {
const { userId, guestId } = useGuestOrAuth()
if (userId) {
// Authenticated - save to user profile
await saveToUserProfile(userId, key, value)
} else if (guestId) {
// Guest - save to localStorage (no Clerk MAU cost)
localStorage.setItem(`pref_${key}`, JSON.stringify(value))
}
}
// Delay requiring sign-in until necessary
'use client'
import { useUser, SignInButton } from '@clerk/nextjs'
export function FeatureGate({ children, requiresAuth = false }) {
const { isSignedIn, isLoaded } = useUser()
// If feature doesn't require auth, show it
if (!requiresAuth) {
return children
}
if (!isLoaded) {
return <Skeleton />
}
if (!isSignedIn) {
return (
<div className="p-4 border rounded">
<p>Sign in to access this feature</p>
<SignInButton mode="modal">
<button className="btn">Sign In</button>
</SignInButton>
</div>
)
}
return children
}
// Usage - only count MAU when user accesses premium features
function App() {
return (
<div>
{/* Free features - no sign-in required */}
<PublicContent />
{/* Premium features - sign-in required */}
<FeatureGate requiresAuth>
<PremiumContent />
</FeatureGate>
</div>
)
}
// lib/batched-clerk.ts
import { clerkClient } from '@clerk/nextjs/server'
// Batch user lookups to reduce API calls
export async function batchGetUsers(userIds: string[]) {
if (userIds.length === 0) return []
const client = await clerkClient()
// Single API call instead of multiple getUser calls
const { data: users } = await client.users.getUserList({
userId: userIds,
limit: 100
})
return users
}
// Cache organization data
const orgCache = new Map<string, any>()
export async function getOrganization(orgId: string) {
if (orgCache.has(orgId)) {
return orgCache.get(orgId)
}
const client = await clerkClient()
const org = await client.organizations.getOrganization({ organizationId: orgId })
orgCache.set(orgId, org)
return org
}
// lib/cost-monitoring.ts
import { clerkClient } from '@clerk/nextjs/server'
export async function getMonthlyUsageEstimate() {
const client = await clerkClient()
// Get unique users this month
const startOfMonth = new Date()
startOfMonth.setDate(1)
startOfMonth.setHours(0, 0, 0, 0)
const { totalCount } = await client.users.getUserList({
limit: 1,
// Note: You may need to track this yourself
})
// Estimate cost
const includedMAU = 10000 // Pro tier
const extraUsers = Math.max(0, totalCount - includedMAU)
const estimatedCost = 25 + (extraUsers * 0.02)
return {
totalUsers: totalCount,
includedMAU,
extraUsers,
estimatedCost,
percentageUsed: (totalCount / includedMAU) * 100
}
}
// Alert when approaching limits
export async function checkUsageAlerts() {
const usage = await getMonthlyUsageEstimate()
if (usage.percentageUsed > 80) {
await sendAlert(`Clerk usage at ${usage.percentageUsed}% of included MAU`)
}
}
// Calculate monthly cost
function estimateMonthlyCost(
tier: 'free' | 'pro' | 'enterprise',
expectedMAU: number
): number {
switch (tier) {
case 'free':
return expectedMAU <= 10000 ? 0 : Infinity // Upgrade required
case 'pro':
const includedMAU = 10000
const basePrice = 25
const extraUsers = Math.max(0, expectedMAU - includedMAU)
return basePrice + (extraUsers * 0.02)
case 'enterprise':
return -1 // Contact sales
}
}
// Examples
console.log(estimateMonthlyCost('pro', 5000)) // $25
console.log(estimateMonthlyCost('pro', 20000)) // $225
console.log(estimateMonthlyCost('pro', 100000)) // $1825
| Issue | Cause | Solution |
|---|---|---|
| Unexpected bill | MAU spike | Implement usage monitoring |
| Feature limitations | Free tier limits | Upgrade to Pro |
| API limits | Heavy usage | Implement caching |
Proceed to clerk-reference-architecture for architecture patterns.
Guide developers through setting up development environments with proper tools, dependencies, and configurations
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...
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".
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'.
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"...
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".
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".
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.
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...
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.
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...
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...
Generate, edit, and beat-sync AI video with leading models in one workspace.
The world's fastest calendar for remote work
Transform Your Design with AI Designer by ImgCreator.ai
Revolutionizing Video Production with AI-Powered Creativity
Extend an image past the frame and let AI fill the new aspect ratio.
Discover your celebrity doppelgänger with StarByFace!
ChainClarity explains 700+ crypto whitepapers in plain English, with layered summaries, comparisons, research tools, alerts, and a $4.99 Pro plan.
Opus.ai: Revolutionize Your Web Experience