Clerk Auth

ClawSkills 作者 veeramanikandanr48 v0.1.0

Clerk auth with API Keys beta (Dec 2025), Next.js 16 proxy.ts (March 2025 CVE context), API version 2025-11-10 breaking changes, clerkMiddleware() options, webhooks, production considerations (GCP outages), and component reference. Prevents 15 documented errors. Use when: API keys for users/orgs, Next.js 16 middleware filename, troubleshooting JWKS/CSRF/JWT/token-type-mismatch errors, webhook verification, user type inconsistencies, or testing with 424242 OTP.

源码 ↗

安装 / 下载方式

TotalClaw CLI推荐
totalclaw install clawskills:veeramanikandanr48~clerk-auth
cURL直接下载,无需登录
curl -fsSL https://skills.taituai.com/api/skills/clawskills%3Aveeramanikandanr48~clerk-auth/file -o clerk-auth.md
Git 仓库获取源码
git clone https://github.com/clawdbot/skills/commit/56350acbcc6f9c0ecb5f5ea47f2ce7ce35b81b1e
# Clerk Auth - Breaking Changes & Error Prevention Guide

**Package Versions**: @clerk/nextjs@6.36.7, @clerk/backend@2.29.2, @clerk/clerk-react@5.59.2, @clerk/testing@1.13.26
**Breaking Changes**: Nov 2025 - API version 2025-11-10, Oct 2024 - Next.js v6 async auth()
**Last Updated**: 2026-01-09

---

## What's New (Dec 2025 - Jan 2026)

### 1. API Keys Beta (Dec 11, 2025) - NEW ✨

User-scoped and organization-scoped API keys for your application. Zero-code UI component.

```typescript
// 1. Add the component for self-service API key management
import { APIKeys } from '@clerk/nextjs'

export default function SettingsPage() {
  return (
    <div>
      <h2>API Keys</h2>
      <APIKeys />  {/* Full CRUD UI for user's API keys */}
    </div>
  )
}
```

**Backend Verification:**
```typescript
import { verifyToken } from '@clerk/backend'

// API keys are verified like session tokens
const { data, error } = await verifyToken(apiKey, {
  secretKey: process.env.CLERK_SECRET_KEY,
  authorizedParties: ['https://yourdomain.com'],
})

// Check token type
if (data?.tokenType === 'api_key') {
  // Handle API key auth
}
```

**clerkMiddleware Token Types:**
```typescript
// v6.36.0+: Middleware can distinguish token types
clerkMiddleware((auth, req) => {
  const { userId, tokenType } = auth()

  if (tokenType === 'api_key') {
    // API key auth - programmatic access
  } else if (tokenType === 'session_token') {
    // Regular session - web UI access
  }
})
```

**Pricing (Beta = Free):**
- Creation: $0.001/key
- Verification: $0.0001/verification

### 2. Next.js 16: proxy.ts Middleware Filename (Dec 2025)

**⚠️ BREAKING**: Next.js 16 changed middleware filename due to critical security vulnerability (CVE disclosed March 2025).

**Background**: The March 2025 vulnerability (affecting Next.js 11.1.4-15.2.2) allowed attackers to completely bypass middleware-based authorization by adding a single HTTP header: `x-middleware-subrequest: true`. This affected all auth libraries (NextAuth, Clerk, custom solutions).

**Why the Rename**: The `middleware.ts` → `proxy.ts` change isn't just cosmetic - it's Next.js signaling that middleware-first security patterns are dangerous. Future auth implementations should not rely solely on middleware for authorization.

```
Next.js 15 and earlier: middleware.ts
Next.js 16+:            proxy.ts
```

**Correct Setup for Next.js 16:**
```typescript
// src/proxy.ts (NOT middleware.ts!)
import { clerkMiddleware } from '@clerk/nextjs/server'

export default clerkMiddleware()

export const config = {
  matcher: [
    '/((?!_next|[^?]*\\.(?:html?|css|js(?!on)|jpe?g|webp|png|gif|svg|ttf|woff2?|ico|csv|docx?|xlsx?|zip|webmanifest)).*)',
    '/(api|trpc)(.*)',
  ],
}
```

**Minimum Version**: @clerk/nextjs@6.35.0+ required for Next.js 16 (fixes Turbopack build errors and cache invalidation on sign-out).

### 3. Force Password Reset (Dec 19, 2025)

Administrators can mark passwords as compromised and force reset:

```typescript
import { clerkClient } from '@clerk/backend'

// Force password reset for a user
await clerkClient.users.updateUser(userId, {
  passwordDigest: 'compromised',  // Triggers reset on next sign-in
})
```

### 4. Organization Reports & Filters (Dec 15-17, 2025)

Dashboard now includes org creation metrics and filtering by name/slug/date.

---

## API Version 2025-11-10 Breaking Changes

### 1. API Version 2025-11-10 (Nov 10, 2025) - BREAKING CHANGES ⚠️

