clerk-observability

1
1
Source

Implement monitoring, logging, and observability for Clerk authentication. Use when setting up monitoring, debugging auth issues in production, or implementing audit logging. Trigger with phrases like "clerk monitoring", "clerk logging", "clerk observability", "clerk metrics", "clerk audit log".

Install

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

Installs to .claude/skills/clerk-observability

About this skill

Clerk Observability

Overview

Implement monitoring, logging, and observability for Clerk authentication. Covers structured auth logging, middleware performance tracking, webhook event monitoring, Sentry integration, and health check endpoints.

Prerequisites

  • Clerk integration working
  • Monitoring platform (Sentry, DataDog, or Pino logger at minimum)
  • Logging infrastructure (structured JSON logs recommended)

Instructions

Step 1: Structured Authentication Event Logging

// lib/auth-logger.ts
import pino from 'pino'

const logger = pino({
  level: process.env.LOG_LEVEL || 'info',
  transport: process.env.NODE_ENV === 'development' ? { target: 'pino-pretty' } : undefined,
})

export function logAuthEvent(event: {
  type: 'sign_in' | 'sign_out' | 'sign_up' | 'permission_denied' | 'session_expired'
  userId?: string | null
  orgId?: string | null
  path: string
  metadata?: Record<string, any>
}) {
  logger.info({
    category: 'auth',
    ...event,
    timestamp: new Date().toISOString(),
  })
}

export function logAuthError(error: Error, context: { userId?: string; path: string }) {
  logger.error({
    category: 'auth',
    error: error.message,
    stack: error.stack,
    ...context,
    timestamp: new Date().toISOString(),
  })
}

Step 2: Middleware Performance Monitoring

// middleware.ts
import { clerkMiddleware, createRouteMatcher } from '@clerk/nextjs/server'

const isPublicRoute = createRouteMatcher(['/', '/sign-in(.*)', '/sign-up(.*)'])

export default clerkMiddleware(async (auth, req) => {
  const start = Date.now()

  if (!isPublicRoute(req)) {
    await auth.protect()
  }

  const duration = Date.now() - start
  const { userId } = await auth()

  // Log slow auth checks
  if (duration > 100) {
    console.warn(`[Auth Perf] ${req.nextUrl.pathname} took ${duration}ms`, {
      userId: userId || 'anonymous',
      method: req.method,
    })
  }

  // Add timing header for debugging
  const response = new Response(null, { status: 200 })
  response.headers.set('X-Auth-Duration', `${duration}ms`)
})

Step 3: Webhook Event Tracking

// app/api/webhooks/clerk/route.ts
import { logAuthEvent } from '@/lib/auth-logger'

async function handleWebhookEvent(evt: WebhookEvent) {
  const startTime = Date.now()

  // Track webhook processing metrics
  const metrics = {
    eventType: evt.type,
    receivedAt: new Date().toISOString(),
    processingTimeMs: 0,
  }

  switch (evt.type) {
    case 'user.created':
      logAuthEvent({
        type: 'sign_up',
        userId: evt.data.id,
        path: '/webhooks/clerk',
        metadata: { email: evt.data.email_addresses[0]?.email_address },
      })
      await db.user.create({ data: { clerkId: evt.data.id } })
      break

    case 'session.created':
      logAuthEvent({
        type: 'sign_in',
        userId: evt.data.user_id,
        path: '/webhooks/clerk',
      })
      break

    case 'session.ended':
      logAuthEvent({
        type: 'sign_out',
        userId: evt.data.user_id,
        path: '/webhooks/clerk',
      })
      break
  }

  metrics.processingTimeMs = Date.now() - startTime

  // Alert on slow webhook processing
  if (metrics.processingTimeMs > 5000) {
    console.error('[Webhook] Slow processing:', metrics)
  }

  return Response.json({ received: true })
}

Step 4: Sentry Error Tracking Integration

// lib/sentry-clerk.ts
import * as Sentry from '@sentry/nextjs'
import { auth, currentUser } from '@clerk/nextjs/server'

export async function initSentryUser() {
  const { userId, orgId } = await auth()

  if (userId) {
    const user = await currentUser()
    Sentry.setUser({
      id: userId,
      email: user?.emailAddresses[0]?.emailAddress,
      username: user?.username || undefined,
    })
    Sentry.setTag('org_id', orgId || 'personal')
  }
}

// Wrap API routes with Sentry + Clerk context
export function withAuthSentry(handler: Function) {
  return async (...args: any[]) => {
    await initSentryUser()
    try {
      return await handler(...args)
    } catch (error) {
      Sentry.captureException(error)
      throw error
    }
  }
}
// sentry.server.config.ts
import * as Sentry from '@sentry/nextjs'

Sentry.init({
  dsn: process.env.SENTRY_DSN,
  tracesSampleRate: 0.1,
  beforeSend(event) {
    // Scrub Clerk secret key if accidentally logged
    if (event.extra) {
      delete event.extra['CLERK_SECRET_KEY']
    }
    return event
  },
})

