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 via Svix webhooks. Trigger with phrases like "clerk webhooks", "clerk events", "clerk user sync", "clerk svix", "clerk event handling".

1,868 stars

Best use case

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

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

Teams using clerk-webhooks-events 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-webhooks-events/SKILL.md --create-dirs "https://raw.githubusercontent.com/jeremylongshore/claude-code-plugins-plus-skills/main/plugins/saas-packs/clerk-pack/skills/clerk-webhooks-events/SKILL.md"

Manual Installation

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

How clerk-webhooks-events Compares

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

Frequently Asked Questions

What does this skill do?

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

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 Webhooks & Events

## Overview
Configure and handle Clerk webhooks for user lifecycle events and data synchronization. Clerk uses Svix for webhook delivery with HMAC-SHA256 signature verification. As of 2025, Clerk provides a built-in `verifyWebhook()` helper in `@clerk/backend` alongside the manual Svix approach.

## Prerequisites
- Clerk account with webhook endpoint configured in Dashboard
- HTTPS endpoint (use `ngrok` for local dev)
- `CLERK_WEBHOOK_SECRET` environment variable (starts with `whsec_`)

## Instructions

### Step 1: Install Dependencies
```bash
# Option A: Use @clerk/backend's built-in verifyWebhook() (recommended)
# Already included with @clerk/nextjs — no extra install needed

# Option B: Manual Svix verification
npm install svix
```

### Step 2: Create Webhook Endpoint (verifyWebhook — Recommended)
```typescript
// app/api/webhooks/clerk/route.ts
import { verifyWebhook } from '@clerk/backend/webhooks'
import type { WebhookEvent } from '@clerk/nextjs/server'

export async function POST(req: Request) {
  let evt: WebhookEvent

  try {
    evt = await verifyWebhook(req)
  } catch (err) {
    console.error('Webhook verification failed:', err)
    return new Response('Invalid signature', { status: 400 })
  }

  return handleWebhookEvent(evt)
}
```

### Step 2 (Alternative): Manual Svix Verification
```typescript
// app/api/webhooks/clerk/route.ts
import { Webhook } from 'svix'
import { headers } from 'next/headers'
import type { 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('Missing CLERK_WEBHOOK_SECRET env variable')
  }

  const headerPayload = await headers()
  const svixHeaders = {
    'svix-id': headerPayload.get('svix-id') || '',
    'svix-timestamp': headerPayload.get('svix-timestamp') || '',
    'svix-signature': headerPayload.get('svix-signature') || '',
  }

  if (!svixHeaders['svix-id'] || !svixHeaders['svix-signature']) {
    return new Response('Missing svix headers', { status: 400 })
  }

  // CRITICAL: Use req.text(), NOT req.json() — JSON parsing alters the payload
  // and breaks signature verification
  const body = await req.text()
  const wh = new Webhook(WEBHOOK_SECRET)
  let evt: WebhookEvent

  try {
    evt = wh.verify(body, svixHeaders) as WebhookEvent
  } catch (err) {
    console.error('Webhook verification failed:', err)
    return new Response('Invalid signature', { status: 400 })
  }

  return handleWebhookEvent(evt)
}
```

### Step 3: Implement Event Handlers
```typescript
async function handleWebhookEvent(evt: WebhookEvent) {
  const eventType = evt.type

  switch (eventType) {
    case 'user.created': {
      const { id, email_addresses, first_name, last_name, image_url } = evt.data
      const primaryEmail = email_addresses.find(e => e.id === evt.data.primary_email_address_id)

      await db.user.create({
        data: {
          clerkId: id,
          email: primaryEmail?.email_address || email_addresses[0]?.email_address,
          firstName: first_name,
          lastName: last_name,
          avatarUrl: image_url,
        },
      })
      console.log(`[Webhook] User created: ${id}`)
      break
    }

    case 'user.updated': {
      const { id, email_addresses, first_name, last_name, image_url } = evt.data
      const primaryEmail = email_addresses.find(e => e.id === evt.data.primary_email_address_id)

      await db.user.upsert({
        where: { clerkId: id },
        update: {
          email: primaryEmail?.email_address,
          firstName: first_name,
          lastName: last_name,
          avatarUrl: image_url,
        },
        create: {
          clerkId: id,
          email: primaryEmail?.email_address || '',
          firstName: first_name,
          lastName: last_name,
          avatarUrl: image_url,
        },
      })
      break
    }

    case 'user.deleted': {
      if (evt.data.id) {
        // Soft-delete or hard-delete based on your data retention policy
        await db.user.update({
          where: { clerkId: evt.data.id },
          data: { deletedAt: new Date() },
        })
      }
      break
    }

    case 'organization.created': {
      const { id, name, slug, created_by } = evt.data
      await db.organization.create({
        data: { clerkOrgId: id, name, slug: slug || '', createdBy: created_by },
      })
      break
    }

    case 'organizationMembership.created': {
      const { organization, public_user_data, role } = evt.data
      await db.orgMembership.create({
        data: {
          orgId: organization.id,
          userId: public_user_data.user_id,
          role,
        },
      })
      break
    }

    case 'session.created':
      console.log(`[Webhook] Session created for user: ${evt.data.user_id}`)
      break

    default:
      console.log(`[Webhook] Unhandled event: ${eventType}`)
  }

  return new Response('OK', { status: 200 })
}
```

