Clerk Integration Guide
Technology: clerk · Category: auth · Last reviewed: 2026-10-22
Source: https://tech-stack.codeamanilabs.org/guide/clerk
Insight:
Clerk is the managed auth layer — drop-in Next.js components handle sign-in, sessions, orgs, billing and machine tokens so you don't roll your own. Current major is Clerk Core 3 (
@clerk/nextjsv7):<ClerkProvider>mounts inside<body>,<Show>replaced<SignedIn>/<SignedOut>/<Protect>, and on Next.js 16 the middleware file isproxy.ts. The big 2026 shift:createRouteMatcher()is deprecated — keepclerkMiddleware()inproxy.ts, but putawait auth.protect()in every page, Route Handler and Server Action. Verify webhooks withverifyWebhook()and make handlers idempotent onsvix-id. SMS sign-in is a paid feature and only US/CA are on the SMS allowlist by default — enable Kenya (+254) explicitly. Self-hosted alternative when per-MRU pricing or aJOIN-able user table matters:better-auth/CLAUDE_CODE_INTEGRATION.md.
██████╗██╗ ███████╗██████╗ ██╗ ██╗
██╔════╝██║ ██╔════╝██╔══██╗██║ ██╔╝
██║ ██║ █████╗ ██████╔╝█████╔╝
██║ ██║ ██╔══╝ ██╔══██╗██╔═██╗
╚██████╗███████╗███████╗██║ ██║██║ ██╗
╚═════╝╚══════╝╚══════╝╚═╝ ╚═╝╚═╝ ╚═╝
Clerk Integration Guide
Focus: Adding Clerk authentication to codeAmani's Next.js apps from Claude Code — the Clerk CLI for setup, the Clerk MCP server for account work, resource-level route protection, verified webhooks, Organizations, Billing, machine auth, and Supabase/Neon RLS.
Overview
Clerk is a hosted authentication and user-management platform: prebuilt UI components, session JWTs, Organizations (multi-tenancy + RBAC), webhooks, social/enterprise SSO, MFA, passkeys, Clerk Billing (subscriptions on Stripe), and machine auth (API keys, M2M tokens, OAuth access tokens). It is codeAmani's default auth provider.
Current versions (npm, 2026-10-22):
| Package | Version | Notes |
|---|---|---|
@clerk/nextjs |
7.9.19 | Core 3. Peer deps: next ^15.2.8 || ^16.0.10 (and later 16.x), React 18 or 19 |
@clerk/backend |
3.26.1 | createClerkClient, verifyWebhook (@clerk/backend/webhooks) |
@clerk/express |
2.1.82 | clerkMiddleware() + getAuth(req) |
@clerk/react |
6.18.0 | Renamed from @clerk/clerk-react in Core 3 |
clerk (CLI) |
4.0.0 | npx -y clerk@latest init / doctor / deploy / mcp install |
@clerk/eslint-plugin |
0.2.0 | require-auth-protection rule (experimental — pin it) |
svix |
2.8.0 | Only for the raw-Svix fallback; verifyWebhook() doesn't need it |
Node.js ≥ 20.9.0 for every Core 3 package.
Official Documentation
| Resource | URL |
|---|---|
Clerk docs (append .md to any page for markdown) |
https://clerk.com/docs |
| Docs index for agents | https://clerk.com/docs/llms.txt |
| Next.js quickstart | https://clerk.com/docs/nextjs/getting-started/quickstart |
| Core 3 upgrade guide | https://clerk.com/docs/guides/development/upgrading/upgrade-guides/core-3 |
Migrate away from createRouteMatcher() |
https://clerk.com/docs/guides/development/upgrading/upgrade-guides/migrate-from-create-route-matcher |
clerkMiddleware() |
https://clerk.com/docs/reference/nextjs/clerk-middleware |
auth() |
https://clerk.com/docs/reference/nextjs/app-router/auth |
| Webhooks — sync data | https://clerk.com/docs/guides/development/webhooks/syncing |
| Clerk MCP server | https://clerk.com/docs/guides/ai/mcp/clerk-mcp-server |
| Clerk CLI | https://clerk.com/docs/cli |
| Machine auth | https://clerk.com/docs/guides/development/machine-auth/overview |
| Billing | https://clerk.com/docs/guides/billing/overview |
| Pricing | https://clerk.com/pricing |
What changed in 2026 (read this first)
| Area | Old pattern | Current pattern |
|---|---|---|
| Major version | Core 2 / @clerk/nextjs v6 |
Core 3 / v7 (released 2026-03-03) — run npx @clerk/upgrade |
| Middleware file | middleware.ts |
proxy.ts on Next.js 16+ (middleware.ts on ≤ 15) — same code |
| Route protection | createRouteMatcher() + auth.protect() in middleware |
createRouteMatcher() deprecated (v7.5.14). clerkMiddleware() stays, with no auth gate. Each page, Route Handler and Server Action calls await auth.protect() |
| Control components | <SignedIn> / <SignedOut> / <Protect> |
<Show when="signed-in" | "signed-out" | { role } | { permission } | { plan } | { feature }> |
| Provider placement | <ClerkProvider> wrapping <html> |
Inside <body> |
| Setup | npm i @clerk/nextjs + hand-written files |
npx -y clerk@latest init (no account needed; writes .env.local) |
| Redirect env vars | NEXT_PUBLIC_CLERK_AFTER_SIGN_IN_URL |
NEXT_PUBLIC_CLERK_SIGN_IN_FALLBACK_REDIRECT_URL (and …_FORCE_REDIRECT_URL) |
| Metadata writes | users.updateUser(id, { publicMetadata }) |
users.updateUserMetadata() (merge) or replaceUserMetadata() (overwrite). API version 2026-05-12 removed metadata from updateUser |
| Backend verify helpers | verifySecret() / verifyAccessToken() / verifyToken() on resources |
verify() (e.g. clerkClient.apiKeys.verify(secret)) |
| Express | req.auth, requireAuth() |
getAuth(req) (req.auth removed; requireAuth() deprecated) |
| MCP server | Docs/snippets only | Account tools too (apps, instance config, users, domains, production deploy) — OAuth sign-in required |
| Dashboard Secret keys | Visible any time | Shown only once, at creation (2026-10-19). Store it in the vault immediately |
| Expo native components | @clerk/expo/native |
@clerk/expo/native-components + npx expo install @clerk/expo-native-components (@clerk/expo 4.11.0+, 2026-10-20). Ship the new binary before any OTA update |
| SAML signing certs | One idp_certificate per connection |
Up to five via idp_certificates (2026-10-06) — rotate with zero sign-in failures |
MCP Server Setup
Official Clerk MCP server (revamped 2026-10-15)
Remote server, Streamable HTTP only (no SSE), at https://mcp.clerk.com/mcp. Every tool
needs an OAuth sign-in with your Clerk Dashboard account; you pick one workspace and the
server acts with your workspace Role.
# Claude Code (native HTTP transport) — then run /mcp → clerk → Authenticate
claude mcp add clerk --transport http https://mcp.clerk.com/mcp
# …or let the Clerk CLI register it in every detected AI client
npx -y clerk@latest mcp install
.mcp.json (project-scoped):
{
"mcpServers": {
"clerk": {
"type": "http",
"url": "https://mcp.clerk.com/mcp"
}
}
}
Clients without MCP OAuth support can bridge through npx -y mcp-remote https://mcp.clerk.com/mcp.
| Tool group | Tools |
|---|---|
| Identity | whoami |
| Applications | list_applications, get_application, create_application |
| Instance config | get_instance_config, get_instance_config_schema, patch_instance_config, put_instance_config (dry-run preview) |
| Users | list_users, create_user |
| Domains / DNS | list_domains, get_domain_status, check_domain_dns |
| Production | get_deploy_oauth_providers, create_production_instance (needs confirm: true, irreversible), set_oauth_provider_credentials |
| SDK snippets | clerk_sdk_snippet (bundles like b2b-saas, organizations), list_clerk_sdk_snippets |
| Feedback | submit_feedback, get_more_tools |
OAuth scopes requested: user:org:read, applications:read|manage, users:read|manage,
application_domains:read|manage. The server never returns Secret keys (pull them with
clerk env pull or the Dashboard). It sends a one-line, agent-written context summary per
tool call to Clerk for analytics (no inputs or results).
Building your own MCP server with Clerk as the OAuth provider: https://clerk.com/docs/nextjs/guides/ai/mcp/build-mcp-server (uses
@clerk/mcp-tools, currently 0.6.0).
Clerk CLI (clerk, v4.0.0)
| Command | Purpose |
|---|---|
npx -y clerk@latest init |
Detect framework, install SDK, write proxy.ts/provider/auth routes, provision an accountless app and write dev keys to .env.local |
clerk auth login / clerk link |
Sign in and claim/link the app |
clerk doctor [--fix] |
Validate the integration (also checks MCP reachability) |
clerk env pull |
Pull keys into the env file |
clerk config pull / config patch / config schema |
Instance auth settings as code (e.g. auth_phone) |
clerk enable orgs / enable billing --for users|orgs |
Toggle features |
clerk webhooks listen / webhooks verify |
Local webhook relay tunnel + offline signature check |
clerk deploy / deploy status --mode agent |
Dev → production (domain, DNS, OAuth creds) |
clerk api <path> |
Authenticated Backend/Platform API client |
clerk impersonate |
Short-lived sign-in link as a user |
Non-TTY shells run the CLI in agent mode automatically (JSON output, no prompts).
SDK Integration — Next.js (App Router)
flowchart TD
A["Request"] --> B["proxy.ts: clerkMiddleware()<br/>reads session, no gating"]
B --> C{"Resource type"}
C -->|"page / layout"| D["await auth.protect()<br/>→ redirect to sign-in"]
C -->|"Route Handler"| E["await auth.protect()<br/>→ 404, or 401 for machine tokens"]
C -->|"Server Action"| F["await auth.protect()<br/>→ 401"]
D --> G["Render with userId / orgId"]
E --> G
F --> G
Requirements (Core 3): Node.js ≥ 20.9.0; Next.js ≥ 15.2.3 per the upgrade guide (the
7.9.19 peer range is ^15.2.8 or ^16.0.10+). Prefer Next 15.5.18+ / 16.2.6+ — earlier
16.x builds are exposed to the GHSA-26hh-7cqf-hhc6 proxy bypass that Clerk's changelog flags.
npx -y clerk@latest init # recommended — signed in or not
npx -y clerk@latest doctor # verify afterwards
# manual fallback only if init failed:
npm install @clerk/nextjs@7.9.19
proxy.ts (Next.js 16) — session plumbing only
// proxy.ts (Next.js 16+). On Next.js ≤ 15 name it middleware.ts — same contents.
import { clerkMiddleware } from "@clerk/nextjs/server";
export default clerkMiddleware();
export const config = {
matcher: [
// Skip Next.js internals and static files, unless found in search params
"/((?!_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)(.*)",
// Always run for Clerk's frontend API routes
"/__clerk/(.*)",
],
};
clerkMiddleware() is still required — auth() won't work without it — but by default it
protects nothing. Use it for non-auth work (i18n, headers, frontendApiProxy, session-task
redirects). Add { debug: process.env.NODE_ENV === "development" } when debugging.
Protect each resource (the current recommendation)
// app/dashboard/page.tsx — Server Component
import { auth, currentUser } from "@clerk/nextjs/server";
export default async function DashboardPage() {
const { userId } = await auth.protect(); // redirects signed-out users to sign-in
const user = await currentUser(); // Backend API call — only when you need profile fields
return <h1>Welcome, {user?.firstName ?? userId}</h1>;
}
// app/api/projects/route.ts — Route Handler
import { auth } from "@clerk/nextjs/server";
export async function GET() {
const { isAuthenticated, userId, orgId, has } = await auth();
if (!isAuthenticated) return Response.json({ error: "Unauthorized" }, { status: 401 });
if (!has({ permission: "org:projects:read" })) {
return Response.json({ error: "Forbidden" }, { status: 403 });
}
return Response.json({ userId, orgId });
}
// app/dashboard/actions.ts — Server Action (middleware can never protect these: called by ID, not path)
"use server";
import { auth } from "@clerk/nextjs/server";
export async function renameProject(formData: FormData) {
const { userId } = await auth.protect(); // 401 when signed out
const name = String(formData.get("name") ?? "").slice(0, 120);
return { userId, name };
}
auth.protect() outcomes: signed in + authorized → returns the Auth object; signed in but
unauthorized → 404; signed out → redirect for documents, 401 for Server Actions,
404 for other session-token requests, 401 for machine-token requests. Use plain
auth() + isAuthenticated when you want your own 401/403 JSON.
Lint it so nothing ships unprotected (@clerk/eslint-plugin, ESLint ≥ 9 flat config):
// eslint.config.mjs
import clerkNext from "@clerk/eslint-plugin/next";
export default [
{
plugins: { "@clerk/next": clerkNext },
rules: {
"@clerk/next/require-auth-protection": [
"error",
{ protected: ["**"], public: ["app/sign-in/**", "app/sign-up/**", "app/api/webhooks/**"] },
],
},
},
];
npx --package @clerk/eslint-plugin clerk-next-fix-auth-protection --dry-run previews the
bulk fixer that inserts await auth.protect() where it's missing.
auth() vs currentUser()
| Helper | Cost | Returns | Use for |
|---|---|---|---|
await auth() |
Free (verified JWT claims) | isAuthenticated, userId, sessionId, orgId, orgRole, orgSlug, has(), getToken(), redirectToSignIn() |
Access checks, DB scoping |
await auth.protect(opts?) |
Free | Auth object or throws/redirects |
Gating a resource; accepts role, permission, has, token, unauthenticatedUrl, unauthorizedUrl |
await currentUser() |
Backend API call (rate-limited, deduped per request) | Backend User incl. privateMetadata |
Profile fields on the server — never pass the whole object to the client |
Both are async — always await. auth() only works in App Router server code with
clerkMiddleware() configured.
Client UI components
// app/layout.tsx — Core 3: <ClerkProvider> INSIDE <body>
import { ClerkProvider, Show, SignInButton, SignUpButton, UserButton } from "@clerk/nextjs";
export default function RootLayout({ children }: { children: React.ReactNode }) {
return (
<html lang="en">
<body>
<ClerkProvider>
<header>
<Show when="signed-out">
<SignInButton />
<SignUpButton />
</Show>
<Show when="signed-in">
<UserButton />
</Show>
</header>
{children}
</ClerkProvider>
</body>
</html>
);
}
<Show> mapping: <SignedIn> → when="signed-in", <SignedOut> → when="signed-out",
<Protect role="admin"> → when={{ role: "admin" }}, <Protect permission="…"> →
when={{ permission: "…" }}, <Protect condition={fn}> → when={fn}; plus
when={{ plan: "pro" }} / when={{ feature: "…" }} for Billing. fallback renders the else
branch. <Show> hides UI — it is not a security boundary.
Mount <SignIn /> / <SignUp /> on optional catch-all routes
(app/sign-in/[[...sign-in]]/page.tsx) so sub-paths like /sign-in/factor-one and
/sign-in/sso-callback resolve. With shadcn/ui: npm i @clerk/ui, then
appearance={{ theme: shadcn }} from @clerk/ui/themes and @import '@clerk/ui/themes/shadcn.css'.
Backend SDK (@clerk/backend / clerkClient)
import { clerkClient } from "@clerk/nextjs/server";
const client = await clerkClient();
const { data: users } = await client.users.getUserList({ limit: 10 });
// Metadata: dedicated endpoints since API version 2026-05-12
await client.users.updateUserMetadata(userId, { publicMetadata: { plan: "pro" } }); // deep merge
await client.users.replaceUserMetadata(userId, { privateMetadata: { tier: "gold" } }); // overwrite field
Recent @clerk/backend additions (3.24 → 3.26.1):
issueroption (3.25.0) onverifyJwt(),verifyToken()andauthenticateRequest()— a string or list of allowedissvalues. Applies to session tokens only; machine-token verification ignores it. Set it when one backend accepts tokens from several Clerk instances.user.deprovisioned(3.24.0) — set and cleared by Directory Sync, separate frombanned(which you set). Also arrives inuser.updatedwebhooks: treat it as "revoke app access".- Legacy JWT category rejected (3.26.1) —
authenticateRequest()now returns signed-out with reasontoken-type-mismatchfor the retiredcl_I7d4PD111IIIcategory. - Email webhook types (3.26.0) for delivery/bounce/complaint events ship ahead of a transactional-email pilot; the events only arrive once Clerk rolls out the backend side.
Outside Next.js: createClerkClient({ secretKey: process.env.CLERK_SECRET_KEY }) from
@clerk/backend. Backend API limit: 1,000 requests / 10 s (production), 100 / 10 s
(development) — currentUser() counts against it.
Node.js / Express
npm install @clerk/express@2.1.82
import express from "express";
import { clerkMiddleware, getAuth } from "@clerk/express";
const app = express();
app.use(clerkMiddleware());
app.get("/api/profile", (req, res) => {
const { isAuthenticated, userId, has } = getAuth(req);
if (!isAuthenticated) return void res.status(401).json({ error: "Unauthorized" });
if (!has({ permission: "org:profile:read" })) return void res.status(403).json({ error: "Forbidden" });
res.json({ userId });
});
requireAuth() is deprecated (and redirects — never use it for APIs); req.auth was removed
in Core 3.
Webhook Integration
sequenceDiagram
participant C as "Clerk (via Svix)"
participant R as "/api/webhooks/clerk"
participant DB as "Database"
C->>R: "POST + svix-id / svix-timestamp / svix-signature"
R->>R: "verifyWebhook(req)"
alt "invalid"
R-->>C: "400 (Svix retries)"
else "valid"
R->>DB: "seen svix-id? skip : upsert (compare updated_at)"
R-->>C: "200"
end
// app/api/webhooks/clerk/route.ts — reads CLERK_WEBHOOK_SIGNING_SECRET automatically
import { verifyWebhook } from "@clerk/nextjs/webhooks";
import type { NextRequest } from "next/server";
export async function POST(req: NextRequest) {
let evt;
try {
evt = await verifyWebhook(req);
} catch {
return new Response("Invalid signature", { status: 400 });
}
if (evt.type === "user.created" || evt.type === "user.updated") {
// upsert by evt.data.id; skip if stored updated_at > evt.data.updated_at
}
return new Response(null, { status: 200 });
}
Rules (from Clerk's webhook docs):
- At-least-once, unordered delivery. Dedupe on the
svix-idheader, upsert instead of insert, comparedata.updated_at(or the top-leveltimestampfor deletes), and don't let late events resurrect deleted rows. - Route must be public — it carries no session. Exclude
app/api/webhooks/**from the lint rule's protected set. - Non-2xx → Svix retries on its schedule; failed messages can be replayed from the Dashboard.
- Optionally allow only Svix's webhook IPs.
- Webhooks are eventually consistent — never block onboarding on one; if data fits in the session token (< 1.2 KB of metadata) read it from the token instead of syncing.
- Billing has its own events:
subscription.created|updated|active|pastDue,subscriptionItem.active|canceled|ended|pastDue|freeTrialEnding|…,paymentAttempt.created|updated. - Outside Next.js:
verifyWebhookfrom@clerk/backend/webhooks; rawsvixWebhook.verify()still works for other runtimes. - Local testing:
clerk webhooks listen(relay tunnel, no ngrok needed) or ngrok.
Organizations (B2B)
- Enable with
npx -y clerk@latest enable orgs. Users can belong to many orgs; the Active Organization (per browser tab) setsorgId/orgRole/ permissions on the session. - Default roles
org:admin/org:member; custom permissions on all plans; custom roles, role sets, verified domains and unlimited members need the B2B Authentication add-on. - Check with
has({ role }),has({ permission }),auth.protect({ permission }), or<Show when={{ permission }}>. Components:<OrganizationSwitcher />,<OrganizationProfile />,<CreateOrganization />,<OrganizationList />. - Free: 100 MROs per production app (50 in development), max 20 members per org.
Enterprise SSO (B2B customers)
- Self-serve SSO + Directory Sync (2026-09-30): a customer admin with
org:sys_entconns:managesets up their IdP and SCIM provisioning from the Security tab of<OrganizationProfile />— no Dashboard access needed. Enable per org under Settings → Allow this organization to set up enterprise SSO and Directory Sync. Production needs Pro or Business plus the B2B Authentication add-on; Directory Sync is billed from 2027-01-01. - SSO bypass (2026-09-29): an allowlist of users can sign in with an email code when the
IdP is down ("Can't use SSO?" in
<SignIn />). Requires Email verification code sign-in. Every use logssign_in.sso_bypass.succeeded— keep the allowlist to the admins who fix SSO. - SAML certificate rotation (2026-10-06): a connection trusts up to five signing certs.
Add the IdP's next cert early, let it switch, then remove the old one. The Backend API field
is
idp_certificates(full list replaces; singleidp_certificateis deprecated).
Clerk Billing (subscriptions on Stripe)
- Plans, Features and Subscriptions live in Clerk (not synced to Stripe Billing). Stripe is only the payment processor. Fee: 0.7% of billing volume on top of Stripe's 2.9% + $0.30.
- Enable:
npx -y clerk@latest enable billing --for users(B2C) or--for orgs(B2B). Development uses Clerk's shared test gateway; production needs your own Stripe account (not one controlled by another platform's Connect). - UI:
<PricingTable />,<CheckoutButton />,<PlanDetailsButton />,<SubscriptionDetailsButton />; gate withhas({ plan: "pro" })/has({ feature: "…" })or<Show when={{ plan: "pro" }}>. - Limits: USD only, no tax/VAT, no refunds via Clerk, no 3-D Secure, not Merchant of Record, checkout is web-only. Not available in Brazil, India, Malaysia, Mexico, Singapore, Thailand.
Machine auth: API keys, M2M tokens, OAuth tokens
| Token | Use case | Create | Verify (Next.js) |
|---|---|---|---|
| API keys (GA 2026-04) | Your users/orgs call your API | <UserProfile>/<OrganizationProfile> "API Keys" tab, <APIKeys />, or clerkClient.apiKeys.create({ name, subject }) |
auth({ acceptsToken: "api_key" }) → subject, scopes, claims |
| M2M tokens | Service ↔ service inside your infra | clerkClient.m2m.createToken({ tokenFormat: "jwt" }) with CLERK_MACHINE_SECRET_KEY |
auth({ acceptsToken: "m2m_token" }) or clerkClient.m2m.verify({ token }) |
| OAuth access tokens | Third-party apps / MCP clients acting for a user | Clerk as OAuth provider | auth({ acceptsToken: "oauth_token" }) |
acceptsToken defaults to session_token, so machine tokens are rejected unless you opt in.
API-key secrets are returned once, from create(). JWT-format M2M tokens verify locally
(no per-verify fee) but can't be revoked or listed; opaque ones can. Clerk does not support the
OAuth client-credentials flow yet.
Database integration (third-party auth + RLS)
Supabase
- Clerk Dashboard → Supabase integration setup → Activate (adds
"role": "authenticated"to session tokens) → copy the Clerk domain. - Supabase Dashboard → Authentication → Sign In / Providers → Third-Party Auth → Clerk → paste the domain. (The old JWT-template + shared-secret path is deprecated since 2025-04-01.)
- Owner column is
text(Clerk IDs areuser_…), defaultauth.jwt()->>'sub'; policies compare(select auth.jwt()->>'sub') = user_id. - Pass the Clerk session token through
createClient(url, publishableKey, { accessToken }).
// lib/supabase-server.ts
import { auth } from "@clerk/nextjs/server";
import { createClient } from "@supabase/supabase-js";
export function createServerSupabaseClient() {
return createClient(
process.env.NEXT_PUBLIC_SUPABASE_URL!,
process.env.NEXT_PUBLIC_SUPABASE_PUBLISHABLE_KEY!,
{ async accessToken() { return (await auth()).getToken(); } },
);
}
Full pattern: supabase/CLAUDE_CODE_INTEGRATION.md and examples/supabase-rls.ts.
Neon
- Server-side (default): query Neon from Route Handlers / Server Actions with the
connection string and scope every query by
userIdfromawait auth()(Clerk's Neon guide uses Drizzle +@neondatabase/serverless). - Data API + RLS: Neon Console → Data API → Other Provider → JWKS URL
https://<your-clerk-frontend-api-domain>/.well-known/jwks.json(Dashboard → API keys → Show JWT public key). RLS policies useauth.user_id()(frompg_session_jwt). Send the Clerk session token as theAuthorization: Bearerheader. Neon's Data API has no permission layer of its own — GRANTs + RLS are the whole boundary. - Neon Functions have public URLs: verify the Clerk JWT with
joseagainst the JWKS (neon/PATTERNS.md).
Phone / SMS sign-in (Kenya-targeted projects)
- Phone + SMS OTP is a paid feature in production (free in development). Pricing page: SMS codes not on Hobby; Pro+ pays per SMS — $0.01 for US/Canada, "market rate" internationally (Kenya's per-SMS rate is not published — check the Dashboard).
- SMS allowlist: only US and Canada are enabled by default. Enable Kenya (+254) under Dashboard → Customization → SMS → Settings; disabled countries can't sign up, receive OTPs, or add the number.
- Codes stay valid 10 minutes; prebuilt components enforce a 30 s resend cooldown. Rate limits: create sign-in 5 / 10 s, attempt factor 3 / 10 s.
- Trace delivery in Application Logs → SMS logs (
sms.accepted|delivered|failed|undeliverable|unconfirmed, with areason). - Configure as code:
npx -y clerk@latest config patch(keys likeauth_phone). - Store numbers in E.164 (
+2547…). The M-Pesa254XXXXXXXXXformat is a separate normalization for Daraja — don't reuse the Clerk value without stripping+.
Environment Variables
Secrets (server-only — store in the vault / Vercel env, never NEXT_PUBLIC_):
CLERK_SECRET_KEY=sk_test_...
CLERK_WEBHOOK_SIGNING_SECRET=whsec_...
CLERK_MACHINE_SECRET_KEY=ak_...
CLERK_ENCRYPTION_KEY=replace-with-128-bit-random-value
CLERK_MACHINE_SECRET_KEY is only for M2M; CLERK_ENCRYPTION_KEY is only needed when you pass
secretKey to clerkMiddleware() (dynamic keys).
Non-secret settings:
| Variable | Example | Notes |
|---|---|---|
NEXT_PUBLIC_CLERK_PUBLISHABLE_KEY |
pk_test_… / pk_live_… |
Public by design |
NEXT_PUBLIC_CLERK_SIGN_IN_URL |
/sign-in |
|
NEXT_PUBLIC_CLERK_SIGN_UP_URL |
/sign-up |
|
NEXT_PUBLIC_CLERK_SIGN_IN_FALLBACK_REDIRECT_URL |
/dashboard |
Replaces deprecated …_AFTER_SIGN_IN_URL |
NEXT_PUBLIC_CLERK_SIGN_UP_FALLBACK_REDIRECT_URL |
/onboarding |
Replaces deprecated …_AFTER_SIGN_UP_URL |
NEXT_PUBLIC_CLERK_PROXY_URL |
https://app.example.com/__clerk |
Only with a Frontend API proxy |
NEXT_PUBLIC_CLERK_TELEMETRY_DISABLED |
1 |
Opt out of telemetry |
The Dashboard now shows a Secret key only once, at creation — copy it straight into the
vault. clerk init / clerk env pull write keys for you; don't paste them into chat.
Automation Workflows
Slash command: scaffold auth
.claude/commands/clerk-auth.md:
Add Clerk authentication to this Next.js App Router project.
1. Check for existing auth first; if found, stop and ask before migrating.
2. Run `npx -y clerk@latest init` (do not hand-write setup unless it fails).
3. Confirm `proxy.ts` (Next 16) or `middleware.ts` (Next ≤15) exports `clerkMiddleware()` with the standard matcher and NO createRouteMatcher gate.
4. Confirm `<ClerkProvider>` is inside `<body>` and the header uses `<Show>`.
5. Add `await auth.protect()` to every protected page, Route Handler and Server Action.
6. Add `@clerk/eslint-plugin` with `require-auth-protection` (public: sign-in, sign-up, api/webhooks).
7. Create `app/api/webhooks/clerk/route.ts` with `verifyWebhook()` and idempotent upserts.
8. Run `npx -y clerk@latest doctor` and report what's left (webhook secret, SMS allowlist, prod deploy).
CI check
# .github/workflows/clerk-check.yml
name: Clerk auth guardrails
on: [pull_request]
jobs:
lint:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
- uses: actions/setup-node@v4
with: { node-version: "22" }
- run: npm ci
- run: npx eslint . # includes @clerk/next/require-auth-protection
- name: No deprecated Clerk APIs
run: |
! grep -rnE "createRouteMatcher|<SignedIn|<SignedOut|<Protect|authMiddleware" app src proxy.ts middleware.ts 2>/dev/null
Common Use Cases
| Use case | Approach |
|---|---|
| Add auth to Next.js | npx -y clerk@latest init, then clerk doctor |
| Protect a page / API / action | await auth.protect() in that file (+ lint rule) |
| Role/permission check | has({ permission }), auth.protect({ role }), <Show when={{ role }}> |
| Paywall a feature | Clerk Billing + has({ plan }) / has({ feature }) |
| Let customers call your API | API keys + auth({ acceptsToken: "api_key" }) |
| Service-to-service auth | M2M tokens (tokenFormat: "jwt" for free local verify) |
| Sync users to DB | verifyWebhook() + idempotent upsert on svix-id |
| RLS in Supabase / Neon | Third-party auth (Supabase) / JWKS provider (Neon Data API) |
| Manage Clerk from an agent | Clerk MCP server (account tools) or clerk api |
Troubleshooting
| Issue | Fix |
|---|---|
auth() was called but Clerk can't detect usage of clerkMiddleware() |
proxy.ts/middleware.ts missing, wrong name for your Next version, or matcher excludes the route |
Dev console: createRouteMatcher() deprecation warning |
Migrate to resource-level auth.protect(); it's removed in the next major |
<SignedIn> is not available in @clerk/nextjs |
Core 3 removed it — use <Show when="signed-in"> |
| Webhook signature fails | Wrong CLERK_WEBHOOK_SIGNING_SECRET (per endpoint, per instance) or body was parsed before verify |
| Webhook 401/redirect | Route is protected — webhooks carry no session |
updateUser() ignores metadata |
API 2026-05-12 — use updateUserMetadata() / replaceUserMetadata() |
| SMS code never arrives (Kenya) | +254 not on the SMS allowlist, or Hobby plan; check SMS logs |
| Billing checkout fails for EU/UK cards | 3-D Secure isn't supported by Clerk Billing |
getToken() throws ClerkOfflineError |
Core 3 behavior when offline — wrap in try/catch |
| Lost Secret key | Dashboard shows it once — create a new one, deploy, then delete the old |
codeAmani notes
- Default auth. Clerk is the default for codeAmani Next.js apps. Identity lives in Clerk;
app data lives in Supabase or Neon keyed by a
textclerk_user_id/user_idcolumn. - Protection lives at the resource. New code never gates in middleware. Every page,
Route Handler and Server Action calls
await auth.protect()(orauth()+ explicit 401/403), and@clerk/eslint-pluginruns in CI. Existing apps withcreateRouteMatcher()keep working but migrate before@clerk/nextjsv8. - Secrets server-side only.
CLERK_SECRET_KEY,CLERK_WEBHOOK_SIGNING_SECRET,CLERK_MACHINE_SECRET_KEY,CLERK_ENCRYPTION_KEYgo in Hazina / Vercel env, never aNEXT_PUBLIC_prefix, never chat. Secret keys are shown once in the Dashboard now. - Webhooks: verify first (
verifyWebhook), dedupe onsvix-id, upsert. Same rule as the Stripe and M-Pesa callbacks. - Payments. Stripe stays the default rail. Clerk Billing is a reasonable shortcut for simple
USD SaaS subscriptions (0.7% on top of Stripe), but it's USD-only with no tax/3DS/refunds — use
Stripe directly (
stripe/) when you need any of those, Connect, or usage billing. Kenya-targeted projects keep M-Pesa (Daraja) as the rail; Clerk Billing has no M-Pesa. - AI routing. Use the Clerk MCP server for account/config work and snippets; Claude stays the primary model. Agents never receive Secret keys from it.
- Kenya-targeted projects: phone OTP is the natural sign-in, but it needs Pro + per-SMS
"market rate" fees and an explicit +254 allowlist entry. For large, low-ARPU user bases weigh
an SMS-OTP fallback via Africa's Talking or self-hosted Better Auth
(
better-auth/CLAUDE_CODE_INTEGRATION.md) — per-MRU USD pricing vs KES revenue rarely works. Keep Clerk's JS lazy (prebuilt components load@clerk/clerk-jsfrom CDN) for 2G/3G users.
Official docs:
- https://clerk.com/docs
- https://clerk.com/docs/nextjs/getting-started/quickstart
- https://clerk.com/docs/reference/nextjs/clerk-middleware
- https://clerk.com/docs/guides/development/upgrading/upgrade-guides/migrate-from-create-route-matcher
- https://clerk.com/docs/guides/development/webhooks/syncing
- https://clerk.com/docs/guides/ai/mcp/clerk-mcp-server
- https://clerk.com/docs/guides/development/machine-auth/overview
- https://clerk.com/docs/guides/billing/overview
- https://clerk.com/pricing