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".
What this skill does
# 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 in Design
contribute
IncludedLocal-only OSS contribution command center. Auto-refreshes the user's in-flight PR and issue state on invoke so conversations start with full context — no need to brief Claude on what's in flight. Helps the user find issues to contribute to on GitHub, builds per-repo dossiers of what each upstream expects (CLA, DCO, branch convention, AI policy, draft-first, review bots, issue templates), runs deterministic gates before any external action so AI-assisted contributions don't reach maintainers as slop. State is markdown-only: candidate files at ~/.contribute-system/candidates/, repo dossiers at ~/.contribute-system/research/, append-only event log at ~/.contribute-system/log.jsonl. No database, no cloud calls. Use when the user asks about their PRs / issues / contributions, wants to find new work to take on, claim an issue, build/refresh a repo's dossier, or draft a Design Issue or PR. Trigger with "/contribute", "what's my PR status", "find a contribution", "claim issue X", "draft a Design Issue for Y", "refresh dossier for Z".
architectural-analysis
IncludedUser-triggered deep architectural analysis of a codebase or scoped subtree across eight modes — information architecture, data flow, integration points, UI surfaces, interaction patterns, data model, control flow, and failure modes. This skill should be used when the user asks to "diagram this codebase," "map the architecture," "show the data flow," "give me an ERD," "trace control flow," "find the integration points," "verify the layout pattern," "audit the UX architecture," or any similar request whose primary deliverable is mermaid diagrams plus cited reports under docs/architecture/. Dispatches haiku/sonnet sub-agents in parallel for per-mode exploration, then verifies every citation mechanically before any node lands in a diagram. Not for one-off prose explanations of code (use code-explanation) or for high-level system design from scratch (use system-design).
mcp
IncludedModel Context Protocol (MCP) server development and tool management. Languages: Python, TypeScript. Capabilities: build MCP servers, integrate external APIs, discover/execute MCP tools, manage multi-server configs, design agent-centric tools. Actions: create, build, integrate, discover, execute, configure MCP servers/tools. Keywords: MCP, Model Context Protocol, MCP server, MCP tool, stdio transport, SSE transport, tool discovery, resource provider, prompt template, external API integration, Gemini CLI MCP, Claude MCP, agent tools, tool execution, server config. Use when: building MCP servers, integrating external APIs as MCP tools, discovering available MCP tools, executing MCP capabilities, configuring multi-server setups, designing tools for AI agents.
react-native-skia
IncludedDesign, build, debug, and optimise high-polish animated graphics in React Native or Expo using @shopify/react-native-skia, Reanimated, and Gesture Handler. Use when the user wants canvas-driven UI, shaders, paths, rich text, image filters, sprite fields, Skottie, video frames, snapshots, web CanvasKit setup, or performance tuning for custom motion-heavy elements such as loaders, hero art, cards, charts, progress indicators, particle systems, or gesture-driven surfaces. Also use when the user asks for fluid, glow, glass, blob, parallax, 60fps/120fps, or GPU-friendly animated effects in React Native, even if they do not explicitly say "Skia". Do not use for ordinary form/layout work with standard views.
plaid
IncludedProduct Led AI Development — guides founders from idea to launched product. Six capabilities: Idea (discover a product idea), Validate (pressure-test the idea against fatal flaws, problem reality, competition, and 2-week MVP feasibility), Plan (vision intake + document generation), Design (translate image references into a design.md spec), Launch (go-to-market strategy), and Build (roadmap execution). Use when someone says "PLAID", "plaid idea", "help me find an idea", "product idea", "idea from my business", "idea from my expertise", "plaid validate", "validate my idea", "pressure-test", "is this idea good", "find fatal flaws", "validate the problem", "plan a product", "define my vision", "generate a PRD", "product strategy", "plaid design", "design from image", "translate image to design", "create design.md", "extract design tokens", "plaid launch", "go-to-market", "launch plan", "GTM strategy", "launch playbook", "plaid build", "build the app", "start building", or "execute the roadmap".
nextjs-framer-motion-animations
IncludedAdds production-safe Motion for React or Framer Motion animations to Next.js apps, including reveal, hover and tap micro-interactions, whileInView, stagger, AnimatePresence, layout and layoutId transitions, reorder, scroll-linked UI, and lightweight route-content transitions. Use when the user asks to add, refactor, or debug Motion or Framer Motion in App Router or Pages Router codebases, especially around server/client boundaries, reduced motion, LazyMotion, bundle size, hydration, or route transitions. Avoid for GSAP-style timelines, WebGL or 3D scenes, heavy scroll storytelling, or CSS-only effects unless Motion is explicitly requested.