clerk-auth
БесплатноБез исполняемых скриптовНе проверенIntegrates Clerk authentication in React/Vite, Next.js App Router, and Cloudflare Workers apps. Covers ClerkProvider setup, clerkMiddleware and…
Об этом скилле
Clerk Authentication
Status: Production Ready ✅ Last Updated: 2025-10-28 Dependencies: None Latest Versions: @clerk/[email protected], @clerk/[email protected], @clerk/[email protected], @clerk/[email protected]
Quick Start (10 Minutes)
Choose your framework:
- React (Vite) - ClerkProvider + hooks
- Next.js App Router - Middleware + async auth()
- Cloudflare Workers - Backend verification
React (Vite) Setup
1. Install Clerk
```bash npm install @clerk/clerk-react ```
Latest Version: @clerk/[email protected] (verified 2025-10-22)
2. Configure ClerkProvider
Update `src/main.tsx`:
```typescript import React from 'react' import ReactDOM from 'react-dom/client' import { ClerkProvider } from '@clerk/clerk-react' import App from './App.tsx' import './index.css'
// Get publishable key from environment const PUBLISHABLE_KEY = import.meta.env.VITE_CLERK_PUBLISHABLE_KEY
if (!PUBLISHABLE_KEY) { throw new Error('Missing Publishable Key') }
ReactDOM.createRoot(document.getElementById('root')!).render(
<React.StrictMode>
CRITICAL:
- Use `VITE_` prefix for environment variables in Vite
- ClerkProvider must wrap your entire app
- Source: https://clerk.com/docs/references/react/clerk-provider
3. Add Environment Variables
Create `.env.local`:
```bash VITE_CLERK_PUBLISHABLE_KEY=pk_test_... ```
Security Note: Only `VITE_` prefixed vars are exposed to client code.
4. Use Authentication Hooks
```typescript import { useUser, useAuth, useClerk } from '@clerk/clerk-react'
function App() { // Get user object (includes email, metadata, etc.) const { isLoaded, isSignedIn, user } = useUser()
// Get auth state and session methods const { userId, sessionId, getToken } = useAuth()
// Get Clerk instance for advanced operations const { openSignIn, signOut } = useClerk()
// Always check isLoaded before rendering auth-dependent UI if (!isLoaded) { return
if (!isSignedIn) { return <button onClick={() => openSignIn()}>Sign In }
return (
Welcome {user.firstName}!
Email: {user.primaryEmailAddress?.emailAddress}
<button onClick={() => signOut()}>Sign OutWhy This Matters:
- `isLoaded` prevents flash of wrong content
- `useUser()` provides full user object with metadata
- `useAuth()` provides session tokens and auth state
- Source: https://clerk.com/docs/references/react/use-user
Next.js App Router Setup
1. Install Clerk
```bash npm install @clerk/nextjs ```
Latest Version: @clerk/[email protected] (verified 2025-10-22)
- New in v6: Async auth() helper, Next.js 15 support, static rendering by default
- Source: https://clerk.com/changelog/2024-10-22-clerk-nextjs-v6
2. Configure Environment Variables
Create `.env.local`:
```bash NEXT_PUBLIC_CLERK_PUBLISHABLE_KEY=pk_test_... CLERK_SECRET_KEY=sk_test_...
Optional: Customize sign-in/up pages
NEXT_PUBLIC_CLERK_SIGN_IN_URL=/sign-in NEXT_PUBLIC_CLERK_SIGN_UP_URL=/sign-up NEXT_PUBLIC_CLERK_AFTER_SIGN_IN_URL=/dashboard NEXT_PUBLIC_CLERK_AFTER_SIGN_UP_URL=/onboarding ```
CRITICAL:
- `CLERK_SECRET_KEY` must NEVER be exposed to client
- Use `NEXT_PUBLIC_` prefix for client-side vars only
- Source: https://clerk.com/docs/guides/development/clerk-environment-variables
3. Add Middleware for Route Protection
Create `middleware.ts` in project root:
```typescript import { clerkMiddleware, createRouteMatcher } from '@clerk/nextjs/server'
// Define which routes are public (everything else requires auth) const isPublicRoute = createRouteMatcher([ '/', '/sign-in(.)', '/sign-up(.)', '/api/webhooks(.*)', // Clerk webhooks should be public ])
export default clerkMiddleware(async (auth, request) => { // Protect all routes except public ones if (!isPublicRoute(request)) { await auth.protect() } })
export const config = { matcher: [ // Skip Next.js internals and static files '/((?!_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)(.*)', ], } ```
CRITICAL:
- `auth.protect()` is async in v6 (breaking change from v5)
- `createRouteMatcher()` accepts glob patterns
- Alternative: protect specific routes instead of inverting logic
- Source: https://clerk.com/docs/reference/nextjs/clerk-middleware
4. Wrap App with ClerkProvider
Update `app/layout.tsx`:
```typescript import { ClerkProvider } from '@clerk/nextjs' import './globals.css'
export default function RootLayout({
children,
}: {
children: React.ReactNode
}) {
return (
Установить clerk-auth в Claude Code и Claude Desktop
Зарегайся, чтобы установить скилл
Создай бесплатный аккаунт, чтобы открыть команду установки и сохранить скилл в библиотеку.
- Открой команду установки в одну строку
- Сохраняй скиллы в синхронизируемую библиотеку
- Уведомления, когда скиллы обновляются
Разрешённые инструменты
Инструменты, которые скиллу разрешено вызывать.
Без ограничений — скилл может использовать любой инструмент.
Вложенные файлы
FAQ
Что делает скилл clerk-auth?
Integrates Clerk authentication in React/Vite, Next.js App Router, and Cloudflare Workers apps. Covers ClerkProvider setup, clerkMiddleware and createRouteMatcher for protected routes, token verification with @clerk/backend verifyToken, custom JWT templates and session claims (user.public_metadata, org_id, org_role) for RBAC, Hono integration via @hono/clerk-auth, shadcn/ui auth components, and Playwright E2E testing with @clerk/testing, +clerk_test emails and the 424242 OTP. Documents 11 pitfalls: Missing Clerk Secret Key, JWKS cache races, missing authorizedParties CSRF risk, Core 2 import path changes, JWT size limits, ClerkProvider cannot be used as a JSX component, async auth() confusion, and Vite dev 431 header errors. Use when adding Clerk to a project, protecting routes, verifying tokens, shaping JWT claims, testing auth flows, or debugging Clerk authentication errors.
Как установить скилл clerk-auth?
Скопируй папку скилла в ~/.claude/skills (вкладка Claude Code выше делает это одной командой), либо поставь как плагин.
Скилл clerk-auth запускает скрипты?
Нет, скилл состоит только из инструкций (SKILL.md), без исполняемых скриптов.
Похожие скиллы
frontend-design
Guidance for distinctive, intentional visual design when building new UI or reshaping an existing one. Helps with aesthetic direction, typography, and making…
от Anthropicwebapp-testing
Toolkit for interacting with and testing local web applications using Playwright. Supports verifying frontend functionality, debugging UI behavior, capturing…
от Anthropicbrand-guidelines
Applies Anthropic's official brand colors and typography to any sort of artifact that may benefit from having Anthropic's look-and-feel. Use it when brand…
от Anthropicweb-artifacts-builder
Suite of tools for creating elaborate, multi-component claude.ai HTML artifacts using modern frontend web technologies (React, Tailwind CSS, shadcn/ui). Use…
от Anthropic