Skip to main content Início Criadores jeremylongshore tons-of-skills-marketplace clerk-observability
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".
Ir para a instalação Skills Marketplace Descubra e explore skills de IA criadas pela comunidade.
Instalar com Codex ou Claude Copie este prompt, cole no Codex, Claude ou outro assistente e deixe que ele revise a página da skill e instale para você.
Copiar promptMostrar detalhes do prompt Um comando direto ignora o prompt de revisão. Verifique a origem antes de executá-lo.
npx skills add https://github.com/jeremylongshore/tons-of-skills-marketplace --skill clerk-observabilityO comando permanece em uma só linha. Role horizontalmente para revisá-lo antes de copiar.
Prefere uma cópia local? Baixe os arquivos disponíveis atualmente no SkillsMP.
Baixar Zip Baixando... Explorador de arquivos
2 arquivos Mais deste repositório langchain-deploy-integration Deploy a LangChain 1.0 / LangGraph 1.0 app to Cloud Run, Vercel, or LangServe correctly — with timeouts sized for chain length, cold-start mitigation, SSE anti-buffering headers, and Secret Manager over .env. Use when prepping a first production deploy, debugging a stream that hangs behind a proxy, or diagnosing p99 latency spikes. Trigger with "langchain deploy", "langchain cloud run", "langchain vercel python", "langchain langserve", or "langchain docker".
langchain-langgraph-agents Build a correct LangGraph 1.0 ReAct agent with create_react_agent — typed tools, error propagation, recursion caps, and stop conditions that actually stop. Use when writing a first tool-calling agent, migrating from AgentExecutor or initialize_agent, or diagnosing an agent that loops on vague prompts. Trigger with "langgraph agent", "create_react_agent", "langgraph tool calling", "AgentExecutor migration", or "agent loop cost".
langchain-langgraph-human-in-loop Build LangGraph 1.0 human-in-the-loop approval flows with interrupt_before /
interrupt_after and Command(resume=...) — JSON-serializable state, clean
resume semantics, and UI wiring for approval decisions. Use when adding an
approval gate before an expensive tool call, wiring a Slack/web UI for agent
approvals, or debugging a graph that crashes on interrupt.
Trigger with "langgraph human in loop", "langgraph interrupt_before",
"langgraph approval flow", "Command resume", "langgraph HITL".
name clerk-observability description 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".
allowed-tools Read, Write, Edit, Bash(npm:*), Grep version 1.14.0 license MIT author Jeremy Longshore <jeremy@intentsolutions.io> tags ["saas","clerk","monitoring","observability","debugging"] compatibility Designed for Claude Code
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
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 (),
})
}
( ) {
logger. ({
: ,
: error. ,
: error. ,
...context,
: (). (),
})
}
export
function
logAuthError
error : Error , context : { userId?: string ; path: string }
error
category
'auth'
error
message
stack
stack
timestamp
new
Date
toISOString
Step 2: Middleware Performance Monitoring
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 ()
if (duration > 100 ) {
console .warn (`[Auth Perf] ${req.nextUrl.pathname} took ${duration} ms` , {
userId : userId || 'anonymous' ,
method : req.method ,
})
}
const response = new Response (null , { status : 200 })
response.headers .set ('X-Auth-Duration' , `${duration} ms` )
})
Step 3: Webhook Event Tracking
import { logAuthEvent } from '@/lib/auth-logger'
async function handleWebhookEvent (evt : WebhookEvent ) {
const startTime = Date .now ()
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
if (metrics.processingTimeMs > 5000 ) {
console .error ('[Webhook] Slow processing:' , metrics)
}
return Response .json ({ received : true })
}
Step 4: Sentry Error Tracking Integration
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' )
}
}
export function withAuthSentry (handler : Function ) {
return async (...args : any []) => {
await initSentryUser ()
try {
return await handler (...args)
} catch (error) {
Sentry .captureException (error)
throw error
}
}
}
import * as Sentry from '@sentry/nextjs'
Sentry .init ({
dsn : process.env .SENTRY_DSN ,
tracesSampleRate : 0.1 ,
beforeSend (event ) {
if (event.extra ) {
delete event.extra ['CLERK_SECRET_KEY' ]
}
return event
},
})
Step 5: Health Check Endpoint
import { clerkClient } from '@clerk/nextjs/server'
export async function GET ( ) {
const checks : Record <string , { status : string ; latencyMs : number ; detail ?: string }> = {}
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 }
}
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
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
LOG_LEVEL=debug npm run dev 2>&1 | grep '"category":"auth"'
Resources
Next Steps Proceed to clerk-incident-runbook for incident response procedures.