Clerk Webhooks
ClerkOfficialCreated by clerk
- Skill
- Tool integration
- Automation and integrations
- MIT
- Medium risk
AutoGineer summary
Written by AutoGineer from the skill’s own files, not by the author
Clerk webhooks enable real-time event-driven architectures by pushing updates from Clerk to your application. This skill provides the patterns and framework-specific implementations required to securely verify incoming webhook payloads using the verifyWebhook utility. It covers the full lifecycle of events, including user management, organization memberships, billing, and payment updates, ensuring your application stays in sync with Clerk's state.
What it does
- Provides framework-specific implementations for verifying webhook signatures.
- Offers patterns for database synchronization based on user and organization events.
- Enables integration with third-party services like Slack or email providers via lifecycle events.
- Details the full catalog of supported Clerk events for comprehensive system monitoring.
- Includes guidance on local testing and production deployment strategies.
- Provides type-safe payload handling for event data.
When to use it
- When you need to keep a local database in sync with Clerk user or organization data.
- When you need to trigger asynchronous side effects like welcome emails or internal alerts.
- When you need to react to billing, subscription, or payment events.
- When you need to handle events that are not available via session tokens.
Advantages
- Ensures security by mandating signature verification for every request.
- Reduces boilerplate with framework-specific adapters.
- Supports a wide range of lifecycle events for granular control.
- Provides clear patterns for handling asynchronous data consistency.
Usage examples
- “How do I set up a Next.js route to handle user.created events from Clerk?”
- The agent provides a POST handler using verifyWebhook from @clerk/nextjs/webhooks, including logic to extract user data and save it to your database.
- “What is the best way to send a Slack notification when a new organization is created?”
- The agent provides a code snippet demonstrating how to verify the webhook and use a fetch call to post the organization details to a Slack webhook URL.
Install
Download the skill as a ZIP:
https://autogineer.com/agent-skills/clerk/clerk-webhooks/downloadUnzip it into the cross-client skills folder of your project:
mkdir -p .agents/skills && unzip clerk-webhooks.zip -d .agents/skills
Documentation by clerk
Webhooks
Output complete, working webhook handlers with verifyWebhook(req) verification in every handler.
When to Use Webhooks
Webhooks 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:
Database sync (a separate users / orgs table that follows Clerk)
Notifications (welcome emails, Slack pings, internal alerts)
Integrations triggered by lifecycle events
Do 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 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.
Verify Every Webhook
Use verifyWebhook(req) from the framework-specific package (@clerk/nextjs/webhooks, @clerk/express/webhooks, 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.
Keep the Webhook Route Unprotected
Webhook deliveries carry no user session. verifyWebhook() is the only check the route needs. A bare clerkMiddleware() protects nothing, so the route is already reachable. Don't call auth.protect() for /api/webhooks(.*), in middleware or in the handler. A project that does returns 404 for every delivery until that call is removed. See Ensure the webhook route is public.
Complete Webhook Handler (Next.js App Router)
// app/api/webhooks/route.ts
import { verifyWebhook } from '@clerk/nextjs/webhooks'
import { NextRequest } from 'next/server'
import { db } from '@/lib/db'
export async function POST(req: NextRequest) {
// ALWAYS verify - never skip, even for notification-only handlers
let evt
try {
evt = await verifyWebhook(req) // uses CLERK_WEBHOOK_SIGNING_SECRET automatically
} catch (err) {
console.error('Webhook verification failed:', err)
return new Response('Verification failed', { status: 400 })
}
if (evt.type === 'user.created') {
const { id, email_addresses, first_name, last_name } = evt.data
const email = email_addresses[0]?.email_address
const name = `${first_name ?? ''} ${last_name ?? ''}`.trim()
await db.users.create({ data: { clerkId: id, email, name } })
}
if (evt.type === 'user.updated') {
const { id, email_addresses, first_name, last_name } = evt.data
const email = email_addresses[0]?.email_address
await db.users.update({ where: { clerkId: id }, data: { email, first_name, last_name } })
}
if (evt.type === 'user.deleted') {
const { id } = evt.data
await db.users.delete({ where: { clerkId: id } })
}
if (evt.type === 'organizationMembership.created') {
const { organization, public_user_data, role } = evt.data
const orgId = organization.id
const userId = public_user_data.user_id
await db.teamMembers.create({ data: { orgId, userId, role } })
}
if (evt.type === 'organizationMembership.deleted') {
const { organization, public_user_data } = evt.data
const orgId = organization.id
const userId = public_user_data.user_id
await db.teamMembers.delete({ where: { orgId_userId: { orgId, userId } } })
}
return new Response('OK', { status: 200 })
}Full Example: Welcome Email (Resend) + Slack Notification on user.created
Notification-only handlers still verify the signature. Same pattern as the database-sync handler:
// app/api/webhooks/route.ts
import { verifyWebhook } from '@clerk/nextjs/webhooks'
import { NextRequest } from 'next/server'
import { Resend } from 'resend'
const resend = new Resend(process.env.RESEND_API_KEY)
export async function POST(req: NextRequest) {
// Step 1: ALWAYS verify the webhook signature - NEVER skip this
let evt
try {
evt = await verifyWebhook(req) // uses CLERK_WEBHOOK_SIGNING_SECRET env var
} catch (err) {
console.error('Webhook verification failed:', err)
return new Response('Verification failed', { status: 400 })
}
// Step 2: Listen for user.created event
if (evt.type === 'user.created') {
// Step 3: Extract user email and name from webhook payload
const { id, email_addresses, first_name, last_name } = evt.data
const email = email_addresses[0]?.email_address
const name = `${first_name ?? ''} ${last_name ?? ''}`.trim()
// Step 4: Call Resend API to send welcome email
await resend.emails.send({
from: '[email protected]',
to: email,
subject: 'Welcome!',
html: `<p>Hi ${name}, welcome to our app!</p>`,
})
// Step 5: Post notification to Slack channel
await fetch(process.env.SLACK_WEBHOOK_URL!, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({
text: `New user signed up: ${name} (${email})`,
}),
})
}
// Always return 200 to acknowledge receipt
return new Response('OK', { status: 200 })
}Full Example: Organization Membership Sync to Database
// app/api/webhooks/route.ts
import { verifyWebhook } from '@clerk/nextjs/webhooks'
import { NextRequest } from 'next/server'
import { db } from '@/lib/db' // your database client
export async function POST(req: NextRequest) {
// ALWAYS verify signature - never skip, even for simple handlers
let evt
try {
evt = await verifyWebhook(req) // uses CLERK_WEBHOOK_SIGNING_SECRET env var
} catch (err) {
console.error('Webhook verification failed:', err)
return new Response('Verification failed', { status: 400 })
}
if (evt.type === 'organization.created') {
const { id, name } = evt.data
await db.workspaces.create({
data: { orgId: id, name, createdAt: new Date() },
})
}
if (evt.type === 'organizationMembership.created') {
// Extract organization ID, user ID, and role from payload
const { organization, public_user_data, role } = evt.data
const orgId = organization.id
const userId = public_user_data.user_id
// Add to team_members table
await db.team_members.create({
data: { orgId, userId, role },
})
// Create workspace record for new member
await db.workspaces.create({
data: { orgId, userId, createdAt: new Date() },
})
}
if (evt.type === 'organizationMembership.deleted') {
// Extract organization ID and user ID from payload
const { organization, public_user_data } = evt.data
const orgId = organization.id
const userId = public_user_data.user_id
// Remove from team_members table
await db.team_members.delete({
where: { orgId, userId },
})
// Remove workspace record
await db.workspaces.deleteMany({
where: { orgId, userId },
})
}
// Return 200 status on success
return new Response('OK', { status: 200 })
}Other Frameworks
For Express, Astro, Fastify, Nuxt, React Router, and TanStack Start, use the framework-specific verifyWebhook adapter. Each Clerk SDK package ships its own (@clerk/express/webhooks, @clerk/astro/webhooks, @clerk/fastify/webhooks, etc.).
See references/frameworks.md for full handler examples per framework.
Type Narrowing for evt.data
verifyWebhook returns WebhookEvent, a discriminated union of all event types. Narrow with evt.type to get type-safe access to evt.data:
const evt = await verifyWebhook(req)
if (evt.type === 'user.created') {
// evt.data is now UserJSON, autocompletes id, email_addresses, etc.
console.log(evt.data.id)
}For manual typing of nested payloads, import the JSON types from your framework's webhook subpath: DeletedObjectJSON, EmailJSON, OrganizationInvitationJSON, OrganizationJSON, OrganizationMembershipJSON, SessionJSON, SMSMessageJSON, UserJSON.
Payload Field Reference
User events (user.created, user.updated, user.deleted)
const {
id, // Clerk user ID
email_addresses, // array; [0].email_address is primary email
first_name,
last_name,
image_url,
public_metadata,
} = evt.dataOrganization events (organization.created, organization.updated, organization.deleted)
const {
id, // org ID
name, // org name
slug,
} = evt.dataOrganization Membership events (organizationMembership.created, organizationMembership.updated, organizationMembership.deleted)
const {
organization, // { id, name, ... }
public_user_data, // { user_id, first_name, last_name, ... }
role, // e.g. 'org:admin', 'org:member'
} = evt.data
// Access: organization.id, public_user_data.user_id, roleSupported Events (Full Catalog)
User: user.created user.updated user.deleted
Session: session.created session.ended session.removed session.revoked
Organization: organization.created organization.updated organization.deleted
Organization Membership: organizationMembership.created organizationMembership.updated organizationMembership.deleted
Organization Domain: organizationDomain.created organizationDomain.updated organizationDomain.deleted
Organization Invitation: organizationInvitation.accepted organizationInvitation.created organizationInvitation.revoked
Communication: email.created sms.created
Waitlist: waitlistEntry.created waitlistEntry.updated
Permission: permission.created permission.updated permission.deleted
Role: role.created role.updated role.deleted
Subscription: subscription.created subscription.updated subscription.active subscription.pastDue
Subscription Item: subscriptionItem.created subscriptionItem.active subscriptionItem.updated subscriptionItem.canceled subscriptionItem.upcoming subscriptionItem.ended subscriptionItem.abandoned subscriptionItem.incomplete subscriptionItem.pastDue subscriptionItem.freeTrialEnding
Payment: paymentAttempt.created paymentAttempt.updated
Webhook Reliability
Retries: Svix retries failed webhooks on a set schedule (see Svix Retry Schedule). Return 2xx to succeed, 4xx/5xx to retry. Use the svix-id header as an idempotency key to deduplicate retried events.
Replay: Failed webhooks can be replayed from Dashboard.
Common Pitfalls
| Symptom | Cause | Fix |
|---|---|---|
| Verification fails (Next.js) | Wrong import or usage | Use @clerk/nextjs/webhooks, pass req directly |
| Verification fails (Express) | Using express.json() | Use express.raw({ type: 'application/json' }) for webhook route |
| Route not found (404) | Wrong path | Use /api/webhooks or preserve existing path |
| 401 or 404 on every delivery | auth.protect() covers the webhook route (in middleware or in the handler) | Remove that check; verifyWebhook() is the only check the route needs |
| No data in DB | Async job pending | Wait/check logs |
| Duplicate entries | Only handling user.created | Also handle user.updated |
| Timeouts | Handler too slow | Queue async work, return 200 first |
Testing & Deployment
Local: Use the Clerk CLI's first-party tunnel — no auth or linked project needed:
clerk webhooks listen --token "$(clerk webhooks token)" --forward-to http://localhost:3000/api/webhooksAdd the printed relay URL (https://webhooks.clerk.com/in/c_.../) 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.
Production: Update webhook endpoint URL to production domain. Copy CLERK_WEBHOOK_SIGNING_SECRET to production env vars.
References
| Reference | Description |
|---|---|
references/frameworks.md | Webhook handler examples for Express, Astro, Fastify, Nuxt, React Router, TanStack Start |
See Also
clerk-cli-clerk webhooks listen/verifyfor local webhook testingclerk-setup- Initial Clerk installclerk-orgs- Org membership eventsclerk-billing- Subscription, subscription item, and payment attempt eventsclerk-backend-api- Sync via direct API calls
Files
- ATTRIBUTION.mdAdded by AutoGineer836 B
- SKILL.md13.0 KiB
- evals/evals.json3.8 KiB
- references/frameworks.md6.2 KiB
references/frameworks.md
Framework-Specific Webhook Handlers
Each Clerk SDK package ships its own verifyWebhook adapter that reads the framework's native request type and uses CLERK_WEBHOOK_SIGNING_SECRET automatically. Use the framework-specific import; do not roll your own with raw svix.
Same WebhookEvent payload shape across all frameworks. See SKILL.md for payload field reference and the full event catalog.
Express
import { verifyWebhook } from '@clerk/express/webhooks'
import express from 'express'
const app = express()
// Use express.raw() not express.json() for the webhook route -
// signature verification requires the raw body bytes.
app.post('/api/webhooks', express.raw({ type: 'application/json' }), async (req, res) => {
try {
const evt = await verifyWebhook(req)
if (evt.type === 'user.created') {
const { id, email_addresses, first_name, last_name } = evt.data
const email = email_addresses[0]?.email_address
console.log(`New user: ${first_name} ${last_name} (${email})`)
}
return res.send('Webhook received')
} catch (err) {
console.error('Error verifying webhook:', err)
return res.status(400).send('Error verifying webhook')
}
})Astro
// src/pages/api/webhooks.ts
import { verifyWebhook } from '@clerk/astro/webhooks'
import type { APIRoute } from 'astro'
export const POST: APIRoute = async ({ request }) => {
try {
const evt = await verifyWebhook(request, {
signingSecret: import.meta.env.CLERK_WEBHOOK_SIGNING_SECRET,
})
if (evt.type === 'user.created') {
const { id, email_addresses } = evt.data
const email = email_addresses[0]?.email_address
console.log(`New user: ${id} (${email})`)
}
return new Response('Webhook received', { status: 200 })
} catch (err) {
console.error('Error verifying webhook:', err)
return new Response('Error verifying webhook', { status: 400 })
}
}Astro requires explicit signingSecret since import.meta.env is not auto-read.
Fastify
import { verifyWebhook } from '@clerk/fastify/webhooks'
import Fastify from 'fastify'
const fastify = Fastify()
fastify.post('/api/webhooks', async (request, reply) => {
try {
const evt = await verifyWebhook(request)
if (evt.type === 'user.created') {
const { id } = evt.data
console.log(`New user: ${id}`)
}
return 'Webhook received'
} catch (err) {
console.error('Error verifying webhook:', err)
return reply.code(400).send('Error verifying webhook')
}
})Nuxt
// server/api/webhooks.post.ts
import { verifyWebhook } from '@clerk/nuxt/webhooks'
export default defineEventHandler(async (event) => {
try {
const evt = await verifyWebhook(event)
if (evt.type === 'user.created') {
const { id } = evt.data
console.log(`New user: ${id}`)
}
return 'Webhook received'
} catch (err) {
console.error('Error verifying webhook:', err)
setResponseStatus(event, 400)
return 'Error verifying webhook'
}
})Prefix the env var with NUXT_ (i.e. NUXT_CLERK_WEBHOOK_SIGNING_SECRET) per Nuxt runtime config rules.
When tunneling via ngrok in dev, allow the host in nuxt.config.ts:
export default defineNuxtConfig({
vite: {
server: {
allowedHosts: ['fawn-two-nominally.ngrok-free.app'],
},
},
})React Router
// app/routes/webhooks.ts
import { verifyWebhook } from '@clerk/react-router/webhooks'
import type { Route } from './+types/webhooks'
export const action = async ({ request }: Route.ActionArgs) => {
try {
const evt = await verifyWebhook(request)
if (evt.type === 'user.created') {
const { id } = evt.data
console.log(`New user: ${id}`)
}
return new Response('Webhook received', { status: 200 })
} catch (err) {
console.error('Error verifying webhook:', err)
return new Response('Error verifying webhook', { status: 400 })
}
}Register the route in router.ts:
import { type RouteConfig, route, index } from '@react-router/dev/routes'
export default [
index('routes/home.tsx'),
route('api/webhooks', 'routes/webhooks.ts'),
] satisfies RouteConfigWhen tunneling via ngrok in dev, allow the host in vite.config.ts:
export default defineConfig({
server: {
allowedHosts: ['fawn-two-nominally.ngrok-free.app'],
},
})TanStack Start
// src/routes/api/webhooks.ts
import { verifyWebhook } from '@clerk/tanstack-react-start/webhooks'
import { createFileRoute } from '@tanstack/react-router'
export const Route = createFileRoute('/api/webhooks')({
server: {
handlers: {
POST: async ({ request }) => {
try {
const evt = await verifyWebhook(request)
if (evt.type === 'user.created') {
const { id } = evt.data
console.log(`New user: ${id}`)
}
return new Response('Webhook received', { status: 200 })
} catch (err) {
console.error('Error verifying webhook:', err)
return new Response('Error verifying webhook', { status: 400 })
}
},
},
},
})When tunneling via ngrok in dev, allow the host in vite.config.ts:
import { tanstackStart } from '@tanstack/react-start/plugin/vite'
import viteReact from '@vitejs/plugin-react'
import { defineConfig } from 'vite'
export default defineConfig({
plugins: [tanstackStart(), viteReact()],
server: {
allowedHosts: ['fawn-two-nominally.ngrok-free.app'],
},
})Common Patterns Across Frameworks
All
verifyWebhookadapters return the sameWebhookEventdiscriminated union, so handler logic (if (evt.type === ...)) is identical.All adapters read
CLERK_WEBHOOK_SIGNING_SECRETautomatically except Astro (passsigningSecretoption).All adapters require an unprotected webhook route: nothing calls
auth.protect()(or the framework's equivalent) for/api/webhooks(.*), in middleware or in the handler.Vite-based frameworks (Nuxt, React Router, TanStack Start) need
allowedHostsconfigured when tunneling localhost via ngrok in development.Express specifically needs
express.raw({ type: 'application/json' })for the webhook route, raw body bytes are required for signature verification.
Requirements and compatibility
Works with: Claude Code, Claude apps, OpenAI Codex, GitHub Copilot, Cursor, Gemini CLI, Kiro, OpenCode, Goose, Amp, Roo Code, JetBrains Junie, Factory Droid, Devin (ex-Windsurf), Mistral Vibe, OpenHands, Letta
“Works with” means the tool reads the open Agent Skills format; a skill written for one tool may use features others lack.
Needs: Declares allowed tools, Needs an API key
The author says: Requires CLERK_WEBHOOK_SIGNING_SECRET (svix signing secret from Clerk dashboard)
Security
What our scanner noticed· Medium risk
- Possible data-exfiltration endpoints
A static scan is not a guarantee. Skills are third-party content: review a skill before you let an agent use it.
Attribution and licence
- Created by
- clerk
- Publisher
- Clerk (Official)
- Source
- clerk/skills · skills/clerk-webhooks · commit c5d2c0d
- Licence
- MIT License (redistribution allowed)
- ATTRIBUTION.md (written by AutoGineer)
- Synced
AutoGineer is not affiliated with or endorsed by clerk or Clerk.
Download ZIP
The ZIP holds the skill’s files, its licence files and an ATTRIBUTION.md. Download clerk-webhooks.zip