### Fetching Framework Quickstart Guide Source: https://github.com/clerk/skills/blob/main/skills/core/clerk-setup/SKILL.md This example shows how to use WebFetch to retrieve the official quickstart guide for a detected framework. The prompt specifies extracting all setup instructions, including code snippets and file paths. ```text WebFetch: https://clerk.com/docs/{framework}/getting-started/quickstart Prompt: "Extract the complete setup instructions including all code snippets, file paths, and configuration steps." ``` -------------------------------- ### Install Clerk TanStack React Start Source: https://github.com/clerk/skills/blob/main/skills/frameworks/clerk-tanstack-patterns/SKILL.md Install the necessary package for Clerk integration with TanStack React Start. ```bash npm install @clerk/tanstack-react-start ``` -------------------------------- ### Install Clerk UI Themes Package Source: https://github.com/clerk/skills/blob/main/skills/core/clerk-setup/SKILL.md Install the `@clerk/ui` package to manage Clerk component theming. ```bash npm install @clerk/ui ``` -------------------------------- ### Print Usage Examples Source: https://github.com/clerk/skills/blob/main/skills/core/clerk-backend-api/SKILL.md Displays examples of how to use the Clerk Backend API for browsing, executing, and inspecting endpoints. ```APIDOC ## Print Usage **Modes:** `help` only Print the following examples to the user verbatim: ``` Browse /clerk-backend-api tags — list all tags /clerk-backend-api Users — browse endpoints for the Users tag /clerk-backend-api Users version 2025-11-10.yml — browse using a different version Execute /clerk-backend-api GET /users — fetch all users /clerk-backend-api get user john_doe — natural language works too /clerk-backend-api POST /invitations — create an invitation Inspect /clerk-backend-api GET /users help — show endpoint schema without executing /clerk-backend-api POST /invitations -h — view request/response details Options --admin — bypass scope restrictions for write/delete --version [date], version [date] — use a specific spec version --help, -h, help — inspect endpoint instead of executing ``` ``` -------------------------------- ### Install Clerk React Package Source: https://github.com/clerk/skills/blob/main/skills/frameworks/clerk-react-patterns/SKILL.md Install the @clerk/react package using npm. ```bash npm install @clerk/react ``` -------------------------------- ### Execute API Request and Parse Response Source: https://github.com/clerk/skills/blob/main/skills/core/clerk-backend-api/SKILL.md This example demonstrates how to execute a GET request to list users, capture the response, and then parse the JSON output using Python to display user IDs and email addresses. Ensure `CLERK_SECRET_KEY` is set in your environment. ```bash RESPONSE=$(curl -s "https://api.clerk.com/v1/users?limit=10" \ -H "Authorization: Bearer $CLERK_SECRET_KEY") echo "$RESPONSE" | python3 -c " import sys, json data = json.load(sys.stdin) if isinstance(data, list): print(f'Found {len(data)} users:') for u in data: print(f' {u["id"]}: {u.get("email_addresses", [{}])[0].get("email_address", "no email")}') else: print(json.dumps(data, indent=2)) " ``` -------------------------------- ### Clerk Backend API Command Examples Source: https://github.com/clerk/skills/blob/main/skills/core/clerk-backend-api/SKILL.md Examples of how to interact with the Clerk Backend API for browsing, executing, and inspecting endpoints. Use these commands to list tags, view endpoints, and fetch specific user or invitation data. ```bash Browse /clerk-backend-api tags — list all tags /clerk-backend-api Users — browse endpoints for the Users tag /clerk-backend-api Users version 2025-11-10.yml — browse using a different version Execute /clerk-backend-api GET /users — fetch all users /clerk-backend-api get user john_doe — natural language works too /clerk-backend-api POST /invitations — create an invitation Inspect /clerk-backend-api GET /users help — show endpoint schema without executing /clerk-backend-api POST /invitations -h — view request/response details Options --admin — bypass scope restrictions for write/delete --version [date], version [date] — use a specific spec version --help, -h, help — inspect endpoint instead of executing ``` -------------------------------- ### Framework Detection Logic Source: https://github.com/clerk/skills/blob/main/skills/core/clerk-setup/SKILL.md This decision tree outlines the logic for detecting the user's framework and proceeding with the Clerk setup. It starts by reading the package.json to identify dependencies. ```text User Request: "Add Clerk" / "Add authentication" │ ├─ Read package.json │ ├─ Existing auth detected? │ ├─ YES → Audit → Migration plan │ └─ NO → Fresh install │ ├─ Identify framework → WebFetch quickstart → Follow instructions │ └─ Next.js? → Create proxy.ts (Next.js <=15: middleware.ts) │ └─ components.json exists? → YES → Apply shadcn theme (see clerk-custom-ui) ``` -------------------------------- ### Install and Apply Dark Theme Source: https://github.com/clerk/skills/blob/main/skills/core/clerk-custom-ui/SKILL.md Install the @clerk/ui package for themes and apply a pre-built theme like 'dark' to the ClerkProvider. For Core 2, import themes from '@clerk/themes'. ```bash npm install @clerk/ui ``` ```typescript import { dark } from '@clerk/ui/themes' ``` -------------------------------- ### Manually Install Clerk Skills Source: https://github.com/clerk/skills/blob/main/README.md Clone the Clerk Skills repository to your local Claude skills directory for manual installation. ```bash git clone https://github.com/clerk/skills ~/.claude/skills/clerk ``` -------------------------------- ### Install Clerk Skills with npm Source: https://github.com/clerk/skills/blob/main/README.md Use this command to add Clerk Skills to your project via npm. ```bash npx skills add clerk/skills ``` -------------------------------- ### Server Component Example with Clerk Source: https://github.com/clerk/skills/blob/main/skills/frameworks/clerk-nextjs-patterns/references/server-vs-client.md Demonstrates fetching authentication status and user details in a Next.js Server Component using await auth() and await currentUser(). ```tsx import { auth, currentUser } from '@clerk/nextjs/server'; export default async function DashboardPage() { const { isAuthenticated } = await auth(); if (!isAuthenticated) return
Please sign in
; const user = await currentUser(); return

