plugins/clerk-auth-master/skills/clerk-backend-apis/SKILL.md
Use for Clerk backend request auth. PROACTIVELY activate for Express, Fastify, Node, Go, Ruby/Rails, Python/FastAPI/Django/Flask, Java/Spring, C#/.NET, PHP/Laravel, custom APIs, @clerk/express clerkMiddleware()/requireAuth()/getAuth(req), backend request state, cookies, Authorization Bearer tokens, cross-origin frontend-to-API calls, M2M/OAuth/API-key/session token validation, clerkClient Backend API users/orgs calls, proxies/CDNs/CORS/X-Forwarded headers, and 401/404 debugging. Provides middleware patterns, token verification flow, API client guardrails, and language-portable diagnostics.
npx skillsauth add JosiahSiegel/claude-plugin-marketplace clerk-backend-apisInstall this skill globally with one command. Works with Claude Code, Cursor, and Windsurf.
3 of 9 scanners reported clean
Some scanners were skipped, did not run, or reported a non-clean status. Review each row below.
Use this skill for Clerk authentication in backend services, API servers, workers, and server-to-server integrations. The key responsibilities are authenticating incoming requests, enforcing authorization on server resources, safely using the Backend API, and making cross-origin token behavior explicit.
Prefer official Clerk SDKs and middleware when available. When the target runtime lacks a first-class Clerk framework SDK, use Clerk-documented token verification and Backend API patterns rather than ad hoc JWT parsing.
The server flow is language-independent:
401 unauthenticated or 403/concealment unauthorized responses for APIs, unless using Clerk defaults intentionally.Avoid handwritten JWT parsing unless Clerk's official docs for the target language require a lower-level path. Clerk token semantics evolve, and framework SDKs handle edge cases better than custom code.
Register Clerk middleware before routes that need auth state. Use getAuth(req) in route handlers when custom JSON responses are preferred. Use requireAuth() when automatic route protection behavior fits the app.
Minimal shape:
import express from 'express'
import { clerkMiddleware, getAuth, requireAuth } from '@clerk/express'
const app = express()
app.use(clerkMiddleware())
app.get('/api/me', (req, res) => {
const { isAuthenticated, userId, orgId } = getAuth(req)
if (!isAuthenticated) return res.status(401).json({ error: 'Unauthorized' })
return res.json({ userId, orgId })
})
app.get('/api/protected', requireAuth(), (req, res) => {
res.json({ ok: true })
})
clerkMiddleware() checks request cookies and headers for a session JWT and attaches auth state to the request. getAuth(req) reads user ID, session ID, organization ID, and related auth state. clerkClient wraps Clerk's Backend API and must be instantiated according to the SDK's current docs before resource access.
Use Clerk's Fastify plugin where available. The documented model is:
clerkPlugin() with the Fastify app before protected routes.request.auth.getAuth(request) to retrieve current auth state.clerkClient server-side for Backend API calls after instantiation.If the framework integration does not expose requireAuth(), implement route guards with getAuth(request) and explicit JSON responses.
Same-origin browser requests in supported Clerk frameworks can often rely on Clerk-managed cookies. Cross-origin requests to a separate API origin must include a Bearer token retrieved from the frontend session.
Client pattern:
const token = await getToken()
await fetch('https://api.example.com/widgets', {
headers: { Authorization: `Bearer ${token}` },
})
Backend pattern:
Authorization header.Authorization header.Common mistakes: forgetting to await getToken(), relying on cookies across origins, stripping Authorization in a proxy, wildcard CORS with credentials, and debugging only browser navigations instead of direct API requests.
Clerk uses request headers to determine whether a request is signed in, signed out, or needs a handshake. Behind proxies, CDNs, and load balancers, preserve auth-relevant headers.
Required/important headers include:
AuthorizationAcceptHostOriginRefererSec-Fetch-DestUser-AgentX-Forwarded-HostX-Forwarded-Proto or CloudFront-Forwarded-ProtoWhen deploying behind CloudFront, Nginx, Vercel rewrites, Cloudflare, custom domains, API gateways, or Kubernetes ingress, test the exact production path. Local success does not prove forwarded headers survive production.
Use Clerk's Backend API client only from trusted server environments. Typical operations include fetching users, listing users, updating metadata, reading organizations, and managing memberships. Never expose Backend API credentials, secret keys, or administrative operations to browser code.
Instantiate the client according to the SDK's current docs before accessing resources. Avoid manual fetches to Clerk's API unless the SDK lacks the needed feature or the docs explicitly recommend direct API calls.
Use Backend API calls sparingly in hot paths. For high-traffic endpoints, prefer auth IDs from request state and store app-specific data in the application's database. Use webhooks for asynchronous denormalization when appropriate.
Use official Clerk middleware/plugins. Keep CLERK_SECRET_KEY on the server. Use getAuth()/request auth state for identity and org context. Use clerkClient only after authorization when calling administrative APIs.
Use Clerk's Go SDK or documented verification helpers if present for the project. If integrating manually, treat the process as verifying a Clerk-issued JWT against Clerk's documented issuer/JWKS/audience rules and extracting claims only after verification. Do not trust decoded claims without signature, issuer, audience, expiration, and token-type validation. Wrap the verification in middleware and attach a typed auth context to context.Context for handlers.
Use a request middleware/dependency/decorator pattern:
Authorization: Bearer <token> or documented Clerk cookie/header inputs.request.state, dependency return value, or framework context.For FastAPI, prefer dependency injection for protected routes. For Django/Flask, prefer middleware plus decorators/blueprint guards.
Use middleware or controller concerns before actions. Verify Clerk tokens with official SDK/helpers or documented JWT verification. Store verified auth state in request env/current context. Do not use params for user/org IDs. Use Rails credentials or server environment variables for Clerk secrets, not frontend packs/assets.
Use a servlet filter or Spring Security authentication provider. Verify Clerk tokens before controllers execute and populate the SecurityContext with a principal containing Clerk user ID, session ID, org ID, and token type. Use method-level authorization or service-layer checks for roles/org resources. Externalize keys/secrets with environment or secret manager configuration.
Use authentication middleware/JWT bearer configuration or a custom authentication handler aligned with Clerk's token verification docs. Populate ClaimsPrincipal only after issuer/audience/signature/expiration checks. Use authorization policies for org/role/permission checks. Keep secret keys in user secrets for local development and managed secret stores for production.
Use HTTP middleware to verify Clerk tokens before controllers. Attach verified auth state to the request/container/auth guard. Use policies/gates for resource authorization. Store Clerk server credentials in .env/secret manager and never expose them through frontend build variables.
Authentication answers “who or what made this request.” Authorization answers “may this identity do this action on this resource.” Enforce both.
Recommended checks:
userId/subject to resource ownership for personal resources.Do not trust user IDs, organization IDs, roles, plan values, or permissions submitted in request bodies. Derive them from the Clerk-authenticated request state or verified server-side records.
Design service-to-service endpoints separately from browser-session endpoints. Decide whether the endpoint accepts session tokens, machine-to-machine tokens, OAuth access tokens, API keys, or any of them. In Next.js, auth.protect() supports token-type checks; in other backends, follow equivalent Clerk docs for accepted token validation.
Recommended endpoint design:
userId, optionally require orgId.Return clear failure codes. Browser session flows may redirect, but API and machine flows should return JSON with 401 for unauthenticated requests and 403 or intentional concealment for unauthorized requests, unless using Clerk defaults that intentionally return 404.
Webhook endpoints are not authenticated user requests. Exempt them from session middleware protection, then verify Svix signatures with Clerk's verifyWebhook() helper or Svix verification libraries before trusting payloads. Do not apply user-session requireAuth() to webhook routes.
When a backend endpoint fails auth:
Authorization: Bearer <token> or valid cookies.Authorization header.Authorization and forwarding headers.development
Use for Clerk sessions, tokens, webhooks, orgs, and security. PROACTIVELY activate for session tokens, JWT templates, getToken(), custom claims, pending sessions, multi-session UX, organizations, roles, permissions, system vs custom permissions, features/plans, MFA/passkeys/password policy/bot protection, Clerk webhooks, Svix signatures, verifyWebhook(), user/org sync, retries/replays, environment variables, custom domains, secret rotation, logs, and auth security reviews. Provides token semantics, webhook idempotency, authorization defaults, and hardening checklist.
tools
Use for Clerk in Next.js. PROACTIVELY activate for @clerk/nextjs setup, App Router auth()/currentUser(), clerkMiddleware(), proxy.ts/middleware.ts, createRouteMatcher(), protected pages/layouts/Route Handlers/Server Actions/API routes/tRPC, auth.protect() role/permission/token checks, ClerkProvider placement, server-only clerkClient, Link prefetch, redirects, 401/404 auth failures, custom domains, __clerk proxy paths, and deployment gotchas. Provides file patterns, server/client boundary rules, matcher templates, and production checks.
development
Use for Clerk frontend auth flows. PROACTIVELY activate for React, JavaScript, Vue, Nuxt, Astro, Expo, React Router, TanStack React Start, or SPA setup; ClerkProvider and publishable-key wiring; SignIn/SignUp/UserButton/UserProfile/OrganizationSwitcher; custom useUser/useAuth/useClerk/useSignIn/useSignUp/useSession/useOrganization flows; multi-session UX; cross-origin getToken() fetches; loading states, redirects, routing, CORS/cookies, or hydration bugs. Provides SDK selection, UI patterns, token-fetch templates, and frontend gotchas.
development
Use for Clerk dev/prod readiness, deployment, and multi-language implementation planning. PROACTIVELY activate for environment variables, pk_test/sk_test vs pk_live/sk_live, local dev, preview/staging/prod instances, domains/DNS, redirects, OAuth credentials, custom domains/proxy, authorizedParties, CSP, CORS/cookies, webhooks/tunnels, Vercel/Netlify/Cloudflare/API gateways, monitoring/troubleshooting, and backends in Node/Express/Fastify, Python/FastAPI/Django/Flask, Go, Ruby/Rails, Java/Spring, .NET, PHP/Laravel. Provides checklists, rollout plans, and language-portable patterns.