### Step 4: Idempotency Protection
```typescript
// lib/webhook-idempotency.ts
// Clerk/Svix may retry failed deliveries — prevent duplicate processing

export async function processIdempotently(
  svixId: string,
  eventType: string,
  handler: () => Promise<void>
): Promise<{ processed: boolean; duplicate: boolean }> {
  // Check if already processed (use your DB or Redis)
  const existing = await db.webhookEvent.findUnique({
    where: { svixId },
  })

  if (existing) {
    console.log(`[Webhook] Duplicate event skipped: ${svixId} (${eventType})`)
    return { processed: false, duplicate: true }
  }

  // Mark as processing (before handler, to catch concurrent deliveries)
  await db.webhookEvent.create({
    data: { svixId, eventType, status: 'processing', receivedAt: new Date() },
  })

  try {
    await handler()
    await db.webhookEvent.update({
      where: { svixId },
      data: { status: 'completed', processedAt: new Date() },
    })
    return { processed: true, duplicate: false }
  } catch (error) {
    await db.webhookEvent.update({
      where: { svixId },
      data: { status: 'failed', error: String(error) },
    })
    throw error
  }
}
```

### Step 5: Configure Webhook in Clerk Dashboard
1. Navigate to **Clerk Dashboard > Webhooks > Add Endpoint**
2. Set endpoint URL: `https://yourdomain.com/api/webhooks/clerk`
3. Select events to subscribe to:
   - **User events:** `user.created`, `user.updated`, `user.deleted`
   - **Org events:** `organization.created`, `organizationMembership.created`
   - **Session events:** `session.created`, `session.ended` (optional, high volume)
4. Copy the **Signing Secret** (`whsec_...`) to your `.env.local`:
```bash
CLERK_WEBHOOK_SECRET=whsec_...
```

### Step 6: Express.js Webhook Endpoint
```typescript
import express from 'express'
import { Webhook } from 'svix'

const app = express()

// CRITICAL: Use express.raw(), NOT express.json() for webhook routes
app.post('/api/webhooks/clerk',
  express.raw({ type: 'application/json' }),
  (req, res) => {
    const wh = new Webhook(process.env.CLERK_WEBHOOK_SECRET!)
    try {
      const evt = wh.verify(req.body, {
        'svix-id': req.headers['svix-id'] as string,
        'svix-timestamp': req.headers['svix-timestamp'] as string,
        'svix-signature': req.headers['svix-signature'] as string,
      })
      // Handle event...
      res.status(200).json({ received: true })
    } catch (err) {
      console.error('Webhook verification failed:', err)
      res.status(400).json({ error: 'Invalid signature' })
    }
  }
)
```

### Local Development with ngrok
```bash
# Start ngrok tunnel for local webhook testing
ngrok http 3000

# Copy the https://xxx.ngrok-free.app URL
# Add it as webhook endpoint in Clerk Dashboard > Webhooks
# URL: https://xxx.ngrok-free.app/api/webhooks/clerk
```

## Error Handling
| Error | Cause | Solution |
|-------|-------|----------|
| Invalid signature | Wrong `CLERK_WEBHOOK_SECRET` | Re-copy signing secret from Dashboard > Webhooks |
| Invalid signature | Body parsed with `json()` before verify | Use `req.text()` (Next.js) or `express.raw()` (Express) |
| Missing svix headers | Request not from Clerk/Svix | Verify endpoint URL; check sender |
| Duplicate processing | Clerk retried delivery | Implement idempotency with `svix-id` as unique key |
| Handler timeout | Slow DB operations | Offload heavy work to a background job queue |
| 404 on webhook URL | Route not matching | Ensure `/api/webhooks` is in middleware's `isPublicRoute` |