Welcome, {user?.firstName}!

; } ``` -------------------------------- ### Install Clerk Skills with Codex Source: https://github.com/clerk/skills/blob/main/README.md Add Clerk Skills to your Codex environment using the plugin marketplace. ```bash codex plugin marketplace add clerk/skills ``` -------------------------------- ### Clerk Backend API - Create Organization and Invite Member Source: https://context7.com/clerk/skills/llms.txt This example shows how to create a new organization and then invite a member to it using the Clerk Backend API. ```APIDOC ## POST /v1/organizations and POST /v1/organizations/{orgId}/invitations ### Description Creates a new organization and subsequently invites a member to that organization. ### Method POST ### Endpoint 1. https://api.clerk.com/v1/organizations 2. https://api.clerk.com/v1/organizations/${ORG_ID}/invitations ### Parameters #### Request Body (Create Organization) - **name** (string) - Required - The name of the organization. - **created_by** (string) - Required - The ID of the user who is creating the organization. #### Request Body (Invite Member) - **email_address** (string) - Required - The email address of the user to invite. - **role** (string) - Required - The role to assign to the invited member (e.g., 'org:admin'). ### Request Example ```bash ORG=$(curl -s -X POST "https://api.clerk.com/v1/organizations" \ -H "Authorization: Bearer $CLERK_SECRET_KEY" \ -H "Content-Type: application/json" \ -d '{"name": "Acme Corp", "created_by": "$USER_ID"}') ORG_ID=$(echo "$ORG" | python3 -c "import sys,json; print(json.load(sys.stdin)['id'])") curl -s -X POST "https://api.clerk.com/v1/organizations/${ORG_ID}/invitations" \ -H "Authorization: Bearer $CLERK_SECRET_KEY" \ -H "Content-Type: application/json" \ -d '{"email_address": "user@example.com", "role": "org:admin"}' ``` ### Response #### Success Response (200) Returns the created organization object for the first request, and the invitation object for the second request. #### Response Example (Invitation) ```json { "id": "inv_xyz789", "object": "invitation", "email_address": "user@example.com", "role": "org:admin", "organization_id": "org_abc123" } ``` ``` -------------------------------- ### Basic Clerk Middleware Setup in Astro Source: https://github.com/clerk/skills/blob/main/skills/frameworks/clerk-astro-patterns/references/middleware.md Set up Clerk middleware to protect specific routes. Use `createRouteMatcher` to define protected paths and redirect unauthenticated users to sign-in. ```typescript // src/middleware.ts import { clerkMiddleware, createRouteMatcher } from '@clerk/astro/server' const isProtectedRoute = createRouteMatcher([ '/dashboard(.*)', '/settings(.*)', '/api/private(.*)', ]) export const onRequest = clerkMiddleware((auth, context, next) => { if (isProtectedRoute(context.request) && !auth().userId) { return auth().redirectToSignIn() } return next() }) ``` -------------------------------- ### Sync Organization Data to Database on Event Source: https://github.com/clerk/skills/blob/main/skills/features/clerk-webhooks/SKILL.md This example demonstrates handling 'organization.created', 'organizationMembership.created', and 'organizationMembership.deleted' events to sync organization and membership data with a local database. ```typescript // app/api/webhooks/route.ts import { verifyWebhook } from '@clerk/nextjs/webhooks' import { NextRequest } from 'next/server' import { db } from '@/lib/db' // your database client export async function POST(req: NextRequest) { // ALWAYS verify signature - never skip, even for simple handlers let evt try { evt = await verifyWebhook(req) // uses CLERK_WEBHOOK_SIGNING_SECRET env var } catch (err) { console.error('Webhook verification failed:', err) return new Response('Verification failed', { status: 400 }) } if (evt.type === 'organization.created') { const { id, name } = evt.data await db.workspaces.create({ data: { orgId: id, name, createdAt: new Date() }, }) } if (evt.type === 'organizationMembership.created') { // Extract organization ID, user ID, and role from payload const { organization, public_user_data, role } = evt.data const orgId = organization.id const userId = public_user_data.user_id // Add to team_members table await db.team_members.create({ data: { orgId, userId, role }, }) // Create workspace record for new member await db.workspaces.create({ data: { orgId, userId, createdAt: new Date() }, }) } if (evt.type === 'organizationMembership.deleted') { // Extract organization ID and user ID from payload const { organization, public_user_data } = evt.data const orgId = organization.id const userId = public_user_data.user_id // Remove from team_members table await db.team_members.delete({ where: { orgId, userId }, }) // Remove workspace record await db.workspaces.deleteMany({ where: { orgId, userId }, }) } // Return 200 status on success return new Response('OK', { status: 200 }) } ``` -------------------------------- ### Use useClerk() Composable Source: https://github.com/clerk/skills/blob/main/skills/frameworks/clerk-nuxt-patterns/references/composables.md Gain access to the Clerk instance for performing programmatic actions like signing out or opening user profile modals. No import needed in ``` -------------------------------- ### Minimal Setup: root.tsx with rootAuthLoader Source: https://github.com/clerk/skills/blob/main/skills/frameworks/clerk-react-router-patterns/SKILL.md Required in `root.tsx` to pass Clerk state to the client. Ensures `getAuth` works in nested loaders. ```tsx import { rootAuthLoader } from '@clerk/react-router/server' import { ClerkApp } from '@clerk/react-router' import type { Route } from './+types/root' export async function loader(args: Route.LoaderArgs) { return rootAuthLoader(args) } export default ClerkApp(function App() { return }) ``` -------------------------------- ### Middleware Setup with clerkMiddleware Source: https://github.com/clerk/skills/blob/main/skills/frameworks/clerk-react-router-patterns/SKILL.md Configure Clerk's middleware to run on every request and attach authentication to the context. This should be exported from your root route or entry.server.ts. ```tsx import { clerkMiddleware } from '@clerk/react-router/server' export const middleware = [clerkMiddleware()] ``` -------------------------------- ### Fetch API Specs Context Source: https://github.com/clerk/skills/blob/main/skills/core/clerk-backend-api/SKILL.md Run this script to get the latest API version and available tags. Cache this information if already fetched in the conversation. ```bash bash scripts/api-specs-context.sh ``` -------------------------------- ### Client Component Example with Clerk Source: https://github.com/clerk/skills/blob/main/skills/frameworks/clerk-nextjs-patterns/references/server-vs-client.md Shows how to use Clerk's useUser and useAuth hooks in a Next.js Client Component for interactive UI elements like sign-out buttons. ```tsx 'use client'; import { useUser, useAuth } from '@clerk/nextjs'; export function UserDashboard() { const { isLoaded, isSignedIn, user } = useUser(); const { signOut } = useAuth(); if (!isLoaded) return
Loading...
; if (!isSignedIn) return
Not signed in
; return (

Hello, {user.firstName}!

); } ``` -------------------------------- ### Server Component Authentication (Next.js) Source: https://context7.com/clerk/skills/llms.txt Demonstrates how to use the `auth()` function in a Next.js Server Component to get authentication status and user information. ```APIDOC ## Server Component Authentication ### Description Retrieves authentication status, user ID, and organization ID within a Next.js Server Component using the `auth()` function. ### Method Asynchronous function call ### Framework Next.js (Server Component) ### Usage ```typescript // Server Component — auth() is ASYNC in Next.js 15+ import { auth } from '@clerk/nextjs/server' export default async function Page() { const { isAuthenticated, userId, orgId, has } = await auth() if (!isAuthenticated) return

