clerk-reference-architecture

0
0
Source

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".

Install

mkdir -p .claude/skills/clerk-reference-architecture && curl -L -o skill.zip "https://mcp.directory/api/skills/download/4780" && unzip -o skill.zip -d .claude/skills/clerk-reference-architecture && rm skill.zip

Installs to .claude/skills/clerk-reference-architecture

About this skill

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
// 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>
  )
}
// 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
// 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())
}
// 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) ──┘
// 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 } })
  )
}
// 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))
    }
  }
})
// 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
// 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

PatternCommon IssueSolution
Full-stackMiddleware redirect loopAdd sign-in route to public routes
MicroservicesJWT template not configuredCreate JWT template in Dashboard per service
Multi-tenantNo org selectedRedirect to org selector before tenant routes
Mobile + WebToken not sent from mobileInclude Authorization: Bearer <token> in mobile fetch

Examples

Database Schema for Clerk Integration

// 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

Next Steps

Proceed to clerk-multi-env-setup for multi-environment configuration.

svg-icon-generator

jeremylongshore

Svg Icon Generator - Auto-activating skill for Visual Content. Triggers on: svg icon generator, svg icon generator Part of the Visual Content skill category.

6814

d2-diagram-creator

jeremylongshore

D2 Diagram Creator - Auto-activating skill for Visual Content. Triggers on: d2 diagram creator, d2 diagram creator Part of the Visual Content skill category.

2412

performing-penetration-testing

jeremylongshore

This skill enables automated penetration testing of web applications. It uses the penetration-tester plugin to identify vulnerabilities, including OWASP Top 10 threats, and suggests exploitation techniques. Use this skill when the user requests a "penetration test", "pentest", "vulnerability assessment", or asks to "exploit" a web application. It provides comprehensive reporting on identified security flaws.

379

designing-database-schemas

jeremylongshore

Design and visualize efficient database schemas, normalize data, map relationships, and generate ERD diagrams and SQL statements.

978

performing-security-audits

jeremylongshore

This skill allows Claude to conduct comprehensive security audits of code, infrastructure, and configurations. It leverages various tools within the security-pro-pack plugin, including vulnerability scanning, compliance checking, cryptography review, and infrastructure security analysis. Use this skill when a user requests a "security audit," "vulnerability assessment," "compliance review," or any task involving identifying and mitigating security risks. It helps to ensure code and systems adhere to security best practices and compliance standards.

86

analyzing-logs

jeremylongshore

Analyze application logs to detect performance issues, identify error patterns, and improve stability by extracting key insights.

965

You might also like

flutter-development

aj-geddes

Build beautiful cross-platform mobile apps with Flutter and Dart. Covers widgets, state management with Provider/BLoC, navigation, API integration, and material design.

643969

drawio-diagrams-enhanced

jgtolentino

Create professional draw.io (diagrams.net) diagrams in XML format (.drawio files) with integrated PMP/PMBOK methodologies, extensive visual asset libraries, and industry-standard professional templates. Use this skill when users ask to create flowcharts, swimlane diagrams, cross-functional flowcharts, org charts, network diagrams, UML diagrams, BPMN, project management diagrams (WBS, Gantt, PERT, RACI), risk matrices, stakeholder maps, or any other visual diagram in draw.io format. This skill includes access to custom shape libraries for icons, clipart, and professional symbols.

591705

ui-ux-pro-max

nextlevelbuilder

"UI/UX design intelligence. 50 styles, 21 palettes, 50 font pairings, 20 charts, 8 stacks (React, Next.js, Vue, Svelte, SwiftUI, React Native, Flutter, Tailwind). Actions: plan, build, create, design, implement, review, fix, improve, optimize, enhance, refactor, check UI/UX code. Projects: website, landing page, dashboard, admin panel, e-commerce, SaaS, portfolio, blog, mobile app, .html, .tsx, .vue, .svelte. Elements: button, modal, navbar, sidebar, card, table, form, chart. Styles: glassmorphism, claymorphism, minimalism, brutalism, neumorphism, bento grid, dark mode, responsive, skeuomorphism, flat design. Topics: color palette, accessibility, animation, layout, typography, font pairing, spacing, hover, shadow, gradient."

318399

godot

bfollington

This skill should be used when working on Godot Engine projects. It provides specialized knowledge of Godot's file formats (.gd, .tscn, .tres), architecture patterns (component-based, signal-driven, resource-based), common pitfalls, validation tools, code templates, and CLI workflows. The `godot` command is available for running the game, validating scripts, importing resources, and exporting builds. Use this skill for tasks involving Godot game development, debugging scene/resource files, implementing game systems, or creating new Godot components.

340397

nano-banana-pro

garg-aayush

Generate and edit images using Google's Nano Banana Pro (Gemini 3 Pro Image) API. Use when the user asks to generate, create, edit, modify, change, alter, or update images. Also use when user references an existing image file and asks to modify it in any way (e.g., "modify this image", "change the background", "replace X with Y"). Supports both text-to-image generation and image-to-image editing with configurable resolution (1K default, 2K, or 4K for high resolution). DO NOT read the image file first - use this skill directly with the --input-image parameter.

452339

fastapi-templates

wshobson

Create production-ready FastAPI projects with async patterns, dependency injection, and comprehensive error handling. Use when building new FastAPI applications or setting up backend API projects.

304231

Stay ahead of the MCP ecosystem

Get weekly updates on new skills and servers.