/clerk:api-authenticationfrom clerk
Configures Clerk JWT middleware and route protection for Express, Fastify, Next.js, FastAPI, and GraphQL backends. Generates type-safe API clients with automatic token handling.
Ships in clerk. Installing the plugin adds it to Claude Code.
What the skill costs in Claude's context, stage by stage
Name and description: Claude knows it exists.
SKILL.md joins the conversation and stays.
Read when SKILL.md points to them; scripts run unread.
Backend API authentication skill for Clerk integration. Provides JWT middleware, route protection patterns, and API client generation for REST and GraphQL backends.
Run the setup script to configure backend authentication:
bash scripts/setup-api-auth.sh <framework> <project-path>
Supported Frameworks:
express - Express.js middlewarefastify - Fastify decoratorsnextjs - Next.js API route helpersfastapi - FastAPI dependencies (Python)What it does:
For Express/Node.js backends:
Use the api-middleware.ts template:
import { requireAuth } from './middleware/clerk-auth'
// Protect individual routes
app.get('/api/protected', requireAuth, (req, res) => {
const userId = req.auth.userId
res.json({ message: 'Protected data', userId })
})
// Protect route groups
app.use('/api/admin', requireAuth, adminRouter)
For Next.js API routes:
Use the api-routes.ts template:
import { withAuth } from '@/lib/clerk-middleware'
export default withAuth(async (req, res) => {
const { userId } = req.auth
// Protected route logic
})
For GraphQL:
Use the graphql-clerk.ts example:
import { ClerkExpressRequireAuth } from '@clerk/clerk-sdk-node'
const server = new ApolloServer({
context: ({ req }) => ({
userId: req.auth?.userId,
user: req.auth?.user
})
})
app.use('/graphql', ClerkExpressRequireAuth(), apolloMiddleware)
Create type-safe API clients with authentication headers:
bash scripts/generate-api-client.sh <api-type> <output-path>
API Types:
rest - REST API client with fetchgraphql - GraphQL client with Apolloaxios - Axios-based REST clienttrpc - tRPC client with auth contextGenerated Client Features:
Run comprehensive authentication tests:
bash scripts/test-api-auth.sh <project-path>
Test Coverage:
// middleware/clerk-auth.ts
import { ClerkExpressRequireAuth } from '@clerk/clerk-sdk-node'
export const requireAuth = ClerkExpressRequireAuth({
onError: (error) => {
console.error('Auth error:', error)
return { status: 401, message: 'Unauthorized' }
}
})
// Optional auth (allows both authenticated and anonymous)
export const optionalAuth = ClerkExpressWithAuth()
// lib/jwt-verify.ts
import { verifyToken } from '@clerk/backend'
export async function validateJWT(token: string) {
try {
const payload = await verifyToken(token, {
secretKey: process.env.CLERK_SECRET_KEY
})
return { valid: true, userId: payload.sub }
} catch (error) {
return { valid: false, error: error.message }
}
}
// middleware/rbac.ts
export function requireRole(role: string) {
return async (req, res, next) => {
const { userId } = req.auth
const user = await clerkClient.users.getUser(userId)
if (user.publicMetadata.role !== role) {
return res.status(403).json({ error: 'Forbidden' })
}
next()
}
}
// Usage
app.get('/api/admin', requireAuth, requireRole('admin'), handler)
// graphql/context.ts
import { ClerkExpressRequireAuth } from '@clerk/clerk-sdk-node'
export const context = async ({ req }) => {
const userId = req.auth?.userId
if (!userId) {
throw new AuthenticationError('Must be authenticated')
}
const user = await clerkClient.users.getUser(userId)
return {
userId,
user,
isAdmin: user.publicMetadata.role === 'admin'
}
}
Required environment variables (always use placeholders in committed files):
# .env.example
CLERK_PUBLISHABLE_KEY=your_clerk_publishable_key_here
CLERK_SECRET_KEY=your_clerk_secret_key_here
# Optional: For webhook verification
CLERK_WEBHOOK_SECRET=your_webhook_secret_here
# Optional: For custom JWT configuration
CLERK_JWT_KEY=your_jwt_key_here
Issue: "Invalid token" errors
CLERK_SECRET_KEY is correctIssue: CORS errors on API requests
Issue: "Missing userId" in request context
Issue: GraphQL authentication not working
templates/api-middleware.ts - Express/Node.js middlewaretemplates/api-routes.ts - Next.js API route helperstemplates/backend-sdk-setup.ts - Backend SDK initializationtemplates/fastapi-middleware.py - FastAPI authentication dependenciesexamples/rest-api.md - Complete REST API with authenticationexamples/graphql-api.md - GraphQL server with Clerk contextexamples/webhooks.md - Webhook event handling and processingscripts/setup-api-auth.sh - Configure backend authenticationscripts/generate-api-client.sh - Create authenticated API clientsscripts/test-api-auth.sh - Test authentication flowsThis skill follows strict security rules:
.gitignore protection documentedReference: @docs/security/SECURITY-RULES.md
examples/graphql-api.md (opens in a new tab)examples/rest-api.md (opens in a new tab)examples/webhooks.md (opens in a new tab)scripts/generate-api-client.sh (opens in a new tab)scripts/setup-api-auth.sh (opens in a new tab)scripts/test-api-auth.sh (opens in a new tab)templates/api-middleware.ts (opens in a new tab)templates/api-routes.ts (opens in a new tab)templates/backend-sdk-setup.ts (opens in a new tab)templates/fastapi-middleware.py (opens in a new tab)What SKILL.md sets; muted values are Claude Code's defaults
Three short reads, in order
npx claudepluginhub vanman2024/ai-dev-marketplace --plugin clerk10 skills in this plugin
/auth-componentsPre-built and custom Clerk authentication component templates with theming and customization patterns. Use when building authentication UI, creating sign-in/sign-up pages, customizing Clerk components, implementing user buttons, theming auth flows, or when user mentions Clerk components, SignIn, SignUp, UserButton, auth UI, appearance customization, or authentication theming./billing-integrationClerk Billing and Stripe subscription management setup. Use when implementing subscriptions, configuring pricing plans, setting up billing, adding payment flows, managing entitlements, or when user mentions Clerk Billing, Stripe integration, subscription management, pricing tables, payment processing, or monetization./middleware-protectionRoute protection and authorization patterns for Clerk middleware. Use when implementing route guards, protecting API routes, configuring middleware matchers, setting up role-based access control, creating auth boundaries, or when user mentions middleware, route protection, auth guards, protected routes, public routes, matcher patterns, or authorization middleware./nextjs-integrationComplete Next.js integration patterns for Clerk authentication with App Router and Pages Router. Use when setting up Clerk in Next.js, configuring authentication middleware, implementing protected routes, setting up server/client components with auth, or when user mentions Clerk Next.js setup, App Router auth, Pages Router auth, or Next.js authentication integration./oauth-providersConfigure OAuth authentication providers for Clerk (Google, GitHub, Discord, Apple, Microsoft, Facebook, LinkedIn, Twitter, and 11+ more). Use when setting up social login, configuring OAuth providers, implementing authentication flows, generating redirect URLs, testing OAuth connections, or when user mentions Clerk OAuth, social authentication, provider setup, or multi-provider auth./organization-managementImplement Clerk multi-tenant organization features with RBAC, role-based access control, organization switching, member management, and tenant isolation. Use when building multi-tenant SaaS applications, implementing organization hierarchies, configuring custom roles and permissions, setting up organization-scoped data isolation, or when user mentions organizations, RBAC, multi-tenancy, roles, permissions, organization switcher, member management, or tenant isolation.Other plugins' skills for the same job