Not signed in

if (!has({ role: 'org:admin' })) return

Admin only

return

Hello {userId} in org {orgId}

} ``` ``` -------------------------------- ### Clerk Backend API - List Users Source: https://context7.com/clerk/skills/llms.txt This example shows how to list users created in the last 7 days using the Clerk Backend API with `curl`. ```APIDOC ## GET /v1/users ### Description Retrieves a list of users, optionally filtered by creation date. ### Method GET ### Endpoint https://api.clerk.com/v1/users?limit=100&order_by=-created_at ### Parameters #### Query Parameters - **limit** (integer) - Optional - The maximum number of users to return. - **order_by** (string) - Optional - Specifies the sorting order for the users. `-created_at` sorts by creation date in descending order. ### Request Example ```bash curl -s "https://api.clerk.com/v1/users?limit=100&order_by=-created_at" \ -H "Authorization: Bearer $CLERK_SECRET_KEY" ``` ### Response #### Success Response (200) Returns a JSON array of user objects. #### Response Example ```json [ { "id": "user_abc123", "email_addresses": [ { "email_address": "user@example.com" } ] } ] ``` ``` -------------------------------- ### Initialize Clerk in a New Project Source: https://github.com/clerk/skills/blob/main/skills/core/clerk-setup/SKILL.md Use `clerk init` to create a new Clerk app, link it to your project, write keys to the environment file, and install the SDK. Specify your framework with the `--framework` flag. ```bash clerk init --framework -y ``` -------------------------------- ### Clerk Setup CLI Commands Source: https://context7.com/clerk/skills/llms.txt Commands for initializing a new project with Clerk, linking an existing Clerk app, and pulling environment variables. Includes commands for health checks and key rotation. ```bash # Scenario A — new project, new Clerk app clerk init --framework next -y # Creates app, writes NEXT_PUBLIC_CLERK_PUBLISHABLE_KEY + CLERK_SECRET_KEY to .env.local, installs @clerk/nextjs # Scenario B — existing project, existing Clerk app clerk auth login clerk link --app app_xxx clerk env pull # Scenario C — existing project, new Clerk app clerk auth login clerk apps create "My App" --json # returns app_id clerk link --app app_xxx clerk env pull # Health check clerk doctor --json # Key rotation (keeps old key valid for 24 h during rolling deploy) clerk api --platform POST /v1/platform/applications//rotate_secret_keys \ -d '{"delay_old_secrets_expiration_hours": 24, "reason": "scheduled rotation"}' ``` -------------------------------- ### GET /api/protected Source: https://github.com/clerk/skills/blob/main/skills/frameworks/clerk-tanstack-patterns/references/vinxi-server.md An example API route that demonstrates how to use the auth() function to protect an endpoint and retrieve the authenticated user's ID. ```APIDOC ## GET /api/protected ### Description This endpoint demonstrates how to protect an API route using Clerk authentication. It checks if the user is authenticated and returns their userId if they are. Otherwise, it returns a 401 Unauthorized response. ### Method GET ### Endpoint /api/protected ### Parameters None ### Request Example None ### Response #### Success Response (200) - **userId** (string) - The ID of the authenticated user. #### Response Example ```json { "userId": "user_..." } ``` #### Error Response (401) Returns 'Unauthorized' when the user is not authenticated. ``` -------------------------------- ### Web3 Sign-Up Method Source: https://github.com/clerk/skills/blob/main/skills/core/clerk-custom-ui/core-3/custom-sign-up.md Enable Web3 sign-ups with `signUp.web3()`, specifying the Web3 strategy, such as 'web3_solana_signature'. ```typescript const { error } = await signUp.web3({ strategy: 'web3_solana_signature' }) ``` -------------------------------- ### Custom Token Cache for Clerk Source: https://github.com/clerk/skills/blob/main/skills/frameworks/clerk-chrome-extension-patterns/SKILL.md Implement a custom token cache using `chrome.storage.local` to persist Clerk tokens across popup closes. This example provides methods to get, save, and clear tokens. ```tsx const tokenCache = { async getToken(key: string) { const result = await chrome.storage.local.get(key) return result[key] ?? null }, async saveToken(key: string, token: string) { await chrome.storage.local.set({ [key]: token }) }, async clearToken(key: string) { await chrome.storage.local.remove(key) }, } ``` -------------------------------- ### Configure ClerkProvider with syncHost Source: https://github.com/clerk/skills/blob/main/skills/frameworks/clerk-chrome-extension-patterns/references/sync-host.md Integrate ClerkProvider in your root layout component, providing your publishable key and the sync host URL. This setup enables session synchronization with your web application. ```tsx import { ClerkProvider, Show, UserButton } from '@clerk/chrome-extension' import { Link, Outlet, useNavigate } from 'react-router-dom' const PUBLISHABLE_KEY = process.env.PLASMO_PUBLIC_CLERK_PUBLISHABLE_KEY const SYNC_HOST = process.env.PLASMO_PUBLIC_CLERK_SYNC_HOST if (!PUBLISHABLE_KEY || !SYNC_HOST) { throw new Error('Missing PLASMO_PUBLIC_CLERK_PUBLISHABLE_KEY or PLASMO_PUBLIC_CLERK_SYNC_HOST') } export function RootLayout() { const navigate = useNavigate() return ( navigate(to)} routerReplace={(to) => navigate(to, { replace: true })} > ) } ``` -------------------------------- ### SSO (OAuth) Sign-Up Method Source: https://github.com/clerk/skills/blob/main/skills/core/clerk-custom-ui/core-3/custom-sign-up.md Initiate an SSO sign-up using `signUp.sso()`. Specify the OAuth strategy and redirect URLs for a seamless user experience. ```typescript const { error } = await signUp.sso({ strategy: 'oauth_google', // or 'oauth_github', etc. redirectUrl: '/dashboard', // where to go after SSO completes redirectCallbackUrl: '/sso-callback', // intermediate callback route }) ``` -------------------------------- ### Set Up Existing Project with New Clerk App Source: https://github.com/clerk/skills/blob/main/skills/core/clerk-setup/SKILL.md To add a new Clerk app to an existing project, log in, create the new app via the CLI, link it using the new app ID, and then pull the environment variables. ```bash clerk auth login clerk apps create "My App" --json # returns the new app_id clerk link --app app_xxx clerk env pull ``` -------------------------------- ### Configure Vinxi Entry with Clerk Middleware Source: https://github.com/clerk/skills/blob/main/skills/frameworks/clerk-tanstack-patterns/SKILL.md Set up the Vinxi entry point (`start.ts`) to include Clerk's middleware for handling authentication requests. ```typescript import { clerkMiddleware } from '@clerk/tanstack-react-start/server' import { createStart } from '@tanstack/react-start' export const startInstance = createStart(() => { return { requestMiddleware: [clerkMiddleware()], } }) ``` -------------------------------- ### Execute GET Requests with Curl Source: https://github.com/clerk/skills/blob/main/skills/core/clerk-backend-api/SKILL.md Use this template for all GET requests. Ensure the CLERK_SECRET_KEY environment variable is set. ```bash curl -s "https://api.clerk.com/v1${PATH}${QUERY_STRING}" \ -H "Authorization: Bearer $CLERK_SECRET_KEY" ``` -------------------------------- ### useSignIn / useSignUp Source: https://github.com/clerk/skills/blob/main/skills/frameworks/clerk-vue-patterns/references/composables.md Provides methods for handling user sign-in and sign-up processes, including creating sessions and setting the active session. ```APIDOC ## useSignIn / useSignUp ### Description Provides methods for managing the sign-in and sign-up flows, including creating user accounts, authenticating users, and establishing active sessions. ### Usage ```ts import { useSignIn } from '@clerk/vue' const { signIn, setActive, isLoaded } = useSignIn() async function submit(email: string, password: string) { const result = await signIn.value!.create({ identifier: email, password, }) if (result.status === 'complete') { await setActive.value!({ session: result.createdSessionId }) } } ``` ### Properties - `signIn` (Object): An object containing methods for sign-in operations. - `setActive` (Function): A function to set the active session for the user. - `isLoaded` (Ref): True when the sign-in/sign-up process has finished loading. ``` -------------------------------- ### Install Clerk for Chrome Extension with Plasmo Source: https://github.com/clerk/skills/blob/main/skills/frameworks/clerk-chrome-extension-patterns/SKILL.md Install the Clerk Chrome extension package using npm. Ensure you have Plasmo and Tailwind CSS set up. ```bash npx create-plasmo --with-tailwindcss --with-src my-extension cd my-extension npm install @clerk/chrome-extension ``` -------------------------------- ### Install Clerk Nuxt Module Source: https://github.com/clerk/skills/blob/main/skills/frameworks/clerk-nuxt-patterns/SKILL.md Install the Clerk Nuxt module using npm. This single line auto-configures middleware, plugins, and component auto-imports. ```bash npm install @clerk/nuxt ``` -------------------------------- ### GET Request Template Source: https://github.com/clerk/skills/blob/main/skills/core/clerk-backend-api/SKILL.md Template for executing GET requests against the Clerk API. This command fetches data from a specified path and includes the necessary authorization header. ```APIDOC ## GET Request ### Description Use this template to fetch data from the Clerk API. Ensure you replace `${PATH}` and `${QUERY_STRING}` with the appropriate values. ### Method GET ### Endpoint `https://api.clerk.com/v1${PATH}${QUERY_STRING}` ### Headers - `Authorization`: `Bearer $CLERK_SECRET_KEY` ``` -------------------------------- ### Set Up API Keys for Clerk Source: https://github.com/clerk/skills/blob/main/README.md Configure your environment variables with your Clerk publishable and secret keys. These are essential for Clerk authentication. ```bash NEXT_PUBLIC_CLERK_PUBLISHABLE_KEY=pk_test_xxx CLERK_SECRET_KEY=sk_test_xxx ``` -------------------------------- ### Get JWT for External APIs (Client-side) Source: https://github.com/clerk/skills/blob/main/skills/frameworks/clerk-nextjs-patterns/SKILL.md Use `useAuth()` hook in Client Components to get a custom JWT for external API calls. Always check if the token is successfully retrieved before making the request. ```typescript 'use client' import { useAuth } from '@clerk/nextjs' export function DataFetcher() { const { getToken } = useAuth() async function fetchData() { const token = await getToken({ template: 'supabase' }) if (!token) return const res = await fetch('https://api.example.com/data', { headers: { Authorization: `Bearer ${token}` }, }) return res.json() } return } ``` -------------------------------- ### Configure Organization Settings via CLI Source: https://github.com/clerk/skills/blob/main/skills/features/clerk-orgs/SKILL.md Patch the instance configuration to set organization settings like max allowed memberships, domain verification, and admin delete. ```bash clerk api --platform PATCH /v1/platform/applications//instances//config \ -d '{"organization_settings":{"max_allowed_memberships":50,"domains_enabled":true,"admin_delete_enabled":true}}' ``` -------------------------------- ### Detecting Existing Authentication Libraries Source: https://github.com/clerk/skills/blob/main/skills/core/clerk-setup/SKILL.md This list provides common dependencies to check in `package.json` to detect existing authentication providers before migrating to Clerk. ```text - next-auth / @auth/core → NextAuth/Auth.js - @supabase/supabase-js → Supabase Auth - firebase / firebase-admin → Firebase Auth - @aws-amplify/auth → AWS Cognito - auth0 / @auth0/nextjs-auth0 → Auth0 - passport → Passport.js - Custom JWT/session implementation ``` -------------------------------- ### Playwright Global Setup for Caching Auth State Source: https://context7.com/clerk/skills/llms.txt Use this Playwright global setup to cache authentication state for E2E tests. It requires navigating to the sign-in page and filling in test credentials before saving the storage state. ```typescript import { clerkSetup } from '@clerk/testing/playwright' import { test as setup } from '@playwright/test' setup('authenticate', async ({ page }) => { await clerkSetup() // Navigate to sign-in page with bot-detection bypass await setupClerkTestingToken({ page }) await page.goto('/sign-in') // ... fill in test credentials await page.context().storageState({ path: 'playwright/.clerk/user.json' }) }) ``` ```typescript export default defineConfig({ projects: [ { name: 'setup', testMatch: /.*\.setup\.ts/ }, { name: 'authenticated', use: { storageState: 'playwright/.clerk/user.json' }, dependencies: ['setup'], }, ], }) ``` -------------------------------- ### Get User Source: https://github.com/clerk/skills/blob/main/skills/core/clerk-backend-api/SKILL.md Retrieves a specific user by their ID. ```APIDOC ## GET /v1/users/{user_id} ### Description Retrieves a specific user by their ID. ### Method GET ### Endpoint /v1/users/{user_id} ### Parameters #### Path Parameters - **user_id** (string) - Required - The ID of the user to retrieve. ### Response #### Success Response (200) - Returns a User object. #### Response Example ```json { "id": "user_abc123", "email_addresses": [ { "email_address": "test@example.com" } ] } ``` ``` -------------------------------- ### Create Organization and Invite Member with Backend API (curl) Source: https://context7.com/clerk/skills/llms.txt Demonstrates creating a new organization and inviting a member using `curl` and the Clerk Backend API. Requires `$CLERK_SECRET_KEY` and `$USER_ID` to be set. The invitation is sent with a specific role. ```bash # Create org + invite member ORG=$(curl -s -X POST "https://api.clerk.com/v1/organizations" \ -H "Authorization: Bearer $CLERK_SECRET_KEY" \ -H "Content-Type: application/json" \ -d "{\"name\": \"Acme Corp\", \"created_by\": \"$USER_ID\"}") ORG_ID=$(echo "$ORG" | python3 -c "import sys,json; print(json.load(sys.stdin)['id'])") curl -s -X POST "https://api.clerk.com/v1/organizations/${ORG_ID}/invitations" \ -H "Authorization: Bearer $CLERK_SECRET_KEY" \ -H "Content-Type: application/json" \ -d "{\"email_address\": \"user@example.com\", \"role\": \"org:admin\"}" \ | python3 -c "import sys,json; print(json.dumps(json.load(sys.stdin), indent=2))" ``` -------------------------------- ### Password Reset Flow Source: https://github.com/clerk/skills/blob/main/skills/core/clerk-custom-ui/core-3/custom-sign-in.md Guide users through the password reset process. ```APIDOC ## Password Reset ```typescript // 1. Send reset code const { error } = await signIn.resetPasswordEmailCode.sendCode() // 2. Verify the code const { error } = await signIn.resetPasswordEmailCode.verifyCode({ code: '123456' }) // 3. Submit new password const { error } = await signIn.resetPasswordEmailCode.submitPassword({ password: 'newSecurePassword123', }) ``` ### Parameters - `verifyCode`: - `code` (string) - Required - The password reset code. - `submitPassword`: - `password` (string) - Required - The new password. ``` -------------------------------- ### SSO (OAuth) Sign-Up Source: https://github.com/clerk/skills/blob/main/skills/core/clerk-custom-ui/core-3/custom-sign-up.md Initiate sign-up using an OAuth provider. ```APIDOC ## SSO (OAuth) ```typescript const { error } = await signUp.sso({ strategy: 'oauth_google', // or 'oauth_github', etc. redirectUrl: '/dashboard', // where to go after SSO completes redirectCallbackUrl: '/sso-callback', // intermediate callback route }) ``` ``` -------------------------------- ### Enable Billing via CLI Source: https://github.com/clerk/skills/blob/main/skills/features/clerk-billing/SKILL.md Use the Clerk CLI to enable billing for your instance. This command can enable billing for users, organizations, or both, and automatically creates default free plans. ```bash clerk enable billing # both targets (default, auto-creates free_user + free_org plans) clerk enable billing --for org # org only clerk enable billing --for user # user only ``` -------------------------------- ### Get Organization Source: https://github.com/clerk/skills/blob/main/skills/features/clerk-orgs/SKILL.md Retrieves a specific organization by its ID using the Clerk API. ```APIDOC ## Get Organization ### Description Retrieves a specific organization by its ID using the Clerk API. ### Method GET ### Endpoint /v1/organizations/ ``` -------------------------------- ### Custom Sign-Up with useSignUp Source: https://github.com/clerk/skills/blob/main/skills/frameworks/clerk-react-patterns/references/custom-flows.md Create a custom sign-up flow using the `useSignUp` hook. Handles user creation and prepares for email verification if needed. Check `isLoaded` before proceeding. ```tsx import { useSignUp } from '@clerk/react' export function CustomSignUp() { const { isLoaded, signUp, setActive } = useSignUp() async function handleSubmit(email: string, password: string) { if (!isLoaded) return const result = await signUp.create({ emailAddress: email, password }) if (result.status === 'complete') { await setActive({ session: result.createdSessionId }) } else if (result.status === 'missing_requirements') { // Email verification needed await signUp.prepareEmailAddressVerification({ strategy: 'email_code' }) } } } ``` -------------------------------- ### Get Single Organization Invitation Source: https://github.com/clerk/skills/blob/main/skills/features/clerk-orgs/references/invitations.md Retrieves details for a specific organization invitation by its ID. ```APIDOC ## Get a Single Invitation ### Description Retrieves the details of a specific organization invitation. ### Method `clerk.organizations.getOrganizationInvitation` ### Parameters #### Request Body - **organizationId** (string) - Required - The ID of the organization. - **invitationId** (string) - Required - The ID of the invitation to retrieve. ### Request Example ```typescript const invitation = await clerk.organizations.getOrganizationInvitation({ organizationId: "org_123", invitationId: "inv_456", }) ``` ### Response Returns the `OrganizationInvitation` object. ``` -------------------------------- ### Password Sign-Up Method Source: https://github.com/clerk/skills/blob/main/skills/core/clerk-custom-ui/core-3/custom-sign-up.md Use the `signUp.password()` method to handle email and password-based sign-ups. Optional fields like `firstName` and `lastName` can be included. ```typescript const { error } = await signUp.password({ emailAddress: 'user@example.com', password: 'securePassword123', firstName: 'Jane', // optional lastName: 'Doe', // optional }) ``` -------------------------------- ### Codex Marketplace Registry Source: https://github.com/clerk/skills/blob/main/AGENTS.md Details the Codex marketplace registry for installing the Clerk skills plugin. ```json .agents/plugins/marketplace.json - Codex marketplace registry for installing the plugin. ``` -------------------------------- ### Add React Integration to Astro Source: https://github.com/clerk/skills/blob/main/skills/frameworks/clerk-astro-patterns/references/astro-react.md Install the React integration for Astro. This is a prerequisite for using React islands. ```bash npx astro add react ``` -------------------------------- ### Web3 Sign-Up Source: https://github.com/clerk/skills/blob/main/skills/core/clerk-custom-ui/core-3/custom-sign-up.md Sign up a user using a Web3 strategy. ```APIDOC ## Web3 ```typescript const { error } = await signUp.web3({ strategy: 'web3_solana_signature' }) ``` ``` -------------------------------- ### Create organization + invite member (two-step) Source: https://github.com/clerk/skills/blob/main/skills/core/clerk-backend-api/SKILL.md This snippet demonstrates how to create a new organization and then invite a member to it using cURL commands. It includes steps for creating the organization, extracting the organization ID, and then inviting a member with a specified role. ```APIDOC ## Create organization + invite member (two-step) ### Description This operation creates a new organization and then invites a member to it. It involves two main steps: creating the organization and then creating an invitation for a member. ### Method POST ### Endpoint - Create organization: `https://api.clerk.com/v1/organizations` - Invite member: `https://api.clerk.com/v1/organizations/{ORG_ID}/invitations` ### Parameters #### Request Body (Create Organization) - **name** (string) - Required - The name of the organization. - **created_by** (string) - Required - The ID of the user creating the organization. #### Request Body (Invite Member) - **email_address** (string) - Required - The email address of the user to invite. - **role** (string) - Required - The role to assign to the invited member (e.g., `org:admin`, `org:member`). ### Request Example (cURL) ```bash # Step 1 — Create organization ORG=$(curl -s -X POST "https://api.clerk.com/v1/organizations" \ -H "Authorization: Bearer $CLERK_SECRET_KEY" \ -H "Content-Type: application/json" \ -d "{\"name\": \"Acme Corp\", \"created_by\": \"$USER_ID\"}") echo "$ORG" | python3 -c "import sys,json; d=json.load(sys.stdin); print(json.dumps(d, indent=2))" # Step 2 — Extract org ID ORG_ID=$(echo "$ORG" | python3 -c "import sys,json; print(json.load(sys.stdin)['id'])") # Step 3 — Invite member with role curl -s -X POST "https://api.clerk.com/v1/organizations/${ORG_ID}/invitations" \ -H "Authorization: Bearer $CLERK_SECRET_KEY" \ -H "Content-Type: application/json" \ -d "{\"email_address\": \"user@example.com\", \"role\": \"org:admin\"}" \ | python3 -c "import sys,json; print(json.dumps(json.load(sys.stdin), indent=2))" ``` ### Response #### Success Response (200) - **id** (string) - The unique identifier for the created organization or invitation. - **name** (string) - The name of the organization. - **created_by** (string) - The ID of the user who created the organization. - **email_address** (string) - The email address of the invited member. - **role** (string) - The role assigned to the invited member. #### Response Example (Create Organization) ```json { "id": "org_...", "name": "Acme Corp", "created_by": "user_..." } ``` #### Response Example (Invite Member) ```json { "id": "invitation_...", "organization_id": "org_...", "email_address": "user@example.com", "role": "org:admin" } ``` ``` -------------------------------- ### Reset Sign-Up State Source: https://github.com/clerk/skills/blob/main/skills/core/clerk-custom-ui/core-3/custom-sign-up.md Clear the local sign-up state and allow the user to start the sign-up process again. ```APIDOC ### Reset State Clear local sign-up state and start over: ```typescript signUp.reset() ``` ``` -------------------------------- ### Get Single Organization via BAPI Source: https://github.com/clerk/skills/blob/main/skills/features/clerk-orgs/SKILL.md Fetch details for a specific organization by its ID using the Backend API. ```bash clerk api /v1/organizations/ ``` -------------------------------- ### Get Single Organization Invitation Source: https://github.com/clerk/skills/blob/main/skills/features/clerk-orgs/references/invitations.md Fetch details for a specific organization invitation using its ID and the organization ID. ```typescript const invitation = await clerk.organizations.getOrganizationInvitation({ organizationId, invitationId, }) ``` -------------------------------- ### Get Auth in Loaders Source: https://github.com/clerk/skills/blob/main/skills/frameworks/clerk-react-router-patterns/references/loaders-actions.md Use `getAuth` in a loader to access user authentication details. Redirect to sign-in if the user is not authenticated. ```tsx import { getAuth } from '@clerk/react-router/server' import { redirect } from 'react-router' import type { Route } from './+types/dashboard' export async function loader(args: Route.LoaderArgs) { const { userId, orgId, sessionId } = await getAuth(args) if (!userId) throw redirect('/sign-in') return { data: await db.query(userId) } } ``` -------------------------------- ### Reset Sign-Up State Source: https://github.com/clerk/skills/blob/main/skills/core/clerk-custom-ui/core-3/custom-sign-up.md Use `signUp.reset()` to clear the local sign-up state and allow the user to start the sign-up process again. ```typescript signUp.reset() ``` -------------------------------- ### Handle User Creation: Send Welcome Email and Slack Notification Source: https://github.com/clerk/skills/blob/main/skills/features/clerk-webhooks/SKILL.md This snippet demonstrates how to verify a webhook signature, listen for the 'user.created' event, extract user details, send a welcome email using Resend, and post a notification to Slack. ```typescript // app/api/webhooks/route.ts import { verifyWebhook } from '@clerk/nextjs/webhooks' import { NextRequest } from 'next/server' import { Resend } from 'resend' const resend = new Resend(process.env.RESEND_API_KEY) export async function POST(req: NextRequest) { // Step 1: ALWAYS verify the webhook signature - NEVER skip this let evt try { evt = await verifyWebhook(req) // uses CLERK_WEBHOOK_SIGNING_SECRET env var } catch (err) { console.error('Webhook verification failed:', err) return new Response('Verification failed', { status: 400 }) } // Step 2: Listen for user.created event if (evt.type === 'user.created') { // Step 3: Extract user email and name from webhook payload const { id, email_addresses, first_name, last_name } = evt.data const email = email_addresses[0]?.email_address const name = `${first_name ?? ''} ${last_name ?? ''}`.trim() // Step 4: Call Resend API to send welcome email await resend.emails.send({ from: 'noreply@yourdomain.com', to: email, subject: 'Welcome!', html: `

