Skip to main content
skill CX Codex

clerk-cost-tuning — Claude Code skill: what it does, how to install

clerk-cost-tuning — a skill that makes Clerk's MRU pricing concrete and trims the bill: auth only where it is needed, caching around the Backend API, a script for idle accounts.

MIT 1 installs ★ 2,935 updated 2026-10-29

Install into Claude Code · Skills CLI (Vercel) All methods and platforms ↓
npx skills add jeremylongshore/tons-of-skills-marketplace --skill clerk-cost-tuning -a claude-code
Open on GitHub

What clerk-cost-tuning does

Clerk charges per Monthly Retained User, and the skill starts by putting a number on that. Four plans: Free at $0 with 50,000 MRU included, Pro at $25/mo ($20/mo billed yearly), Business at $300/mo ($250/mo billed yearly), Enterprise custom. Every user past the included 50,000 adds $0.02. Only a person who comes back 24+ hours after signing up lands on the bill. Activity on sign-up day, crawlers and readers of public pages never count.

Then it edits the app: auth.protect() moves into middleware.ts and covers the routes you list, Clerk Backend API calls get wrapped in cache() and unstable_cache(), and you get an admin-only endpoint with the user total plus a script that lists accounts idle for 90 days. Its tools are Read, Write, Edit and Grep, so it writes and patches code while running the scripts stays with you.

An active Clerk account is the prerequisite. Without one the route and cache steps have nothing to attach to. Test instances are free and unlimited — try a narrower auth matcher there before it reaches production.

What it helps with

  • estimate what a jump from Free to Pro costs at your current MRU count
  • keep sign-in off public pages and scope it to the dashboard
  • cache user metadata so requests stop hitting the Backend API
  • list accounts with no sign-in for 90 days
  • expose an admin-only usage endpoint

Example prompts for the agent

  • Our Clerk bill jumped. Walk through the pricing tiers and tell me where we are overpaying.
  • Scope auth.protect() in middleware.ts to /dashboard and /settings, leave the public pages open.
  • Write a script that finds Clerk users who have not signed in for 90 days.

How to install clerk-cost-tuning

1Skills CLI (Vercel)

npx skills add jeremylongshore/tons-of-skills-marketplace --skill clerk-cost-tuning -a claude-code

2Manually: put the files in place

~/.claude/skills/clerk-cost-tuning/SKILL.md

Copy the whole skill folder; for one project use .claude/skills/clerk-cost-tuning/

Step by step, with commands for each platform: How to install skills in Claude Code: five ways

Questions about clerk-cost-tuning

How do I install clerk-cost-tuning in Claude Code?

Run npx skills add jeremylongshore/tons-of-skills-marketplace --skill clerk-cost-tuning -a claude-code. The skill file ends up at ~/.claude/skills/clerk-cost-tuning/SKILL.md.

What does clerk-cost-tuning do?

It explains how Clerk bills by MRU and changes the project to lower that bill: scoped auth on selected routes, caching in front of the Backend API, and an endpoint for watching usage.

Who counts as an MRU in Clerk?

Someone who returns to the app 24+ hours after signing up. Sign-up-day activity, bots and visitors who only read public pages are not counted.

Source text

SKILL.md · MIT
---
name: clerk-cost-tuning
description: '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".

  '
allowed-tools: Read, Write, Edit, Grep
version: 1.15.0
license: MIT
author: Jeremy Longshore <[email protected]>
tags:
- saas
- clerk
- cost-optimization
compatibility: Designed for Claude Code
---
# Clerk Cost Tuning

## Overview

Understand Clerk pricing and optimize costs. Clerk charges by Monthly Retained Users (MRU) — a user is counted as retained only when they return 24+ hours after signing up. Covers pricing tiers, MRU reduction strategies, caching to reduce API calls, and usage monitoring.

## Prerequisites

- Clerk account active
- Understanding of MRU (Monthly Retained Users)
- Application usage patterns known

## Instructions

### Step 1: Understand Clerk Pricing Model

| Plan | Price | MRU Included | Extra MRU |
|------|-------|-------------|-----------|
| Free (Hobby) | $0/mo | 50,000 MRU | N/A |
| Pro | $25/mo ($20/mo billed annually) | 50,000 MRU | $0.02/MRU |
| Business | $300/mo ($250/mo billed annually) | 50,000 MRU | $0.02/MRU |
| Enterprise | Custom | Custom | Custom |

Key pricing concepts:

- **MRU** = unique user who returns to your app 24+ hours after signing up ("first day free" — sign-up-day activity never counts)
- Users who sign up and never return are not billed
- Users who only visit public pages are not counted
- Bot/crawler sessions are not counted
- Test/development instances are free and unlimited

### Step 2: Reduce MRU Count

```typescript
// Strategy 1: Defer authentication — don't force sign-in until necessary
// middleware.ts
import { clerkMiddleware, createRouteMatcher } from '@clerk/nextjs/server'

const requiresAuth = createRouteMatcher([
  '/dashboard(.*)',
  '/settings(.*)',
  '/api/protected(.*)',
])

export default clerkMiddleware(async (auth, req) => {
  // Only require auth for specific routes (not entire site)
  if (requiresAuth(req)) {
    await auth.protect()
  }
})
```

```typescript
// Strategy 2: Use anonymous access for read-only features
// app/blog/[slug]/page.tsx
import { auth } from '@clerk/nextjs/server'

export default async function BlogPost({ params }: { params: { slug: string } }) {
  const { userId } = await auth() // Check but don't require
  const post = await db.post.findUnique({ where: { slug: params.slug } })

  return (
    <article>
      <h1>{post?.title}</h1>
      <div>{post?.content}</div>
      {userId ? <CommentForm /> : <p>Sign in to comment</p>}
    </article>
  )
}
```

