[{"data":1,"prerenderedAt":-1},["ShallowReactive",2],{"skill:01M7AZ6NMDJVSZ4E6H99VFX2GD":3,"skill-same:01M7AZ6NMDJVSZ4E6H99VFX2GD":60},{"skillNo":4,"name":5,"nameZh":6,"description":7,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":16,"categories":17,"keywords":18,"publishedAt":19,"linkOnly":20,"markdownContent":21,"markdownBody":22,"frontMatter":23,"refName":29,"commitSha":30,"skillDirectory":31,"forksCount":14,"repositoryHtmlUrl":32,"repositoryHomepageUrl":6,"ownerHtmlUrl":33,"ownerBlogUrl":6,"ownerDescription":34,"updatedAt":35,"install":36,"resources":49},"01M7AZ6NMDJVSZ4E6H99VFX2GD","clerk-webhooks",null,"Clerk webhooks for real-time events and data syncing. Verify with verifyWebhook from the framework-specific package. Handle user, session, organization, billing, and payment events. Build event-driven features like database sync, notifications, and integrations.","dbillion\u002Fhermes-skills-public","dbillion","https:\u002F\u002Favatars.githubusercontent.com\u002Fu\u002F49393855?v=4","01M7AVH8QPGCM8WKWS22TRT0T6","Oludayo Adeoye","01M7AVH8RD1JJWA0YS9CFEWAV9",0,"MIT","https:\u002F\u002Fgithub.com\u002Fdbillion\u002Fhermes-skills-public\u002Fblob\u002Fmaster\u002Fskills\u002Fclerk-webhooks\u002FSKILL.md",[],[],"2026-11-15 14:19:17",false,"---\nname: clerk-webhooks\ndescription: Clerk webhooks for real-time events and data syncing. Verify with verifyWebhook\n  from the framework-specific package. Handle user, session, organization, billing, and\n  payment events. Build event-driven features like database sync, notifications, and\n  integrations.\nallowed-tools: WebFetch\nlicense: MIT\nmetadata:\n  author: clerk\n  version: 1.2.0\ncompatibility: Requires CLERK_WEBHOOK_SIGNING_SECRET (svix signing secret from Clerk dashboard)\n---\n\n# Webhooks\n\nOutput complete, working webhook handlers with `verifyWebhook(req)` verification in every handler.\n\n## When to Use Webhooks\n\nWebhooks are **asynchronous and eventually consistent**. Delivery is fast but not guaranteed to be immediate, and may occasionally fail (Svix retries on a fixed schedule). Use them for:\n\n- Database sync (a separate users \u002F orgs table that follows Clerk)\n- Notifications (welcome emails, Slack pings, internal alerts)\n- Integrations triggered by lifecycle events\n\nDo NOT rely on webhook delivery as part of a synchronous flow such as onboarding (\"user signs up, then we read X from our DB\"). For data the user just created, read it from the [Clerk session token](https:\u002F\u002Fclerk.com\u002Fdocs\u002Fguides\u002Fsessions\u002Fsession-tokens) or call the Backend API directly. Webhooks fill the gap when you need data about *other* users or events the session token doesn't carry.\n\n## Verify Every Webhook\n\nUse `verifyWebhook(req)` from the framework-specific package (`@clerk\u002Fnextjs\u002Fwebhooks`, `@clerk\u002Fexpress\u002Fwebhooks`, etc.). It reads `CLERK_WEBHOOK_SIGNING_SECRET` automatically and throws on bad signatures. Skipping verification, even for notification-only handlers, exposes the endpoint to spoofed events.\n\n## Make the Webhook Route Public\n\nWebhook routes must be excluded from Clerk middleware protection. Without this, Clerk returns 401.\n\n```typescript\n\u002F\u002F proxy.ts (Next.js \u003C=15: middleware.ts)\nimport { clerkMiddleware, createRouteMatcher } from '@clerk\u002Fnextjs\u002Fserver'\n\nconst isPublicRoute = createRouteMatcher(['\u002Fapi\u002Fwebhooks(.*)'])\n\nexport default clerkMiddleware(async (auth, req) => {\n  if (!isPublicRoute(req)) await auth.protect()\n})\n```\n\n## Complete Webhook Handler (Next.js App Router)\n\n```typescript\n\u002F\u002F app\u002Fapi\u002Fwebhooks\u002Froute.ts\nimport { verifyWebhook } from '@clerk\u002Fnextjs\u002Fwebhooks'\nimport { NextRequest } from 'next\u002Fserver'\nimport { db } from '@\u002Flib\u002Fdb'\n\nexport async function POST(req: NextRequest) {\n  \u002F\u002F ALWAYS verify - never skip, even for notification-only handlers\n  let evt\n  try {\n    evt = await verifyWebhook(req) \u002F\u002F uses CLERK_WEBHOOK_SIGNING_SECRET automatically\n  } catch (err) {\n    console.error('Webhook verification failed:', err)\n    return new Response('Verification failed', { status: 400 })\n  }\n\n  if (evt.type === 'user.created') {\n    const { id, email_addresses, first_name, last_name } = evt.data\n    const email = email_addresses[0]?.email_address\n    const name = `${first_name ?? ''} ${last_name ?? ''}`.trim()\n    await db.users.create({ data: { clerkId: id, email, name } })\n  }\n\n  if (evt.type === 'user.updated') {\n    const { id, email_addresses, first_name, last_name } = evt.data\n    const email = email_addresses[0]?.email_address\n    await db.users.update({ where: { clerkId: id }, data: { email, first_name, last_name } })\n  }\n\n  if (evt.type === 'user.deleted') {\n    const { id } = evt.data\n    await db.users.delete({ where: { clerkId: id } })\n  }\n\n  if (evt.type === 'organizationMembership.created') {\n    const { organization, public_user_data, role } = evt.data\n    const orgId = organization.id\n    const userId = public_user_data.user_id\n    await db.teamMembers.create({ data: { orgId, userId, role } })\n  }\n\n  if (evt.type === 'organizationMembership.deleted') {\n    const { organization, public_user_data } = evt.data\n    const orgId = organization.id\n    const userId = public_user_data.user_id\n    await db.teamMembers.delete({ where: { orgId_userId: { orgId, userId } } })\n  }\n\n  return new Response('OK', { status: 200 })\n}\n```\n\n## Full Example: Welcome Email (Resend) + Slack Notification on user.created\n\nNotification-only handlers still verify the signature. Same pattern as the database-sync handler:\n\n```typescript\n\u002F\u002F app\u002Fapi\u002Fwebhooks\u002Froute.ts\nimport { verifyWebhook } from '@clerk\u002Fnextjs\u002Fwebhooks'\nimport { NextRequest } from 'next\u002Fserver'\nimport { Resend } from 'resend'\n\nconst resend = new Resend(process.env.RESEND_API_KEY)\n\nexport async function POST(req: NextRequest) {\n  \u002F\u002F Step 1: ALWAYS verify the webhook signature - NEVER skip this\n  let evt\n  try {\n    evt = await verifyWebhook(req) \u002F\u002F uses CLERK_WEBHOOK_SIGNING_SECRET env var\n  } catch (err) {\n    console.error('Webhook verification failed:', err)\n    return new Response('Verification failed', { status: 400 })\n  }\n\n  \u002F\u002F Step 2: Listen for user.created event\n  if (evt.type === 'user.created') {\n    \u002F\u002F Step 3: Extract user email and name from webhook payload\n    const { id, email_addresses, first_name, last_name } = evt.data\n    const email = email_addresses[0]?.email_address\n    const name = `${first_name ?? ''} ${last_name ?? ''}`.trim()\n\n    \u002F\u002F Step 4: Call Resend API to send welcome email\n    await resend.emails.send({\n      from: 'noreply@yourdomain.com',\n      to: email,\n      subject: 'Welcome!',\n      html: `\u003Cp>Hi ${name}, welcome to our app!\u003C\u002Fp>`,\n    })\n\n    \u002F\u002F Step 5: Post notification to Slack channel\n    await fetch(process.env.SLACK_WEBHOOK_URL!, {\n      method: 'POST',\n      headers: { 'Content-Type': 'application\u002Fjson' },\n      body: JSON.stringify({\n        text: `New user signed up: ${name} (${email})`,\n      }),\n    })\n  }\n\n  \u002F\u002F Always return 200 to acknowledge receipt\n  return new Response('OK', { status: 200 })\n}\n```\n\n**Also include proxy.ts (Next.js \u003C=15: middleware.ts) to make the route public:**\n```typescript\n\u002F\u002F proxy.ts (Next.js \u003C=15: middleware.ts)\nimport { clerkMiddleware, createRouteMatcher } from '@clerk\u002Fnextjs\u002Fserver'\nconst isPublicRoute = createRouteMatcher(['\u002Fapi\u002Fwebhooks(.*)'])\nexport default clerkMiddleware(async (auth, req) => {\n  if (!isPublicRoute(req)) await auth.protect()\n})\n```\n\n## Full Example: Organization Membership Sync to Database\n\n```typescript\n\u002F\u002F app\u002Fapi\u002Fwebhooks\u002Froute.ts\nimport { verifyWebhook } from '@clerk\u002Fnextjs\u002Fwebhooks'\nimport { NextRequest } from 'next\u002Fserver'\nimport { db } from '@\u002Flib\u002Fdb' \u002F\u002F your database client\n\nexport async function POST(req: NextRequest) {\n  \u002F\u002F ALWAYS verify signature - never skip, even for simple handlers\n  let evt\n  try {\n    evt = await verifyWebhook(req) \u002F\u002F uses CLERK_WEBHOOK_SIGNING_SECRET env var\n  } catch (err) {\n    console.error('Webhook verification failed:', err)\n    return new Response('Verification failed', { status: 400 })\n  }\n\n  if (evt.type === 'organization.created') {\n    const { id, name } = evt.data\n    await db.workspaces.create({\n      data: { orgId: id, name, createdAt: new Date() },\n    })\n  }\n\n  if (evt.type === 'organizationMembership.created') {\n    \u002F\u002F Extract organization ID, user ID, and role from payload\n    const { organization, public_user_data, role } = evt.data\n    const orgId = organization.id\n    const userId = public_user_data.user_id\n\n    \u002F\u002F Add to team_members table\n    await db.team_members.create({\n      data: { orgId, userId, role },\n    })\n\n    \u002F\u002F Create workspace record for new member\n    await db.workspaces.create({\n      data: { orgId, userId, createdAt: new Date() },\n    })\n  }\n\n  if (evt.type === 'organizationMembership.deleted') {\n    \u002F\u002F Extract organization ID and user ID from payload\n    const { organization, public_user_data } = evt.data\n    const orgId = organization.id\n    const userId = public_user_data.user_id\n\n    \u002F\u002F Remove from team_members table\n    await db.team_members.delete({\n      where: { orgId, userId },\n    })\n\n    \u002F\u002F Remove workspace record\n    await db.workspaces.deleteMany({\n      where: { orgId, userId },\n    })\n  }\n\n  \u002F\u002F Return 200 status on success\n  return new Response('OK', { status: 200 })\n}\n```\n\n## Other Frameworks\n\nFor Express, Astro, Fastify, Nuxt, React Router, and TanStack Start, use the framework-specific `verifyWebhook` adapter. Each Clerk SDK package ships its own (`@clerk\u002Fexpress\u002Fwebhooks`, `@clerk\u002Fastro\u002Fwebhooks`, `@clerk\u002Ffastify\u002Fwebhooks`, etc.).\n\nSee `references\u002Fframeworks.md` for full handler examples per framework.\n\n## Type Narrowing for `evt.data`\n\n`verifyWebhook` returns `WebhookEvent`, a discriminated union of all event types. Narrow with `evt.type` to get type-safe access to `evt.data`:\n\n```typescript\nconst evt = await verifyWebhook(req)\n\nif (evt.type === 'user.created') {\n  \u002F\u002F evt.data is now UserJSON, autocompletes id, email_addresses, etc.\n  console.log(evt.data.id)\n}\n```\n\nFor manual typing of nested payloads, import the JSON types from your framework's webhook subpath: `DeletedObjectJSON`, `EmailJSON`, `OrganizationInvitationJSON`, `OrganizationJSON`, `OrganizationMembershipJSON`, `SessionJSON`, `SMSMessageJSON`, `UserJSON`.\n\n## Payload Field Reference\n\n### User events (`user.created`, `user.updated`, `user.deleted`)\n```typescript\nconst {\n  id,                  \u002F\u002F Clerk user ID\n  email_addresses,     \u002F\u002F array; [0].email_address is primary email\n  first_name,\n  last_name,\n  image_url,\n  public_metadata,\n} = evt.data\n```\n\n### Organization events (`organization.created`, `organization.updated`, `organization.deleted`)\n```typescript\nconst {\n  id,    \u002F\u002F org ID\n  name,  \u002F\u002F org name\n  slug,\n} = evt.data\n```\n\n### Organization Membership events (`organizationMembership.created`, `organizationMembership.updated`, `organizationMembership.deleted`)\n```typescript\nconst {\n  organization,        \u002F\u002F { id, name, ... }\n  public_user_data,    \u002F\u002F { user_id, first_name, last_name, ... }\n  role,                \u002F\u002F e.g. 'org:admin', 'org:member'\n} = evt.data\n\u002F\u002F Access: organization.id, public_user_data.user_id, role\n```\n\n## Supported Events (Full Catalog)\n\n**User**: `user.created` `user.updated` `user.deleted`\n\n**Session**: `session.created` `session.ended` `session.removed` `session.revoked`\n\n**Organization**: `organization.created` `organization.updated` `organization.deleted`\n\n**Organization Membership**: `organizationMembership.created` `organizationMembership.updated` `organizationMembership.deleted`\n\n**Organization Domain**: `organizationDomain.created` `organizationDomain.updated` `organizationDomain.deleted`\n\n**Organization Invitation**: `organizationInvitation.accepted` `organizationInvitation.created` `organizationInvitation.revoked`\n\n**Communication**: `email.created` `sms.created`\n\n**Waitlist**: `waitlistEntry.created` `waitlistEntry.updated`\n\n**Permission**: `permission.created` `permission.updated` `permission.deleted`\n\n**Role**: `role.created` `role.updated` `role.deleted`\n\n**Subscription**: `subscription.created` `subscription.updated` `subscription.active` `subscription.pastDue`\n\n**Subscription Item**: `subscriptionItem.created` `subscriptionItem.active` `subscriptionItem.updated` `subscriptionItem.canceled` `subscriptionItem.upcoming` `subscriptionItem.ended` `subscriptionItem.abandoned` `subscriptionItem.incomplete` `subscriptionItem.pastDue` `subscriptionItem.freeTrialEnding`\n\n**Payment**: `paymentAttempt.created` `paymentAttempt.updated`\n\n## Webhook Reliability\n\n**Retries**: Svix retries failed webhooks on a set schedule (see [Svix Retry Schedule](https:\u002F\u002Fdocs.svix.com\u002Fretries)). Return 2xx to succeed, 4xx\u002F5xx to retry. Use the `svix-id` header as an idempotency key to deduplicate retried events.\n\n**Replay**: Failed webhooks can be replayed from Dashboard.\n\n## Common Pitfalls\n\n| Symptom | Cause | Fix |\n|---------|-------|-----|\n| Verification fails (Next.js) | Wrong import or usage | Use `@clerk\u002Fnextjs\u002Fwebhooks`, pass `req` directly |\n| Verification fails (Express) | Using `express.json()` | Use `express.raw({ type: 'application\u002Fjson' })` for webhook route |\n| Route not found (404) | Wrong path | Use `\u002Fapi\u002Fwebhooks` or preserve existing path |\n| Not authorized (401) | Route is protected by middleware | Make route public in `clerkMiddleware()` |\n| No data in DB | Async job pending | Wait\u002Fcheck logs |\n| Duplicate entries | Only handling `user.created` | Also handle `user.updated` |\n| Timeouts | Handler too slow | Queue async work, return 200 first |\n\n## Testing & Deployment\n\n**Local**: Use the Clerk CLI's first-party tunnel — no auth or linked project needed:\n\n```sh\nclerk webhooks listen --token \"$(clerk webhooks token)\" --forward-to http:\u002F\u002Flocalhost:3000\u002Fapi\u002Fwebhooks\n```\n\nAdd the printed relay URL (`https:\u002F\u002Fwebhooks.clerk.com\u002Fin\u002Fc_...\u002F`) as a webhook endpoint in the Dashboard — events don't flow until you do. `svix-*` headers are preserved, so `verifyWebhook()` works against that endpoint's signing secret as usual. Flags, offline signature checks (`clerk webhooks verify`), and agent-mode behavior are in the `clerk-cli` skill. Without the CLI, tunnel `localhost:3000` yourself (`ngrok`, `localtunnel`, `Cloudflare Tunnel`) and add the public URL to the Dashboard endpoint.\n\n**Production**: Update webhook endpoint URL to production domain. Copy `CLERK_WEBHOOK_SIGNING_SECRET` to production env vars.\n\n## References\n\n| Reference | Description |\n|-----------|-------------|\n| `references\u002Fframeworks.md` | Webhook handler examples for Express, Astro, Fastify, Nuxt, React Router, TanStack Start |\n\n## See Also\n\n- `clerk-cli` - `clerk webhooks listen`\u002F`verify` for local webhook testing\n- `clerk-setup` - Initial Clerk install\n- `clerk-orgs` - Org membership events\n- `clerk-billing` - Subscription, subscription item, and payment attempt events\n- `clerk-backend-api` - Sync via direct API calls","# Webhooks\n\nOutput complete, working webhook handlers with `verifyWebhook(req)` verification in every handler.\n\n## When to Use Webhooks\n\nWebhooks are **asynchronous and eventually consistent**. Delivery is fast but not guaranteed to be immediate, and may occasionally fail (Svix retries on a fixed schedule). Use them for:\n\n- Database sync (a separate users \u002F orgs table that follows Clerk)\n- Notifications (welcome emails, Slack pings, internal alerts)\n- Integrations triggered by lifecycle events\n\nDo NOT rely on webhook delivery as part of a synchronous flow such as onboarding (\"user signs up, then we read X from our DB\"). For data the user just created, read it from the [Clerk session token](https:\u002F\u002Fclerk.com\u002Fdocs\u002Fguides\u002Fsessions\u002Fsession-tokens) or call the Backend API directly. Webhooks fill the gap when you need data about *other* users or events the session token doesn't carry.\n\n## Verify Every Webhook\n\nUse `verifyWebhook(req)` from the framework-specific package (`@clerk\u002Fnextjs\u002Fwebhooks`, `@clerk\u002Fexpress\u002Fwebhooks`, etc.). It reads `CLERK_WEBHOOK_SIGNING_SECRET` automatically and throws on bad signatures. Skipping verification, even for notification-only handlers, exposes the endpoint to spoofed events.\n\n## Make the Webhook Route Public\n\nWebhook routes must be excluded from Clerk middleware protection. Without this, Clerk returns 401.\n\n```typescript\n\u002F\u002F proxy.ts (Next.js \u003C=15: middleware.ts)\nimport { clerkMiddleware, createRouteMatcher } from '@clerk\u002Fnextjs\u002Fserver'\n\nconst isPublicRoute = createRouteMatcher(['\u002Fapi\u002Fwebhooks(.*)'])\n\nexport default clerkMiddleware(async (auth, req) => {\n  if (!isPublicRoute(req)) await auth.protect()\n})\n```\n\n## Complete Webhook Handler (Next.js App Router)\n\n```typescript\n\u002F\u002F app\u002Fapi\u002Fwebhooks\u002Froute.ts\nimport { verifyWebhook } from '@clerk\u002Fnextjs\u002Fwebhooks'\nimport { NextRequest } from 'next\u002Fserver'\nimport { db } from '@\u002Flib\u002Fdb'\n\nexport async function POST(req: NextRequest) {\n  \u002F\u002F ALWAYS verify - never skip, even for notification-only handlers\n  let evt\n  try {\n    evt = await verifyWebhook(req) \u002F\u002F uses CLERK_WEBHOOK_SIGNING_SECRET automatically\n  } catch (err) {\n    console.error('Webhook verification failed:', err)\n    return new Response('Verification failed', { status: 400 })\n  }\n\n  if (evt.type === 'user.created') {\n    const { id, email_addresses, first_name, last_name } = evt.data\n    const email = email_addresses[0]?.email_address\n    const name = `${first_name ?? ''} ${last_name ?? ''}`.trim()\n    await db.users.create({ data: { clerkId: id, email, name } })\n  }\n\n  if (evt.type === 'user.updated') {\n    const { id, email_addresses, first_name, last_name } = evt.data\n    const email = email_addresses[0]?.email_address\n    await db.users.update({ where: { clerkId: id }, data: { email, first_name, last_name } })\n  }\n\n  if (evt.type === 'user.deleted') {\n    const { id } = evt.data\n    await db.users.delete({ where: { clerkId: id } })\n  }\n\n  if (evt.type === 'organizationMembership.created') {\n    const { organization, public_user_data, role } = evt.data\n    const orgId = organization.id\n    const userId = public_user_data.user_id\n    await db.teamMembers.create({ data: { orgId, userId, role } })\n  }\n\n  if (evt.type === 'organizationMembership.deleted') {\n    const { organization, public_user_data } = evt.data\n    const orgId = organization.id\n    const userId = public_user_data.user_id\n    await db.teamMembers.delete({ where: { orgId_userId: { orgId, userId } } })\n  }\n\n  return new Response('OK', { status: 200 })\n}\n```\n\n## Full Example: Welcome Email (Resend) + Slack Notification on user.created\n\nNotification-only handlers still verify the signature. Same pattern as the database-sync handler:\n\n```typescript\n\u002F\u002F app\u002Fapi\u002Fwebhooks\u002Froute.ts\nimport { verifyWebhook } from '@clerk\u002Fnextjs\u002Fwebhooks'\nimport { NextRequest } from 'next\u002Fserver'\nimport { Resend } from 'resend'\n\nconst resend = new Resend(process.env.RESEND_API_KEY)\n\nexport async function POST(req: NextRequest) {\n  \u002F\u002F Step 1: ALWAYS verify the webhook signature - NEVER skip this\n  let evt\n  try {\n    evt = await verifyWebhook(req) \u002F\u002F uses CLERK_WEBHOOK_SIGNING_SECRET env var\n  } catch (err) {\n    console.error('Webhook verification failed:', err)\n    return new Response('Verification failed', { status: 400 })\n  }\n\n  \u002F\u002F Step 2: Listen for user.created event\n  if (evt.type === 'user.created') {\n    \u002F\u002F Step 3: Extract user email and name from webhook payload\n    const { id, email_addresses, first_name, last_name } = evt.data\n    const email = email_addresses[0]?.email_address\n    const name = `${first_name ?? ''} ${last_name ?? ''}`.trim()\n\n    \u002F\u002F Step 4: Call Resend API to send welcome email\n    await resend.emails.send({\n      from: 'noreply@yourdomain.com',\n      to: email,\n      subject: 'Welcome!',\n      html: `\u003Cp>Hi ${name}, welcome to our app!\u003C\u002Fp>`,\n    })\n\n    \u002F\u002F Step 5: Post notification to Slack channel\n    await fetch(process.env.SLACK_WEBHOOK_URL!, {\n      method: 'POST',\n      headers: { 'Content-Type': 'application\u002Fjson' },\n      body: JSON.stringify({\n        text: `New user signed up: ${name} (${email})`,\n      }),\n    })\n  }\n\n  \u002F\u002F Always return 200 to acknowledge receipt\n  return new Response('OK', { status: 200 })\n}\n```\n\n**Also include proxy.ts (Next.js \u003C=15: middleware.ts) to make the route public:**\n```typescript\n\u002F\u002F proxy.ts (Next.js \u003C=15: middleware.ts)\nimport { clerkMiddleware, createRouteMatcher } from '@clerk\u002Fnextjs\u002Fserver'\nconst isPublicRoute = createRouteMatcher(['\u002Fapi\u002Fwebhooks(.*)'])\nexport default clerkMiddleware(async (auth, req) => {\n  if (!isPublicRoute(req)) await auth.protect()\n})\n```\n\n## Full Example: Organization Membership Sync to Database\n\n```typescript\n\u002F\u002F app\u002Fapi\u002Fwebhooks\u002Froute.ts\nimport { verifyWebhook } from '@clerk\u002Fnextjs\u002Fwebhooks'\nimport { NextRequest } from 'next\u002Fserver'\nimport { db } from '@\u002Flib\u002Fdb' \u002F\u002F your database client\n\nexport async function POST(req: NextRequest) {\n  \u002F\u002F ALWAYS verify signature - never skip, even for simple handlers\n  let evt\n  try {\n    evt = await verifyWebhook(req) \u002F\u002F uses CLERK_WEBHOOK_SIGNING_SECRET env var\n  } catch (err) {\n    console.error('Webhook verification failed:', err)\n    return new Response('Verification failed', { status: 400 })\n  }\n\n  if (evt.type === 'organization.created') {\n    const { id, name } = evt.data\n    await db.workspaces.create({\n      data: { orgId: id, name, createdAt: new Date() },\n    })\n  }\n\n  if (evt.type === 'organizationMembership.created') {\n    \u002F\u002F Extract organization ID, user ID, and role from payload\n    const { organization, public_user_data, role } = evt.data\n    const orgId = organization.id\n    const userId = public_user_data.user_id\n\n    \u002F\u002F Add to team_members table\n    await db.team_members.create({\n      data: { orgId, userId, role },\n    })\n\n    \u002F\u002F Create workspace record for new member\n    await db.workspaces.create({\n      data: { orgId, userId, createdAt: new Date() },\n    })\n  }\n\n  if (evt.type === 'organizationMembership.deleted') {\n    \u002F\u002F Extract organization ID and user ID from payload\n    const { organization, public_user_data } = evt.data\n    const orgId = organization.id\n    const userId = public_user_data.user_id\n\n    \u002F\u002F Remove from team_members table\n    await db.team_members.delete({\n      where: { orgId, userId },\n    })\n\n    \u002F\u002F Remove workspace record\n    await db.workspaces.deleteMany({\n      where: { orgId, userId },\n    })\n  }\n\n  \u002F\u002F Return 200 status on success\n  return new Response('OK', { status: 200 })\n}\n```\n\n## Other Frameworks\n\nFor Express, Astro, Fastify, Nuxt, React Router, and TanStack Start, use the framework-specific `verifyWebhook` adapter. Each Clerk SDK package ships its own (`@clerk\u002Fexpress\u002Fwebhooks`, `@clerk\u002Fastro\u002Fwebhooks`, `@clerk\u002Ffastify\u002Fwebhooks`, etc.).\n\nSee `references\u002Fframeworks.md` for full handler examples per framework.\n\n## Type Narrowing for `evt.data`\n\n`verifyWebhook` returns `WebhookEvent`, a discriminated union of all event types. Narrow with `evt.type` to get type-safe access to `evt.data`:\n\n```typescript\nconst evt = await verifyWebhook(req)\n\nif (evt.type === 'user.created') {\n  \u002F\u002F evt.data is now UserJSON, autocompletes id, email_addresses, etc.\n  console.log(evt.data.id)\n}\n```\n\nFor manual typing of nested payloads, import the JSON types from your framework's webhook subpath: `DeletedObjectJSON`, `EmailJSON`, `OrganizationInvitationJSON`, `OrganizationJSON`, `OrganizationMembershipJSON`, `SessionJSON`, `SMSMessageJSON`, `UserJSON`.\n\n## Payload Field Reference\n\n### User events (`user.created`, `user.updated`, `user.deleted`)\n```typescript\nconst {\n  id,                  \u002F\u002F Clerk user ID\n  email_addresses,     \u002F\u002F array; [0].email_address is primary email\n  first_name,\n  last_name,\n  image_url,\n  public_metadata,\n} = evt.data\n```\n\n### Organization events (`organization.created`, `organization.updated`, `organization.deleted`)\n```typescript\nconst {\n  id,    \u002F\u002F org ID\n  name,  \u002F\u002F org name\n  slug,\n} = evt.data\n```\n\n### Organization Membership events (`organizationMembership.created`, `organizationMembership.updated`, `organizationMembership.deleted`)\n```typescript\nconst {\n  organization,        \u002F\u002F { id, name, ... }\n  public_user_data,    \u002F\u002F { user_id, first_name, last_name, ... }\n  role,                \u002F\u002F e.g. 'org:admin', 'org:member'\n} = evt.data\n\u002F\u002F Access: organization.id, public_user_data.user_id, role\n```\n\n## Supported Events (Full Catalog)\n\n**User**: `user.created` `user.updated` `user.deleted`\n\n**Session**: `session.created` `session.ended` `session.removed` `session.revoked`\n\n**Organization**: `organization.created` `organization.updated` `organization.deleted`\n\n**Organization Membership**: `organizationMembership.created` `organizationMembership.updated` `organizationMembership.deleted`\n\n**Organization Domain**: `organizationDomain.created` `organizationDomain.updated` `organizationDomain.deleted`\n\n**Organization Invitation**: `organizationInvitation.accepted` `organizationInvitation.created` `organizationInvitation.revoked`\n\n**Communication**: `email.created` `sms.created`\n\n**Waitlist**: `waitlistEntry.created` `waitlistEntry.updated`\n\n**Permission**: `permission.created` `permission.updated` `permission.deleted`\n\n**Role**: `role.created` `role.updated` `role.deleted`\n\n**Subscription**: `subscription.created` `subscription.updated` `subscription.active` `subscription.pastDue`\n\n**Subscription Item**: `subscriptionItem.created` `subscriptionItem.active` `subscriptionItem.updated` `subscriptionItem.canceled` `subscriptionItem.upcoming` `subscriptionItem.ended` `subscriptionItem.abandoned` `subscriptionItem.incomplete` `subscriptionItem.pastDue` `subscriptionItem.freeTrialEnding`\n\n**Payment**: `paymentAttempt.created` `paymentAttempt.updated`\n\n## Webhook Reliability\n\n**Retries**: Svix retries failed webhooks on a set schedule (see [Svix Retry Schedule](https:\u002F\u002Fdocs.svix.com\u002Fretries)). Return 2xx to succeed, 4xx\u002F5xx to retry. Use the `svix-id` header as an idempotency key to deduplicate retried events.\n\n**Replay**: Failed webhooks can be replayed from Dashboard.\n\n## Common Pitfalls\n\n| Symptom | Cause | Fix |\n|---------|-------|-----|\n| Verification fails (Next.js) | Wrong import or usage | Use `@clerk\u002Fnextjs\u002Fwebhooks`, pass `req` directly |\n| Verification fails (Express) | Using `express.json()` | Use `express.raw({ type: 'application\u002Fjson' })` for webhook route |\n| Route not found (404) | Wrong path | Use `\u002Fapi\u002Fwebhooks` or preserve existing path |\n| Not authorized (401) | Route is protected by middleware | Make route public in `clerkMiddleware()` |\n| No data in DB | Async job pending | Wait\u002Fcheck logs |\n| Duplicate entries | Only handling `user.created` | Also handle `user.updated` |\n| Timeouts | Handler too slow | Queue async work, return 200 first |\n\n## Testing & Deployment\n\n**Local**: Use the Clerk CLI's first-party tunnel — no auth or linked project needed:\n\n```sh\nclerk webhooks listen --token \"$(clerk webhooks token)\" --forward-to http:\u002F\u002Flocalhost:3000\u002Fapi\u002Fwebhooks\n```\n\nAdd the printed relay URL (`https:\u002F\u002Fwebhooks.clerk.com\u002Fin\u002Fc_...\u002F`) as a webhook endpoint in the Dashboard — events don't flow until you do. `svix-*` headers are preserved, so `verifyWebhook()` works against that endpoint's signing secret as usual. Flags, offline signature checks (`clerk webhooks verify`), and agent-mode behavior are in the `clerk-cli` skill. Without the CLI, tunnel `localhost:3000` yourself (`ngrok`, `localtunnel`, `Cloudflare Tunnel`) and add the public URL to the Dashboard endpoint.\n\n**Production**: Update webhook endpoint URL to production domain. Copy `CLERK_WEBHOOK_SIGNING_SECRET` to production env vars.\n\n## References\n\n| Reference | Description |\n|-----------|-------------|\n| `references\u002Fframeworks.md` | Webhook handler examples for Express, Astro, Fastify, Nuxt, React Router, TanStack Start |\n\n## See Also\n\n- `clerk-cli` - `clerk webhooks listen`\u002F`verify` for local webhook testing\n- `clerk-setup` - Initial Clerk install\n- `clerk-orgs` - Org membership events\n- `clerk-billing` - Subscription, subscription item, and payment attempt events\n- `clerk-backend-api` - Sync via direct API calls",{"name":5,"license":15,"metadata":24,"description":7,"allowed-tools":27,"compatibility":28},{"author":25,"version":26},"clerk","1.2.0","WebFetch","Requires CLERK_WEBHOOK_SIGNING_SECRET (svix signing secret from Clerk dashboard)","master","f341c46fed021656175d5c9ccc67a72126e50bfb","skills\u002Fclerk-webhooks","https:\u002F\u002Fgithub.com\u002Fdbillion\u002Fhermes-skills-public","https:\u002F\u002Fgithub.com\u002Fdbillion","I enjoy writing codes,teaching programming, solving problems, tasted automation in Python and never looked back😋😋😋💞","2026-10-14 03:31:55",{"source":8,"skillName":5,"commands":37,"prompt":47,"zipAvailable":48},[38,41,44],{"tool":39,"command":40},"npx","npx skills add dbillion\u002Fhermes-skills-public --skill clerk-webhooks",{"tool":42,"command":43},"bunx","bunx skills add dbillion\u002Fhermes-skills-public --skill clerk-webhooks",{"tool":45,"command":46},"pnpm","pnpm dlx skills add dbillion\u002Fhermes-skills-public --skill clerk-webhooks","安装技能，技能地址：https:\u002F\u002Fgithub.com\u002Fdbillion\u002Fhermes-skills-public\u002Fblob\u002Fmaster\u002Fskills\u002Fclerk-webhooks\u002FSKILL.md",true,[50,56],{"path":51,"resourceType":52,"resourceTypeDesc":53,"sizeBytes":54,"sourceHtmlUrl":55},"evals\u002Fevals.json","REFERENCE","参考文档",3750,"https:\u002F\u002Fgithub.com\u002Fdbillion\u002Fhermes-skills-public\u002Fblob\u002Fmaster\u002Fskills\u002Fclerk-webhooks\u002Fevals\u002Fevals.json",{"path":57,"resourceType":52,"resourceTypeDesc":53,"sizeBytes":58,"sourceHtmlUrl":59},"references\u002Fframeworks.md",6073,"https:\u002F\u002Fgithub.com\u002Fdbillion\u002Fhermes-skills-public\u002Fblob\u002Fmaster\u002Fskills\u002Fclerk-webhooks\u002Freferences\u002Fframeworks.md",[61,68,75,84,91,98],{"skillNo":62,"name":63,"nameZh":6,"description":64,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":65,"categories":66,"keywords":67,"publishedAt":19},"01M7B25T0V7RBKES86Y3RTXQRN","blocked-page-recovery","Use when a fetch fails: 403\u002F429, paywall, WAF, bot wall.","https:\u002F\u002Fgithub.com\u002Fdbillion\u002Fhermes-skills-public\u002Fblob\u002Fmaster\u002Fskills\u002Fweb\u002Fblocked-page-recovery\u002FSKILL.md",[],[],{"skillNo":69,"name":70,"nameZh":6,"description":71,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":72,"categories":73,"keywords":74,"publishedAt":19},"01M7B25DSBBMZRHVD28MAX7N5X","gemini-vision-fallback","Vision fallback: Gemini REST API if vision_analyze blocked.","https:\u002F\u002Fgithub.com\u002Fdbillion\u002Fhermes-skills-public\u002Fblob\u002Fmaster\u002Fskills\u002Fvision\u002Fgemini-vision-fallback\u002FSKILL.md",[],[],{"skillNo":76,"name":77,"nameZh":6,"description":78,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":79,"licenseFileUrl":80,"sourceHtmlUrl":81,"categories":82,"keywords":83,"publishedAt":19},"01M7B22XW9QXT2ZWWXVZDFWYZP","twitter-cli","Use twitter-cli for ALL Twitter\u002FX operations — reading tweets, posting, replying, quoting, liking, retweeting, following, searching, user lookups. Invoke whenever user requests any Twitter interaction.","Apache-2.0","https:\u002F\u002Fgithub.com\u002Fdbillion\u002Fhermes-skills-public\u002Fblob\u002Fmaster\u002Fskills\u002Ftwitter-cli\u002FLICENSE","https:\u002F\u002Fgithub.com\u002Fdbillion\u002Fhermes-skills-public\u002Fblob\u002Fmaster\u002Fskills\u002Ftwitter-cli\u002FSKILL.md",[],[],{"skillNo":85,"name":86,"nameZh":6,"description":87,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":88,"categories":89,"keywords":90,"publishedAt":19},"01M7B22QMWY1B4F7BC114RG4S6","prism-scan","Structural analysis through dynamically generated cognitive lenses. Generates the optimal analytical lens for the specific code\u002Fartifact, then executes it. Finds conservation laws, structural invariants, and concrete bugs that vanilla analysis misses. Use on any code file, system design, or text artifact.","https:\u002F\u002Fgithub.com\u002Fdbillion\u002Fhermes-skills-public\u002Fblob\u002Fmaster\u002Fskills\u002Fts-superhermes-prism-scan\u002FSKILL.md",[],[],{"skillNo":92,"name":93,"nameZh":6,"description":94,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":95,"categories":96,"keywords":97,"publishedAt":19},"01M7B22JA5XCAP1ACT6V50WYR1","prism-reflect","Constraint transparency: analyzes an artifact structurally, then analyzes what its own analysis concealed. Produces a conservation law AND a constraint report showing what was maximized, what was sacrificed, and what to investigate next. The only AI skill that knows what it can't see.","https:\u002F\u002Fgithub.com\u002Fdbillion\u002Fhermes-skills-public\u002Fblob\u002Fmaster\u002Fskills\u002Fts-superhermes-prism-reflect\u002FSKILL.md",[],[],{"skillNo":99,"name":100,"nameZh":6,"description":101,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":102,"categories":103,"keywords":104,"publishedAt":19},"01M7B22EB15M75M4X3C52YGDCC","prism-full","Full Prism: multi-pass structural analysis with mandatory adversarial self-correction. Designs custom analytical passes, executes them with chaining, then attacks its own findings before synthesizing. Use for maximum depth on important code or artifacts.","https:\u002F\u002Fgithub.com\u002Fdbillion\u002Fhermes-skills-public\u002Fblob\u002Fmaster\u002Fskills\u002Fts-superhermes-prism-full\u002FSKILL.md",[],[]]