**Affects:** Applications using Clerk Billing/Commerce APIs

**Critical Changes:**
- **Endpoint URLs:** `/commerce/` → `/billing/` (30+ endpoints)
  ```
  GET /v1/commerce/plans → GET /v1/billing/plans
  GET /v1/commerce/statements → GET /v1/billing/statements
  POST /v1/me/commerce/checkouts → POST /v1/me/billing/checkouts
  ```

- **Field Terminology:** `payment_source` → `payment_method`
  ```typescript
  // OLD (deprecated)
  { payment_source_id: "...", payment_source: {...} }

  // NEW (required)
  { payment_method_id: "...", payment_method: {...} }
  ```

- **Removed Fields:** Plans responses no longer include:
  - `amount`, `amount_formatted` (use `fee.amount` instead)
  - `currency`, `currency_symbol` (use fee objects)
  - `payer_type` (use `for_payer_type`)
  - `annual_monthly_amount`, `annual_amount`

- **Removed Endpoints:**
  - Invoices endpoint (use statements)
  - Products endpoint

- **Null Handling:** Explicit rules - `null` means "doesn't exist", omitted means "not asserting existence"

**Migration:** Update SDK to v6.35.0+ which includes support for API version 2025-11-10.

**Official Guide:** https://clerk.com/docs/guides/development/upgrading/upgrade-guides/2025-11-10

### 2. Next.js v6 Async auth() (Oct 2024) - BREAKING CHANGE ⚠️

**Affects:** All Next.js Server Components using `auth()`

```typescript
// ❌ OLD (v5 - synchronous)
const { userId } = auth()

// ✅ NEW (v6 - asynchronous)
const { userId } = await auth()
```

**Also affects:** `auth.protect()` is now async in middleware

```typescript
// ❌ OLD (v5)
auth.protect()

// ✅ NEW (v6)
await auth.protect()
```

**Compatibility:** Next.js 15, 16 supported. Static rendering by default.

### 3. PKCE Support for Custom OAuth (Nov 12, 2025)

Custom OIDC providers and social connections now support PKCE (Proof Key for Code Exchange) for enhanced security in native/mobile applications where client secrets cannot be safely stored.

**Use case:** Mobile apps, native apps, public clients that can't securely store secrets.

### 4. Client Trust: Credential Stuffing Defense (Nov 14, 2025)

Automatic secondary authentication when users sign in from unrecognized devices:
- Activates for users with valid passwords but no 2FA
- No configuration required
- Included in all Clerk plans

**How it works:** Clerk automatically prompts for additional verification (email code, backup code) when detecting sign-in from new device.

### 5. Next.js 16 Support (Nov 2025)

**@clerk/nextjs v6.35.2+** includes cache invalidation improvements for Next.js 16 during sign-out.

---

## Critical Patterns & Error Prevention

### Next.js v6: Async auth() Helper

**Pattern:**
```typescript
import { auth } from '@clerk/nextjs/server'

export default async function Page() {
  const { userId } = await auth()  // ← Must await

  if (!userId) {
    return <div>Unauthorized</div>
  }

  return <div>User ID: {userId}</div>
}
```

### Cloudflare Workers: authorizedParties (CSRF Prevention)

**CRITICAL:** Always set `authorizedParties` to prevent CSRF attacks

```typescript
import { verifyToken } from '@clerk/backend'

const { data, error } = await verifyToken(token, {
  secretKey: c.env.CLERK_SECRET_KEY,
  // REQUIRED: Prevent CSRF attacks
  authorizedParties: ['https://yourdomain.com'],
})
```

**Why:** Without `authorizedParties`, attackers can use valid tokens from other domains.

**Source:** https://clerk.com/docs/reference/backend/verify-token

---

## clerkMiddleware() Configuration

### Route Protection Patterns

```typescript
import { clerkMiddleware, createRouteMatcher } from '@clerk/nextjs/server'

// Define protected routes
const isProtectedRoute = createRouteMatcher([
  '/dashboard(.*)',
  '/api/private(.*)',
])

const isAdminRoute = createRouteMatcher(['/admin(.*)'])

export default clerkMiddleware(async (auth, req) => {
  // Protect routes
  if (isProtectedRoute(req)) {
    await auth.protect()  // Redirects unauthenticated users
  }

  // Require specific permissions
  if (isAdminRoute(req)) {
    await auth.protect({
      role: 'org:admin',  // Requires organization admin role
    })
  }
})
```

### All Middleware Options

| Option | Type | Description |
|--------|------|-------------|
| `debug` | `boolean` | Enable debug logging |
| `jwtKey` | `string` | JWKS public key for networkless verification |
| `clockSkewInMs` | `number` | Token time variance (default: 5000ms) |
| `organizationSyncOptions` | `object` | URL-based org activation |
| `signInUrl` | `string` | Custom sign-in URL |
| `signUpUrl` | `string` | Custom sign-up URL |

##