Hi ${name}, welcome to our app!

`, }) // Step 5: Post notification to Slack channel await fetch(process.env.SLACK_WEBHOOK_URL!, { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ text: `New user signed up: ${name} (${email})`, }), }) } // Always return 200 to acknowledge receipt return new Response('OK', { status: 200 }) } ``` -------------------------------- ### Password Reset Flow Source: https://github.com/clerk/skills/blob/main/skills/core/clerk-custom-ui/core-3/custom-sign-in.md Guide users through resetting their password by sending a reset code, verifying it, and submitting a new password. ```typescript // 1. Send reset code const { error } = await signIn.resetPasswordEmailCode.sendCode() // 2. Verify the code const { error } = await signIn.resetPasswordEmailCode.verifyCode({ code: '123456' }) // 3. Submit new password const { error } = await signIn.resetPasswordEmailCode.submitPassword({ password: 'newSecurePassword123', }) ``` -------------------------------- ### Initialize Clerk in Vanilla JS Popup Source: https://github.com/clerk/skills/blob/main/skills/frameworks/clerk-chrome-extension-patterns/references/create-clerk-client.md Use `createClerkClient()` for popups or side panels not using React. Configure redirect URLs and allowed protocols for seamless authentication flow. ```typescript import { createClerkClient } from '@clerk/chrome-extension/client' const publishableKey = process.env.CLERK_PUBLISHABLE_KEY const EXTENSION_URL = chrome.runtime.getURL('.') const POPUP_URL = `${EXTENSION_URL}popup.html` const clerk = createClerkClient({ publishableKey }) const contentEl = document.getElementById('content') as HTMLDivElement function render() { const email = clerk.user?.primaryEmailAddress?.emailAddress contentEl.textContent = email ?? 'Not signed in' } clerk.load({ afterSignOutUrl: POPUP_URL, signInForceRedirectUrl: POPUP_URL, signUpForceRedirectUrl: POPUP_URL, allowedRedirectProtocols: ['chrome-extension:'], }).then(() => { clerk.addListener(render) render() }) ``` -------------------------------- ### ClerkProvider Setup in React SPA Source: https://context7.com/clerk/skills/llms.txt Wrap your React application with ClerkProvider at the root. Ensure the VITE_CLERK_PUBLISHABLE_KEY environment variable is set. ```tsx import { ClerkProvider } from '@clerk/react' const PUBLISHABLE_KEY = import.meta.env.VITE_CLERK_PUBLISHABLE_KEY createRoot(document.getElementById('root')!).render( ) ``` -------------------------------- ### Link Existing Project to Clerk App Source: https://github.com/clerk/skills/blob/main/skills/core/clerk-setup/SKILL.md For existing projects and Clerk apps, log in if necessary, then link the project. `clerk link` autolinks if a publishable key is present; otherwise, use `clerk link --app app_xxx` for explicit linking. Finally, pull environment variables. ```bash clerk auth login # one-time OAuth (skip if already logged in) clerk link # autolinks if a CLERK_PUBLISHABLE_KEY is in your .env clerk link --app app_xxx # explicit form, required in agent mode clerk env pull # writes the framework-detected env vars ``` -------------------------------- ### Organization-Scoped Cache Source: https://github.com/clerk/skills/blob/main/skills/frameworks/clerk-nextjs-patterns/references/caching-auth.md Cache organization-specific data by including the `orgId` in the cache key and tags. This example assumes `orgId` is available from `auth()`. ```typescript const { orgId } = await auth(); const getOrgData = unstable_cache( () => db.orgData.findMany({ where: { organizationId: orgId } }), [`org-${orgId}-data`], { revalidate: 300, tags: [`org-${orgId}`] } ); ``` -------------------------------- ### Session Task: Choose Organization Setup Source: https://context7.com/clerk/skills/llms.txt Configure ClerkProvider with `taskUrls` for the 'choose-organization' task. Then, implement the `TaskChooseOrganization` component in the specified route. ```tsx // In layout.tsx: import { ClerkProvider } from '@clerk/nextjs' // In app/session-tasks/choose-organization/page.tsx: import { TaskChooseOrganization } from '@clerk/nextjs' export default function Page() { return } ``` -------------------------------- ### Create Organization and Invite Member (TypeScript SDK) Source: https://github.com/clerk/skills/blob/main/skills/core/clerk-backend-api/SKILL.md This TypeScript example demonstrates creating an organization and inviting a member using the Clerk SDK for Next.js or backend applications. It requires the user ID for organization creation and specifies the role for the invited member. ```typescript import { clerkClient } from '@clerk/nextjs/server' // OR if using @clerk/backend directly: // import { createClerkClient } from '@clerk/backend' // const clerkClient = createClerkClient({ secretKey: process.env.CLERK_SECRET_KEY }) // Step 1: Create organization const org = await clerkClient.organizations.createOrganization({ name: 'Acme Corp', createdBy: userId, // required — the ID of the user creating the org }) // Step 2: Invite member to the org const invitation = await clerkClient.organizations.createOrganizationInvitation({ organizationId: org.id, emailAddress: 'user@example.com', role: 'org:admin', // or 'org:member' }) ``` -------------------------------- ### useSignIn() Methods (Core 3) Source: https://context7.com/clerk/skills/llms.txt Demonstrates various methods available through the `useSignIn` hook for handling different authentication strategies like password, SSO, Passkey, Email OTP, Phone OTP, MFA, and password reset. ```APIDOC ## Password await signIn.password({ identifier: 'user@example.com', password: 'secret' }) ## SSO / OAuth await signIn.sso({ strategy: 'oauth_google', redirectUrl: '/dashboard', redirectCallbackUrl: '/sso-callback' }) ## Passkey await signIn.passkey({ flow: 'discoverable' }) ## Email OTP await signIn.emailCode.sendCode({ emailAddress: 'user@example.com' }) await signIn.emailCode.verifyCode({ code: '123456' }) ## Phone OTP await signIn.phoneCode.sendCode({ phoneNumber: '+12015551234' }) await signIn.phoneCode.verifyCode({ code: '123456' }) ## MFA (second factor) await signIn.mfa.verifyTOTP({ code: '123456' }) // Authenticator app await signIn.mfa.verifyBackupCode({ code: 'backup-xxx' }) await signIn.mfa.sendPhoneCode() && signIn.mfa.verifyPhoneCode({ code: '123456' }) ## Password reset await signIn.resetPasswordEmailCode.sendCode() await signIn.resetPasswordEmailCode.verifyCode({ code: '123456' }) await signIn.resetPasswordEmailCode.submitPassword({ password: 'newPassword' }) ``` -------------------------------- ### Ref vs Value Usage Source: https://github.com/clerk/skills/blob/main/skills/frameworks/clerk-nuxt-patterns/references/composables.md Explains how composables return Ref values and how to access them correctly in script setup versus templates. ```APIDOC ## Ref vs Value ### Description Composables return `Ref` values. Access with `.value` in ` ``` ```