Skip to content
clerk-webhooks-events logo

Clerk Webhooks & Events

clerk-webhooks-events

Configure Clerk webhooks and handle authentication events. Use when setting up user sync, handling auth events, or integrating Clerk with external systems. Trigger with phrases like "clerk webhooks", "clerk events", "clerk user sync", "clerk notifications", "clerk event handling".

SKILL.md

Full skill instructions

Clerk Webhooks & Events

Overview

Configure and handle Clerk webhooks for user lifecycle events and data synchronization.

Prerequisites

  • Clerk account with webhook access
  • HTTPS endpoint for webhooks
  • svix package for verification

Instructions

Step 1: Install Dependencies

npm install svix

Step 2: Create Webhook Endpoint

// app/​api/​webhooks/​clerk/​route.ts
import { Webhook } from 'svix'
import { headers } from 'next/​headers'
import { WebhookEvent } from '@clerk/​nextjs/​server'

export async function POST(req: Request) {
  const WEBHOOK_SECRET = process.env.CLERK_WEBHOOK_SECRET

  if (!WEBHOOK_SECRET) {
    throw new Error('CLERK_WEBHOOK_SECRET not set')
  }

  // Get Svix headers
  const headerPayload = await headers()
  const svix_id = headerPayload.get('svix-id')
  const svix_timestamp = headerPayload.get('svix-timestamp')
  const svix_signature = headerPayload.get('svix-signature')

  if (!svix_id || !svix_timestamp || !svix_signature) {
    return Response.json({ error: 'Missing headers' }, { status: 400 })
  }

  // Get body
  const payload = await req.json()
  const body = JSON.stringify(payload)

  // Verify webhook
  const wh = new Webhook(WEBHOOK_SECRET)
  let evt: WebhookEvent

  try {
    evt = wh.verify(body, {
      'svix-id': svix_id,
      'svix-timestamp': svix_timestamp,
      'svix-signature': svix_signature,
    }) as WebhookEvent
  } catch (err) {
    console.error('Webhook verification failed:', err)
    return Response.json({ error: 'Invalid signature' }, { status: 400 })
  }

  // Handle event
  const eventType = evt.type
  console.log(`Received webhook: ${eventType}`)

  switch (eventType) {
    case 'user.created':
      await handleUserCreated(evt.data)
      break
    case 'user.updated':
      await handleUserUpdated(evt.data)
      break
    case 'user.deleted':
      await handleUserDeleted(evt.data)
      break
    case 'session.created':
      await handleSessionCreated(evt.data)
      break
    case 'organization.created':
      await handleOrgCreated(evt.data)
      break
    default:
      console.log(`Unhandled event type: ${eventType}`)
  }

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

Step 3: Implement Event Handlers

// lib/​webhook-handlers.ts
import { db } from './​db'

interface ClerkUserData {
  id: string
  email_addresses: Array<{ email_address: string; id: string }>
  first_name: string | null
  last_name: string | null
  image_url: string
  created_at: number
  updated_at: number
}

export async function handleUserCreated(data: ClerkUserData) {
  const primaryEmail = data.email_addresses.find(
    e => e.id === data.primary_email_address_id
  )?.email_address

  await db.user.create({
    data: {
      clerkId: data.id,
      email: primaryEmail,
      firstName: data.first_name,
      lastName: data.last_name,
      imageUrl: data.image_url,
      createdAt: new Date(data.created_at)
    }
  })

  // Send welcome email
  await sendWelcomeEmail(primaryEmail)

  console.log(`User created: ${data.id}`)
}

export async function handleUserUpdated(data: ClerkUserData) {
  const primaryEmail = data.email_addresses.find(
    e => e.id === data.primary_email_address_id
  )?.email_address

  await db.user.update({
    where: { clerkId: data.id },
    data: {
      email: primaryEmail,
      firstName: data.first_name,
      lastName: data.last_name,
      imageUrl: data.image_url,
      updatedAt: new Date(data.updated_at)
    }
  })

  console.log(`User updated: ${data.id}`)
}

export async function handleUserDeleted(data: { id: string }) {
  await db.user.delete({
    where: { clerkId: data.id }
  })

  // Clean up user data
  await cleanupUserData(data.id)

  console.log(`User deleted: ${data.id}`)
}

export async function handleSessionCreated(data: any) {
  // Log session for analytics
  await db.sessionLog.create({
    data: {
      userId: data.user_id,
      sessionId: data.id,
      createdAt: new Date(data.created_at),
      userAgent: data.user_agent
    }
  })

  console.log(`Session created: ${data.id}`)
}

export async function handleOrgCreated(data: any) {
  await db.organization.create({
    data: {
      clerkOrgId: data.id,
      name: data.name,
      slug: data.slug,
      createdAt: new Date(data.created_at)
    }
  })

  console.log(`Organization created: ${data.id}`)
}

Step 4: Idempotency and Error Handling

// lib/​webhook-idempotency.ts
import { Redis } from '@upstash/​redis'

const redis = Redis.fromEnv()

export async function processWithIdempotency(
  eventId: string,
  handler: () => Promise<void>
) {
  const key = `webhook:${eventId}`

  // Check if already processed
  const processed = await redis.get(key)
  if (processed) {
    console.log(`Event ${eventId} already processed`)
    return { skipped: true }
  }

  try {
    await handler()

    // Mark as processed (expire after 24 hours)
    await redis.set(key, 'processed', { ex: 86400 })

    return { success: true }
  } catch (error) {
    // Log error but don't mark as processed
    console.error(`Failed to process ${eventId}:`, error)
    throw error
  }
}

// Usage in webhook handler
export async function POST(req: Request) {
  // ... verification code ...

  const svix_id = headerPayload.get('svix-id')!

  const result = await processWithIdempotency(svix_id, async () => {
    switch (evt.type) {
      case 'user.created':
        await handleUserCreated(evt.data)
        break
      // ... other handlers
    }
  })

  return Response.json(result)
}

Step 5: Configure Webhook in Clerk Dashboard

  1. Go to Clerk Dashboard > Webhooks
  2. Add endpoint URL: https://yourdomain.com/​api/​webhooks/​clerk
  3. Select events:
    • user.created
    • user.updated
    • user.deleted
    • session.created
    • session.ended
    • organization.* (if using organizations)
  4. Copy webhook secret to environment

Available Events

EventDescription
user.createdNew user signed up
user.updatedUser profile changed
user.deletedUser account deleted
session.createdNew session started
session.endedSession terminated
session.revokedSession manually revoked
organization.createdOrg created
organization.updatedOrg settings changed
organization.deletedOrg deleted
organizationMembership.*Member added/​removed
email.createdEmail verification sent

Output

  • Webhook endpoint configured
  • Event handlers implemented
  • Idempotency protection
  • User data sync working

Testing Webhooks Locally

# Use ngrok for local testing
npx ngrok http 3000

# Or use Clerk CLI
npx @clerk/​cli dev

# Test with curl
curl -X POST http://localhost:3000/​api/​webhooks/​clerk \
  -H "Content-Type: application/​json" \
  -H "svix-id: test" \
  -H "svix-timestamp: $(date +%s)" \
  -H "svix-signature: v1,..." \
  -d '{"type":"user.created","data":{}}'

Error Handling

ErrorCauseSolution
Invalid signatureWrong secretVerify CLERK_WEBHOOK_SECRET
Missing headersRequest not from ClerkCheck sender is Clerk
Duplicate processingEvent sent twiceImplement idempotency
TimeoutHandler too slowUse background jobs

Resources

Next Steps

Proceed to clerk-performance-tuning for optimization strategies.

More skills from Dicklesworthstone

environment-setup-guide logo
Dicklesworthstone/pi_agent_rust

environment-setup-guide

Guide developers through setting up development environments with proper tools, dependencies, and configurations

1.8K 0
View
exa-policy-guardrails logo
Dicklesworthstone/pi_agent_rust

exa-policy-guardrails

Implement Exa lint rules, policy enforcement, and automated guardrails. Use when setting up code quality rules for Exa integrations, implementing pre-commit hooks, or configuring CI policy checks for Exa best practices. Trigger with phrases like "exa policy", "exa lint", "exa guardrails", "exa be...

1.8K 0
View
documenso-ci-integration logo
Dicklesworthstone/pi_agent_rust

documenso-ci-integration

Configure CI/CD pipelines for Documenso integrations. Use when setting up automated testing, deployment pipelines, or continuous integration for Documenso projects. Trigger with phrases like "documenso CI", "documenso GitHub Actions", "documenso pipeline", "documenso automated testing".

1.8K 0
View
openrouter-model-availability logo
Dicklesworthstone/pi_agent_rust

openrouter-model-availability

Build check model availability and implement fallback chains. Use when building resilient systems or handling model outages. Trigger with phrases like 'openrouter availability', 'openrouter fallback', 'openrouter model down', 'openrouter health check'.

1.8K 0
View
langfuse-enterprise-rbac logo
Dicklesworthstone/pi_agent_rust

langfuse-enterprise-rbac

Configure Langfuse enterprise organization management and access control. Use when implementing team access controls, configuring organization settings, or setting up role-based permissions for Langfuse projects. Trigger with phrases like "langfuse RBAC", "langfuse teams", "langfuse organization"...

1.8K 0
View
cursor-compliance-audit logo
Dicklesworthstone/pi_agent_rust

cursor-compliance-audit

Execute compliance and security auditing for Cursor usage. Triggers on "cursor compliance", "cursor audit", "cursor security review", "cursor soc2", "cursor gdpr". Use when analyzing or auditing cursor compliance audit. Trigger with phrases like "cursor compliance audit", "cursor audit", "cursor".

1.8K 0
View
apollo-ci-integration logo
Dicklesworthstone/pi_agent_rust

apollo-ci-integration

Configure Apollo.io CI/CD integration. Use when setting up automated testing, continuous integration, or deployment pipelines for Apollo integrations. Trigger with phrases like "apollo ci", "apollo github actions", "apollo pipeline", "apollo ci/cd", "apollo automated tests".

1.8K 0
View
python-script logo
Dicklesworthstone/pi_agent_rust

python-script

Create robust Python automation with full logging and safety checks. Use when tasks need complex data processing, authenticated API work, conditional file operations, or error handling beyond simple shell commands.

1.8K 0
View
posthog-multi-env-setup logo
Dicklesworthstone/pi_agent_rust

posthog-multi-env-setup

Configure PostHog across development, staging, and production environments. Use when setting up multi-environment deployments, configuring per-environment secrets, or implementing environment-specific PostHog configurations. Trigger with phrases like "posthog environments", "posthog staging", "po...

1.8K 0
View
ai-agents-architect logo
Dicklesworthstone/pi_agent_rust

ai-agents-architect

Expert in designing and building autonomous AI agents. Masters tool use, memory systems, planning strategies, and multi-agent orchestration. Use when: build agent, AI agent, autonomous agent, tool use, function calling.

1.8K 0
View
insecure-deserialization-checker logo
Dicklesworthstone/pi_agent_rust

insecure-deserialization-checker

Validate insecure deserialization checker operations. Auto-activating skill for Security Fundamentals. Triggers on: insecure deserialization checker, insecure deserialization checker Part of the Security Fundamentals skill category. Use when working with insecure deserialization checker functiona...

1.8K 0
View
path-traversal-finder logo
Dicklesworthstone/pi_agent_rust

path-traversal-finder

Manage path traversal finder operations. Auto-activating skill for Security Fundamentals. Triggers on: path traversal finder, path traversal finder Part of the Security Fundamentals skill category. Use when working with path traversal finder functionality. Trigger with phrases like "path traversa...

1.8K 0
View

Popular AI tools

Kaiber logo
Video

Kaiber

Generate, edit, and beat-sync AI video with leading models in one workspace.

Paid
View
Vimcal logo
Productivity

Vimcal

The world's fastest calendar for remote work

Free
View

Transform Your Design with AI Designer by ImgCreator.ai

Freemium
View
Akool AI logo
Content & writing

Akool AI

Revolutionizing Video Production with AI-Powered Creativity

Paid
View

Extend an image past the frame and let AI fill the new aspect ratio.

Freemium
View
StarByFace logo
Security

StarByFace

Discover your celebrity doppelgänger with StarByFace!

Free
View
C

ChainClarity explains 700+ crypto whitepapers in plain English, with layered summaries, comparisons, research tools, alerts, and a $4.99 Pro plan.

Freemium
View
Opus Clip logo
Coding & apps

Opus Clip

Opus.ai: Revolutionize Your Web Experience

Free
View