clerk-reference-architecture
Reference architecture patterns for Clerk authentication. Use when designing application architecture, planning auth flows, or implementing enterprise-grade authentication. Trigger with phrases like "clerk architecture", "clerk design", "clerk system design", "clerk integration patterns".
Best use case
clerk-reference-architecture is best used when you need a repeatable AI agent workflow instead of a one-off prompt.
Reference architecture patterns for Clerk authentication. Use when designing application architecture, planning auth flows, or implementing enterprise-grade authentication. Trigger with phrases like "clerk architecture", "clerk design", "clerk system design", "clerk integration patterns".
Teams using clerk-reference-architecture should expect a more consistent output, faster repeated execution, less prompt rewriting.
When to use this skill
- You want a reusable workflow that can be run more than once with consistent structure.
When not to use this skill
- You only need a quick one-off answer and do not need a reusable workflow.
- You cannot install or maintain the underlying files, dependencies, or repository context.
Installation
Claude Code / Cursor / Codex
Manual Installation
- Download SKILL.md from GitHub
- Place it in
.claude/skills/clerk-reference-architecture/SKILL.mdinside your project - Restart your AI agent — it will auto-discover the skill
How clerk-reference-architecture Compares
| Feature / Agent | clerk-reference-architecture | Standard Approach |
|---|---|---|
| Platform Support | Not specified | Limited / Varies |
| Context Awareness | High | Baseline |
| Installation Complexity | Unknown | N/A |
Frequently Asked Questions
What does this skill do?
Reference architecture patterns for Clerk authentication. Use when designing application architecture, planning auth flows, or implementing enterprise-grade authentication. Trigger with phrases like "clerk architecture", "clerk design", "clerk system design", "clerk integration patterns".
Where can I find the source code?
You can find the source code on GitHub using the link provided at the top of the page.
Related Guides
Best AI Skills for Claude
Explore the best AI skills for Claude and Claude Code across coding, research, workflow automation, documentation, and agent operations.
ChatGPT vs Claude for Agent Skills
Compare ChatGPT and Claude for AI agent skills across coding, writing, research, and reusable workflow execution.
SKILL.md Source
# Clerk Reference Architecture
## Overview
Reference architectures for implementing Clerk in common application patterns: Next.js full-stack, microservices with shared auth, multi-tenant SaaS, and mobile + web with shared backend.
## Prerequisites
- Understanding of web application architecture
- Familiarity with authentication patterns (JWT, sessions, OAuth)
- Knowledge of your tech stack and scaling requirements
## Instructions
### Architecture 1: Next.js Full-Stack Application
```
Browser
│
├─▸ Next.js Middleware (clerkMiddleware)
│ └─▸ Validates session token on every request
│
├─▸ Server Components (auth(), currentUser())
│ └─▸ Direct access to user data, no network call
│
├─▸ Client Components (useUser(), useAuth())
│ └─▸ Real-time auth state via ClerkProvider
│
├─▸ API Routes (auth() for userId, getToken() for JWT)
│ └─▸ Call external services with Clerk JWT
│
└─▸ Webhooks (/api/webhooks/clerk)
└─▸ Sync user data to database
```
```typescript
// app/layout.tsx — entry point
import { ClerkProvider } from '@clerk/nextjs'
export default function RootLayout({ children }: { children: React.ReactNode }) {
return (
<ClerkProvider>
<html><body>{children}</body></html>
</ClerkProvider>
)
}
```
```typescript
// middleware.ts — auth boundary
import { clerkMiddleware, createRouteMatcher } from '@clerk/nextjs/server'
const isPublic = createRouteMatcher(['/', '/sign-in(.*)', '/sign-up(.*)', '/api/webhooks(.*)'])
export default clerkMiddleware(async (auth, req) => {
if (!isPublic(req)) await auth.protect()
})
```
### Architecture 2: Microservices with Shared Auth
```
Browser ─▸ API Gateway / BFF (Next.js + Clerk)
│
├─▸ Service A (Node.js) ──── verifies JWT
├─▸ Service B (Python) ──── verifies JWT
└─▸ Service C (Go) ──────── verifies JWT
```
```typescript
// BFF: Generate service-specific JWT
// app/api/proxy/[service]/route.ts
import { auth } from '@clerk/nextjs/server'
export async function GET(req: Request, { params }: { params: { service: string } }) {
const { userId, getToken } = await auth()
if (!userId) return Response.json({ error: 'Unauthorized' }, { status: 401 })
// Get JWT with service-specific claims
const token = await getToken({ template: params.service })
const serviceUrls: Record<string, string> = {
billing: process.env.BILLING_SERVICE_URL!,
analytics: process.env.ANALYTICS_SERVICE_URL!,
notifications: process.env.NOTIFICATION_SERVICE_URL!,
}
const response = await fetch(`${serviceUrls[params.service]}/api/data`, {
headers: { Authorization: `Bearer ${token}` },
})
return Response.json(await response.json())
}
```
```typescript
// Downstream service: Verify Clerk JWT
// services/billing/src/middleware.ts (Express)
import { clerkMiddleware, requireAuth } from '@clerk/express'
app.use(clerkMiddleware())
app.get('/api/data', requireAuth(), (req, res) => {
// req.auth.userId is available
res.json({ userId: req.auth.userId })
})
```
### Architecture 3: Multi-Tenant SaaS
```
Tenant A (org_abc) ──┐
Tenant B (org_def) ──┤──▸ Shared App ──▸ Shared DB (tenant-scoped queries)
Tenant C (org_ghi) ──┘
```
```typescript
// lib/tenant.ts — tenant-scoped data access
import { auth } from '@clerk/nextjs/server'
export async function getTenantData<T>(query: (orgId: string) => Promise<T>): Promise<T> {
const { orgId } = await auth()
if (!orgId) throw new Error('No organization selected')
return query(orgId)
}
// Usage:
export async function getProjects() {
return getTenantData((orgId) =>
db.project.findMany({ where: { organizationId: orgId } })
)
}
```
```typescript
// middleware.ts — enforce org context on tenant routes
import { clerkMiddleware, createRouteMatcher } from '@clerk/nextjs/server'
const isTenantRoute = createRouteMatcher(['/app(.*)'])
export default clerkMiddleware(async (auth, req) => {
if (isTenantRoute(req)) {
const { orgId } = await auth.protect()
if (!orgId) {
// Redirect to org selector if no org is active
return Response.redirect(new URL('/select-org', req.url))
}
}
})
```
```typescript
// app/select-org/page.tsx
import { OrganizationSwitcher } from '@clerk/nextjs'
export default function SelectOrg() {
return (
<div className="flex min-h-screen items-center justify-center">
<div>
<h1>Select Your Organization</h1>
<OrganizationSwitcher
afterSelectOrganizationUrl="/app/dashboard"
hidePersonal={true}
/>
</div>
</div>
)
}
```
### Architecture 4: Mobile + Web with Shared Backend
```
Web App (Next.js + @clerk/nextjs) ──┐
Mobile App (React Native + @clerk/clerk-expo) ──┤──▸ Backend API (Express + @clerk/express)
└──▸ Database
```
```typescript
// Backend API: Express with Clerk
// server.ts
import express from 'express'
import { clerkMiddleware, requireAuth, getAuth } from '@clerk/express'
const app = express()
// Apply Clerk middleware globally
app.use(clerkMiddleware())
// Public endpoint
app.get('/api/public', (req, res) => {
res.json({ message: 'Public endpoint' })
})
// Protected endpoint (works with both web and mobile clients)
app.get('/api/profile', requireAuth(), async (req, res) => {
const { userId } = getAuth(req)
const user = await db.user.findUnique({ where: { clerkId: userId } })
res.json({ user })
})
app.listen(3001)
```
## Output
- Next.js full-stack architecture with middleware, server/client components, and webhooks
- Microservices architecture with BFF proxy and JWT-based service auth
- Multi-tenant SaaS with organization-scoped data access
- Mobile + web with shared Express backend using `@clerk/express`
## Error Handling
| Pattern | Common Issue | Solution |
|---------|-------------|----------|
| Full-stack | Middleware redirect loop | Add sign-in route to public routes |
| Microservices | JWT template not configured | Create JWT template in Dashboard per service |
| Multi-tenant | No org selected | Redirect to org selector before tenant routes |
| Mobile + Web | Token not sent from mobile | Include `Authorization: Bearer <token>` in mobile fetch |
## Examples
### Database Schema for Clerk Integration
```prisma
// prisma/schema.prisma
model User {
id String @id @default(cuid())
clerkId String @unique
email String @unique
name String?
createdAt DateTime @default(now())
posts Post[]
orgMemberships OrgMembership[]
}
model OrgMembership {
id String @id @default(cuid())
userId String
orgId String // Clerk organization ID
role String // org:admin, org:member, etc.
user User @relation(fields: [userId], references: [id])
@@unique([userId, orgId])
}
```
## Resources
- [Clerk Architecture Patterns](https://clerk.com/docs/quickstarts/nextjs)
- [Clerk Organizations (Multi-Tenant)](https://clerk.com/docs/organizations/overview)
- [Clerk Express Integration](https://clerk.com/docs/quickstarts/express)
## Next Steps
Proceed to `clerk-multi-env-setup` for multi-environment configuration.Related Skills
workhuman-reference-architecture
Workhuman reference architecture for employee recognition and rewards API. Use when integrating Workhuman Social Recognition, or building recognition workflows with HRIS systems. Trigger: "workhuman reference architecture".
wispr-reference-architecture
Wispr Flow reference architecture for voice-to-text API integration. Use when integrating Wispr Flow dictation, WebSocket streaming, or building voice-powered applications. Trigger: "wispr reference architecture".
windsurf-reference-architecture
Implement Windsurf reference architecture with optimal project structure and AI configuration. Use when designing workspace configuration for Windsurf, setting up team standards, or establishing architecture patterns that maximize Cascade effectiveness. Trigger with phrases like "windsurf architecture", "windsurf project structure", "windsurf best practices", "windsurf team setup", "optimize for cascade".
windsurf-architecture-variants
Choose workspace architectures for different project scales in Windsurf. Use when deciding how to structure Windsurf workspaces for monorepos, multi-service setups, or polyglot codebases. Trigger with phrases like "windsurf workspace strategy", "windsurf monorepo", "windsurf project layout", "windsurf multi-service", "windsurf workspace size".
webflow-reference-architecture
Implement Webflow reference architecture — layered project structure, client wrapper, CMS sync service, webhook handlers, and caching layer for production integrations. Trigger with phrases like "webflow architecture", "webflow project structure", "how to organize webflow", "webflow integration design", "webflow best practices".
vercel-reference-architecture
Implement a Vercel reference architecture with layered project structure and best practices. Use when designing new Vercel projects, reviewing project structure, or establishing architecture standards for Vercel applications. Trigger with phrases like "vercel architecture", "vercel project structure", "vercel best practices layout", "how to organize vercel project".
vercel-architecture-variants
Choose and implement Vercel architecture blueprints for different scales and use cases. Use when designing new Vercel projects, choosing between static, serverless, and edge architectures, or planning how to structure a multi-project Vercel deployment. Trigger with phrases like "vercel architecture", "vercel blueprint", "how to structure vercel", "vercel monorepo", "vercel multi-project".
veeva-reference-architecture
Veeva Vault reference architecture for REST API and clinical operations. Use when working with Veeva Vault document management and CRM. Trigger: "veeva reference architecture".
vastai-reference-architecture
Implement Vast.ai reference architecture for GPU compute workflows. Use when designing ML training pipelines, structuring GPU orchestration, or establishing architecture patterns for Vast.ai applications. Trigger with phrases like "vastai architecture", "vastai design pattern", "vastai project structure", "vastai ml pipeline".
twinmind-reference-architecture
Production architecture for meeting AI systems using TwinMind: transcription pipeline, memory vault, action item workflow, and calendar integration. Use when implementing reference architecture, or managing TwinMind meeting AI operations. Trigger with phrases like "twinmind reference architecture", "twinmind reference architecture".
together-reference-architecture
Together AI reference architecture for inference, fine-tuning, and model deployment. Use when working with Together AI's OpenAI-compatible API. Trigger: "together reference architecture".
techsmith-reference-architecture
TechSmith reference architecture for Snagit COM API and Camtasia automation. Use when working with TechSmith screen capture and video editing automation. Trigger: "techsmith reference architecture".