clerk-observability

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

1,868 stars

Best use case

clerk-observability is best used when you need a repeatable AI agent workflow instead of a one-off prompt.

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

Teams using clerk-observability 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

$curl -o ~/.claude/skills/clerk-observability/SKILL.md --create-dirs "https://raw.githubusercontent.com/jeremylongshore/claude-code-plugins-plus-skills/main/plugins/saas-packs/clerk-pack/skills/clerk-observability/SKILL.md"

Manual Installation

  1. Download SKILL.md from GitHub
  2. Place it in .claude/skills/clerk-observability/SKILL.md inside your project
  3. Restart your AI agent — it will auto-discover the skill

How clerk-observability Compares

Feature / Agentclerk-observabilityStandard Approach
Platform SupportNot specifiedLimited / Varies
Context Awareness High Baseline
Installation ComplexityUnknownN/A

Frequently Asked Questions

What does this skill do?

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

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

SKILL.md Source

# 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
```typescript
// 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
```typescript
// 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
```typescript
// 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
```typescript
// 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
    }
  }
}
```

```typescript
// 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
```typescript
// 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
```typescript
// 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
| Issue | Monitoring 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 anomalies | Track unusual sign-in patterns via audit log |
| Clerk API errors | Capture with Sentry context, check status.clerk.com |

## Examples

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

## Resources
- [Clerk Dashboard Analytics](https://dashboard.clerk.com)
- [Sentry Next.js Integration](https://docs.sentry.io/platforms/javascript/guides/nextjs/)
- [Pino Logger](https://getpino.io/)

## Next Steps
Proceed to `clerk-incident-runbook` for incident response procedures.

Related Skills

windsurf-observability

1868
from jeremylongshore/claude-code-plugins-plus-skills

Monitor Windsurf AI adoption, feature usage, and team productivity metrics. Use when tracking AI feature usage, measuring ROI, setting up dashboards, or analyzing Cascade effectiveness across your team. Trigger with phrases like "windsurf monitoring", "windsurf metrics", "windsurf analytics", "windsurf usage", "windsurf adoption".

webflow-observability

1868
from jeremylongshore/claude-code-plugins-plus-skills

Set up observability for Webflow integrations — Prometheus metrics for API calls, OpenTelemetry tracing, structured logging with pino, Grafana dashboards, and alerting for rate limits, errors, and latency. Trigger with phrases like "webflow monitoring", "webflow metrics", "webflow observability", "monitor webflow", "webflow alerts", "webflow tracing".

vercel-observability

1868
from jeremylongshore/claude-code-plugins-plus-skills

Set up Vercel observability with runtime logs, analytics, log drains, and OpenTelemetry tracing. Use when implementing monitoring for Vercel deployments, setting up log drains, or configuring alerting for function errors and performance. Trigger with phrases like "vercel monitoring", "vercel metrics", "vercel observability", "vercel logs", "vercel alerts", "vercel tracing".

veeva-observability

1868
from jeremylongshore/claude-code-plugins-plus-skills

Veeva Vault observability for enterprise operations. Use when implementing advanced Veeva Vault patterns. Trigger: "veeva observability".

vastai-observability

1868
from jeremylongshore/claude-code-plugins-plus-skills

Monitor Vast.ai GPU instance health, utilization, and costs. Use when setting up monitoring dashboards, configuring alerts, or tracking GPU utilization and spending. Trigger with phrases like "vastai monitoring", "vastai metrics", "vastai observability", "monitor vastai", "vastai alerts".

twinmind-observability

1868
from jeremylongshore/claude-code-plugins-plus-skills

Monitor TwinMind transcription quality, meeting coverage, action item extraction rates, and memory vault health. Use when implementing observability, or managing TwinMind meeting AI operations. Trigger with phrases like "twinmind observability", "twinmind observability".

speak-observability

1868
from jeremylongshore/claude-code-plugins-plus-skills

Monitor Speak API health, assessment latency, session metrics, and pronunciation score distributions. Use when implementing observability, or managing Speak language learning platform operations. Trigger with phrases like "speak observability", "speak observability".

snowflake-observability

1868
from jeremylongshore/claude-code-plugins-plus-skills

Set up Snowflake observability using ACCOUNT_USAGE views, alerts, and external monitoring. Use when implementing Snowflake monitoring dashboards, setting up query performance tracking, or configuring alerting for warehouse and pipeline health. Trigger with phrases like "snowflake monitoring", "snowflake metrics", "snowflake observability", "snowflake dashboard", "snowflake alerts".

shopify-observability

1868
from jeremylongshore/claude-code-plugins-plus-skills

Set up observability for Shopify app integrations with query cost tracking, rate limit monitoring, webhook delivery metrics, and structured logging. Trigger with phrases like "shopify monitoring", "shopify metrics", "shopify observability", "monitor shopify API", "shopify alerts", "shopify dashboard".

salesforce-observability

1868
from jeremylongshore/claude-code-plugins-plus-skills

Set up observability for Salesforce integrations with API limit monitoring, error tracking, and alerting. Use when implementing monitoring for Salesforce operations, tracking API consumption, or configuring alerting for Salesforce integration health. Trigger with phrases like "salesforce monitoring", "salesforce metrics", "salesforce observability", "monitor salesforce", "salesforce alerts", "salesforce API usage dashboard".

retellai-observability

1868
from jeremylongshore/claude-code-plugins-plus-skills

Retell AI observability — AI voice agent and phone call automation. Use when working with Retell AI for voice agents, phone calls, or telephony. Trigger with phrases like "retell observability", "retellai-observability", "voice agent".

replit-observability

1868
from jeremylongshore/claude-code-plugins-plus-skills

Monitor Replit deployments with health checks, uptime tracking, resource usage, and alerting. Use when setting up monitoring for Replit apps, building health dashboards, or configuring alerting for deployment health and performance. Trigger with phrases like "replit monitoring", "replit metrics", "replit observability", "monitor replit", "replit alerts", "replit uptime".