## Enterprise Considerations
- Treat `CLERK_WEBHOOK_SECRET` like a password -- rotate it if compromised (Dashboard > Webhooks > Signing Secret > Rotate)
- Svix headers include `svix-timestamp` for replay attack protection (rejects events older than 5 minutes by default)
- For high-volume apps, offload webhook processing to a queue (BullMQ, Inngest, Trigger.dev) and return 200 immediately
- Monitor webhook delivery in Dashboard > Webhooks > Message Logs -- failed messages auto-retry with exponential backoff
- Use `verifyWebhook()` from `@clerk/backend/webhooks` when possible -- it handles header extraction and secret key resolution automatically

## Resources
- [Webhooks Overview](https://clerk.com/docs/guides/development/webhooks/overview)
- [verifyWebhook() Reference](https://clerk.com/docs/reference/backend/verify-webhook)
- [Sync Data with Webhooks](https://clerk.com/docs/webhooks/sync-data)
- [Debug Webhooks](https://clerk.com/docs/guides/development/webhooks/debugging)

## Next Steps
Proceed to `clerk-performance-tuning` for optimization strategies.

Related Skills

workhuman-webhooks-events

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

Workhuman webhooks events for employee recognition and rewards API. Use when integrating Workhuman Social Recognition, or building recognition workflows with HRIS systems. Trigger: "workhuman webhooks events".

wispr-webhooks-events

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

Wispr Flow webhooks events for voice-to-text API integration. Use when integrating Wispr Flow dictation, WebSocket streaming, or building voice-powered applications. Trigger: "wispr webhooks events".

windsurf-webhooks-events

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

Build Windsurf extensions and integrate with VS Code extension API events. Use when building custom Windsurf extensions, tracking editor events, or integrating Windsurf with external tools via extension development. Trigger with phrases like "windsurf extension", "windsurf events", "windsurf plugin", "build windsurf extension", "windsurf API".

webflow-webhooks-events

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

Implement Webflow webhook registration, signature verification, and event handling for form_submission, site_publish, ecomm_new_order, page_created, and more. Use when setting up webhook endpoints, implementing event-driven workflows, or handling Webflow notifications. Trigger with phrases like "webflow webhook", "webflow events", "webflow webhook signature", "handle webflow events", "webflow notifications".

vercel-webhooks-events

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

Implement Vercel webhook handling with signature verification and event processing. Use when setting up webhook endpoints, processing deployment events, or building integrations that react to Vercel deployment lifecycle. Trigger with phrases like "vercel webhook", "vercel events", "vercel deployment.ready", "handle vercel events", "vercel webhook signature".

veeva-webhooks-events

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

Veeva Vault webhooks events for REST API and clinical operations. Use when working with Veeva Vault document management and CRM. Trigger: "veeva webhooks events".

vastai-webhooks-events

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

Build event-driven workflows around Vast.ai instance lifecycle events. Use when monitoring instance status changes, implementing auto-recovery, or building event-driven GPU orchestration. Trigger with phrases like "vastai events", "vastai instance monitoring", "vastai status changes", "vastai lifecycle events".

twinmind-webhooks-events

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

Handle TwinMind meeting events including transcription completion, action item extraction, and calendar sync notifications. Use when implementing webhooks events, or managing TwinMind meeting AI operations. Trigger with phrases like "twinmind webhooks events", "twinmind webhooks events".

together-webhooks-events

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

Together AI webhooks events for inference, fine-tuning, and model deployment. Use when working with Together AI's OpenAI-compatible API. Trigger: "together webhooks events".

techsmith-webhooks-events

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

TechSmith webhooks events for Snagit COM API and Camtasia automation. Use when working with TechSmith screen capture and video editing automation. Trigger: "techsmith webhooks events".

supabase-webhooks-events

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

Implement Supabase database webhooks, pg_net async HTTP, LISTEN/NOTIFY, and Edge Function event handlers with signature verification. Use when setting up database webhooks for INSERT/UPDATE/DELETE events, sending HTTP requests from PostgreSQL triggers, handling Realtime postgres_changes as an event source, or building event-driven architectures. Trigger with phrases like "supabase webhook", "database events", "pg_net trigger", "supabase LISTEN NOTIFY", "webhook signature verify", "supabase event-driven", "supabase_functions.http_request".

stackblitz-webhooks-events

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

WebContainer lifecycle events: server-ready, port changes, error handling. Use when working with WebContainers or StackBlitz SDK. Trigger: "webcontainer events".