### Step 3: Cache to Reduce API Calls

```typescript
// lib/user-cache.ts
import { cache } from 'react'
import { currentUser } from '@clerk/nextjs/server'

// Deduplicate within single request (free)
export const getUser = cache(async () => {
  return currentUser()
})

// Cross-request caching reduces Backend API calls
import { unstable_cache } from 'next/cache'
import { clerkClient } from '@clerk/nextjs/server'

export const getUserMetadata = unstable_cache(
  async (userId: string) => {
    const client = await clerkClient()
    const user = await client.users.getUser(userId)
    return user.publicMetadata
  },
  ['user-metadata'],
  { revalidate: 600 } // 10-minute cache
)
```

### Step 4: Monitor Usage

```typescript
// app/api/admin/clerk-usage/route.ts
import { auth, clerkClient } from '@clerk/nextjs/server'

export async function GET() {
  const { has } = await auth()
  if (!has({ role: 'org:admin' })) {
    return Response.json({ error: 'Admin only' }, { status: 403 })
  }

  const client = await clerkClient()
  const users = await client.users.getUserList({ limit: 1 })

  return Response.json({
    totalUsers: users.totalCount,
    // Estimate MRU based on recent sign-ins
    estimatedMRU: 'Check Clerk Dashboard > Billing for actual MRU',
    dashboardUrl: 'last-active?after=30d',
  })
}
```

### Step 5: Clean Up Inactive Users

```typescript
// scripts/cleanup-inactive-users.ts
import { createClerkClient } from '@clerk/backend'

const clerk = createClerkClient({ secretKey: process.env.CLERK_SECRET_KEY! })

async function findInactiveUsers(daysInactive = 90) {
  const cutoff = Date.now() - daysInactive * 24 * 60 * 60 * 1000
  const allUsers = await clerk.users.getUserList({ limit: 500 })

  const inactive = allUsers.data.filter(
    (user) => (user.lastSignInAt || 0) < cutoff
  )

  console.log(`Found ${inactive.length} users inactive for ${daysInactive}+ days`)
  console.log('Consider: notification campaign, data export, or account cleanup')

  return inactive
}

findInactiveUsers()
```

## Output

- Pricing model understood with MRU thresholds
- Route-level auth to minimize unnecessary MRU counts
- Request-level and cross-request caching reducing API calls
- Usage monitoring endpoint for admins
- Inactive user identification script

## Error Handling

| Issue | Cause | Solution |
|-------|-------|----------|
| Unexpected bill increase | MRU spike from bot traffic | Add bot detection, restrict auth to needed routes |
| Feature limitations | Free tier limits (no SSO, etc.) | Upgrade to Pro ($25/mo, or $20/mo billed annually) |
| High API call volume | No caching | Add React `cache()` + `unstable_cache()` |
| MRU count mismatch | Counting test users | Use separate dev instance (free, unlimited) |

## Examples

### Cost Estimation Script

```typescript
function estimateMonthlyCost(mru: number): string {
  if (mru <= 50_000) return 'Free tier ($0/mo)'
  const overage = mru - 50_000
  const cost = 25 + overage * 0.02
  return `Pro tier: $${cost.toFixed(2)}/mo (${overage.toLocaleString()} extra MRU at $0.02 each)`
}

console.log(estimateMonthlyCost(15_000))  // "Free tier ($0/mo)"
console.log(estimateMonthlyCost(60_000))  // "Pro tier: $225.00/mo (10,000 extra MRU at $0.02 each)"
```

## Resources

- [Clerk Pricing](https://clerk.com/pricing)
- Clerk Usage Dashboard
- Clerk Fair Use Policy

## Next Steps

Proceed to `clerk-reference-architecture` for architecture patterns.

© Jeremy Longshore · MIT · jeremylongshore/tons-of-skills-marketplace

Similar skills

All skills for Backend and APIs →

From the same set139

The whole set →
juicebox-cost-tuning The juicebox-cost-tuning skill helps control Juicebox spending by cutting redundant searches and profile enrichment, then checking changes against a quota baseline. CX Codex +1 1installs twinmind-cost-tuning twinmind-cost-tuning picks a TwinMind tier and tracks where meeting minutes go. Handy when transcription costs climb and you need a clear picture. CX Codex +1 1installs openevidence-cost-tuning openevidence-cost-tuning evaluates OpenEvidence adoption and workflow burden in healthcare without inventing pricing, quotas, or telemetry. Helps prepare renewal briefs. CX Codex +1 1installs deepgram-cost-tuning The deepgram-cost-tuning skill outlines ways to track Deepgram spend, set budget checks for transcription, and reduce billable audio time through preprocessing. CX Codex +1 1installs lindy-cost-tuning lindy-cost-tuning audits Lindy AI credit usage, downsizes models, and consolidates agent workflows to cut monthly spending. CX Codex +1 1installs evernote-cost-tuning The evernote-cost-tuning skill helps track Evernote upload quotas, estimate note sizes, and spot storage-heavy notes. Use it when an integration needs quota checks before uploading attachments. CX Codex +1 1installs posthog-cost-tuning posthog-cost-tuning is a Claude Code skill for PostHog cost analysis: it measures which products drive the bill and trims capture noise without losing events needed for decisions. CX Codex +1 1installs ideogram-cost-tuning ideogram-cost-tuning controls prepaid Ideogram API consumption with admission ceilings, retry limits, and output tracking. Helps teams eliminate wasted spend on failed or duplicate runs. CX Codex +1 1installs

Project sponsors

Companies that keep this analytics open