Step 5: Health Check Endpoint

// app/api/health/route.ts
import { clerkClient } from '@clerk/nextjs/server'

export async function GET() {
  const checks: Record<string, { status: string; latencyMs: number; detail?: string }> = {}

  // Check Clerk Backend API
  const clerkStart = Date.now()
  try {
    const client = await clerkClient()
    await client.users.getUserList({ limit: 1 })
    checks.clerk = { status: 'healthy', latencyMs: Date.now() - clerkStart }
  } catch (err: any) {
    checks.clerk = { status: 'unhealthy', latencyMs: Date.now() - clerkStart, detail: err.message }
  }

  // Check database
  const dbStart = Date.now()
  try {
    await db.$queryRaw`SELECT 1`
    checks.database = { status: 'healthy', latencyMs: Date.now() - dbStart }
  } catch (err: any) {
    checks.database = { status: 'unhealthy', latencyMs: Date.now() - dbStart, detail: err.message }
  }

  const allHealthy = Object.values(checks).every((c) => c.status === 'healthy')
  return Response.json(
    { status: allHealthy ? 'healthy' : 'degraded', checks, timestamp: new Date().toISOString() },
    { status: allHealthy ? 200 : 503 }
  )
}

Step 6: Dashboard Metrics Query

// app/api/admin/auth-metrics/route.ts
import { auth } from '@clerk/nextjs/server'

export async function GET() {
  const { has } = await auth()
  if (!has({ role: 'org:admin' })) {
    return Response.json({ error: 'Forbidden' }, { status: 403 })
  }

  const now = new Date()
  const dayAgo = new Date(now.getTime() - 24 * 60 * 60 * 1000)

  const metrics = {
    signIns24h: await db.auditLog.count({
      where: { action: 'sign_in', timestamp: { gte: dayAgo } },
    }),
    signUps24h: await db.auditLog.count({
      where: { action: 'sign_up', timestamp: { gte: dayAgo } },
    }),
    authErrors24h: await db.auditLog.count({
      where: { action: 'permission_denied', timestamp: { gte: dayAgo } },
    }),
    webhookEvents24h: await db.webhookEvent.count({
      where: { processedAt: { gte: dayAgo } },
    }),
  }

  return Response.json(metrics)
}

Output

  • Structured auth event logging with Pino (sign-in, sign-out, sign-up, errors)
  • Middleware performance tracking with slow-request alerts
  • Webhook event monitoring with processing time metrics
  • Sentry integration with Clerk user context
  • Health check endpoint monitoring Clerk API and database
  • Admin metrics endpoint for auth dashboard

Error Handling

IssueMonitoring Action
High auth latency (p95 > 200ms)Alert via middleware timing logs, investigate caching
Webhook failure rate > 1%Alert on processing errors, check endpoint health
Session anomaliesTrack unusual sign-in patterns via audit log
Clerk API errorsCapture with Sentry context, check status.clerk.com

Examples

Quick Monitoring One-Liner

# Watch auth events in real-time (development)
LOG_LEVEL=debug npm run dev 2>&1 | grep '"category":"auth"'

Resources

Next Steps

Proceed to clerk-incident-runbook for incident response procedures.

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.

11240

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.

9033

automating-mobile-app-testing

jeremylongshore

This skill enables automated testing of mobile applications on iOS and Android platforms using frameworks like Appium, Detox, XCUITest, and Espresso. It generates end-to-end tests, sets up page object models, and handles platform-specific elements. Use this skill when the user requests mobile app testing, test automation for iOS or Android, or needs assistance with setting up device farms and simulators. The skill is triggered by terms like "mobile testing", "appium", "detox", "xcuitest", "espresso", "android test", "ios test".

18828

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.

5519

designing-database-schemas

jeremylongshore

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

12516

optimizing-sql-queries

jeremylongshore

This skill analyzes and optimizes SQL queries for improved performance. It identifies potential bottlenecks, suggests optimal indexes, and proposes query rewrites. Use this when the user mentions "optimize SQL query", "improve SQL performance", "SQL query optimization", "slow SQL query", or asks for help with "SQL indexing". The skill helps enhance database efficiency by analyzing query structure, recommending indexes, and reviewing execution plans.

5513

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.

1,6851,428

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

1,2661,333

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.

1,5381,147

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.

1,356809

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.

1,264728

pdf-to-markdown

aliceisjustplaying

Convert entire PDF documents to clean, structured Markdown for full context loading. Use this skill when the user wants to extract ALL text from a PDF into context (not grep/search), when discussing or analyzing PDF content in full, when the user mentions "load the whole PDF", "bring the PDF into context", "read the entire PDF", or when partial extraction/grepping would miss important context. This is the preferred method for PDF text extraction over page-by-page or grep approaches.

1,489684