Communityコーディング&開発github.com

clerk/clerk-webhooks

ClerkのWebhookを使用して、リアルタイムイベントとデータ同期を実現します。各フレームワーク固有のパッケージからverifyWebhookを使って検証し、ユーザー、セッション、組織、請求、支払いイベントを処理します。データベース同期、通知、統合などのイベント駆動機能を構築できます。

clerk-webhooks とは?

このスキルは、Clerkが提供するWebhook機能を利用して、ユーザー管理や認証に関するリアルタイムイベントを処理し、外部システムとのデータ同期を実現するためのものです。ClerkのWebhookは、ユーザーの作成・更新・削除、セッションの開始・終了、組織の変更、課金や支払いの状態変化など、多岐にわたるイベントを配信します。スキルの主な用途は、これらのイベントを検証し、データベースへの同期、通知の送信、外部APIとの連携などのイベント駆動型機能を構築することです。対応プラットフォームは特に限定されておらず、Node.jsやその他のフレームワーク(Next.js、Expressなど)で利用可能で、各フレームワーク向けのClerk SDKに含まれる`verifyWebhook`関数を使用して署名を検証します。Clerk Webhookは、設定ダッシュボードからエンドポイントを登録し、イベントタイプを選択することで有効化できます。このスキルを活用することで、アプリケーションはClerkの認証イベントにリアクティブに反応し、スケーラブルで一貫性のあるデータ管理を実現できます。

対応~Claude Code~Codex CLI~Cursor
npx skills add https://github.com/clerk/skills/tree/main/skills/clerk-webhooks

Installed? Explore more コーディング&開発 skills: steipete/bluebubbles, steipete/eightctl, steipete/blucli · View all 6 →

お気に入りのAIに質問する

このエージェントスキルを事前に読み込んだ状態で新しいチャットを開きます。

ドキュメント

clerk-webhooks は何をしますか?

ClerkのWebhookを使用して、リアルタイムイベントとデータ同期を実現します。各フレームワーク固有のパッケージからverifyWebhookを使って検証し、ユーザー、セッション、組織、請求、支払いイベントを処理します。データベース同期、通知、統合などのイベント駆動機能を構築できます。

概要

Clerk Webhookは、アプリケーション内の認証およびユーザー管理イベントをリアルタイムで外部システムに通知するためのメカニズムです。ユーザー作成、セッション開始、組織変更などのイベントが発生すると、Clerkは設定されたエンドポイントにHTTP POSTリクエストを送信します。

セットアップ

  1. Clerkダッシュボードの「Webhooks」セクションでエンドポイントを追加します。
  2. 受信するイベントタイプ(例:user.created、session.ended、organization.updated)を選択します。
  3. エンドポイントのシークレットキーを環境変数(例:CLERK_WEBHOOK_SECRET)に保存します。

検証

各フレームワーク固有のClerk SDKにはverifyWebhook関数が含まれており、Webhookリクエストの署名を検証します。

Node.js(Express)の例

import { Webhook } from 'svix';

const webhookSecret = process.env.CLERK_WEBHOOK_SECRET;

app.post('/api/webhooks', async (req, res) => {
  const payload = req.body;
  const headers = req.headers;

  const wh = new Webhook(webhookSecret);
  let event;
  try {
    event = wh.verify(payload, headers);
  } catch (err) {
    return res.status(400).json({ error: 'Webhook verification failed' });
  }

  const eventType = event.type;
  const eventData = event.data;

  // イベントの処理
  switch (eventType) {
    case 'user.created':
      // 新しいユーザーをデータベースに同期
      break;
    case 'session.ended':
      // セッション終了時の処理
      break;
    default:
      // 未処理のイベントタイプ
  }

  res.status(200).end();
});

Next.js App Routerの例

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('Please add CLERK_WEBHOOK_SECRET to .env.local');
  }

  const headerPayload = headers();
  const svixId = headerPayload.get('svix-id');
  const svixTimestamp = headerPayload.get('svix-timestamp');
  const svixSignature = headerPayload.get('svix-signature');

  if (!svixId || !svixTimestamp || !svixSignature) {
    return new Response('Error: Missing Svix headers', { status: 400 });
  }

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

  const wh = new Webhook(WEBHOOK_SECRET);
  let evt: WebhookEvent;

  try {
    evt = wh.verify(body, {
      'svix-id': svixId,
      'svix-timestamp': svixTimestamp,
      'svix-signature': svixSignature,
    }) as WebhookEvent;
  } catch (err) {
    return new Response('Error: Verification failed', { status: 400 });
  }

  // イベントの処理
  const { id } = evt.data;
  const eventType = evt.type;

  switch (eventType) {
    case 'user.created':
      console.log('User created:', id);
      break;
    case 'user.updated':
      console.log('User updated:', id);
      break;
    case 'user.deleted':
      console.log('User deleted:', id);
      break;
    default:
      console.log('Unhandled event type:', eventType);
  }

  return new Response('Webhook received', { status: 200 });
}

イベントタイプ

ユーザーイベント

  • user.created - 新しいユーザーが作成された
  • user.updated - ユーザー情報が更新された
  • user.deleted - ユーザーが削除された

セッションイベント

  • session.created - 新しいセッションが開始された
  • session.ended - セッションが終了した
  • session.revoked - セッションが取り消された

組織イベント

  • organization.created - 新しい組織が作成された
  • organization.updated - 組織情報が更新された
  • organization.deleted - 組織が削除された
  • organizationMembership.created - メンバーが追加された
  • organizationMembership.deleted - メンバーが削除された

課金/支払いイベント(Clerkの課金アドオン使用時)

  • billing.created - 課金レコードが作成された
  • billing.updated - 課金情報が更新された
  • payment.successful - 支払いが成功した
  • payment.failed - 支払いが失敗した

ユースケース

データベース同期

新しいユーザーが登録した際に、user.createdイベントを処理してユーザープロファイルをデータベースに自動同期します。

通知送信

セッション開始や組織変更イベントをトリガーに、メールやSlack通知を送信します。

外部統合

ユーザー削除イベントをキャッチして、CRMやメーリングリストなど外部サービスからもユーザーを削除します。

ベストプラクティス

  • 常にWebhookリクエストの署名を検証して、正当性を確認してください。
  • 重複配信を考慮して、べき等性を確保する処理を実装してください。
  • イベント処理に失敗した場合のリトライ戦略を用意してください。
  • 環境変数を使ってシークレットキーを管理し、コードに直接記述しないでください。

参考リンク

Individual skills in this repo

This repo contains 19 individual skills — each has its own dedicated page.

clerk/clerk

Clerk authentication router. Use when user asks about adding authentication, setting up Clerk, custom sign-in flows, Swift or native iOS auth, native Android auth, Next.js patterns, React patterns, Vue patterns, Nuxt patterns, Astro patterns, TanStack Start patterns, Expo patterns, React Router patterns, Chrome Extension patterns, organizations, billing, subscriptions, payments, pricing, plans, seat-based pricing, feature entitlements, syncing users, or testing. Automatically routes to the specific skill based on their task.

clerk/clerk-android

Implement Clerk authentication for native Android apps using Kotlin and Jetpack Compose with clerk-android source-guided patterns. Use for prebuilt AuthView/UserButton or custom API-driven auth flows. Do not use for Expo or React Native projects.

clerk/clerk-astro-patterns

Astro patterns with Clerk — middleware, SSR pages, island components, API routes, static vs SSR rendering. Triggers on: astro clerk, clerk astro middleware, astro protected page, clerk island component, astro API route auth, clerk astro SSR.

clerk/clerk-backend-api

Clerk Backend REST API explorer and executor. Browse tags, inspect endpoint schemas, and execute authenticated requests. Use when listing users, managing organizations, or calling any Clerk API endpoint.

clerk/clerk-billing

Clerk Billing for subscription management - render Clerk's PricingTable and in-app checkout drawer, configure subscription plans, seat-limit plans for B2B, feature entitlements with has(), and billing webhooks. Use for SaaS monetization, plan gating, checkout flows, trials, invoicing, and subscription lifecycle management.

clerk/clerk-chrome-extension-patterns

Chrome Extension auth with @clerk/chrome-extension -- popup/sidepanel setup, syncHost for OAuth/SAML via web app, createClerkClient for service workers and headless extensions, stable CRX ID. Triggers on: Chrome extension auth, Plasmo clerk, popup sign-in, syncHost, background service worker token, createClerkClient, headless extension.

clerk/clerk-custom-ui

Custom authentication flows and component appearance - hooks (useSignIn, useSignUp), themes, colors, fonts, CSS. Use for custom sign-in/sign-up flows, appearance styling, visual customization, branding.

clerk/clerk-expo

Implement Clerk authentication for Expo and React Native apps using @clerk/expo source-guided patterns. Use for prebuilt AuthView/UserButton or custom hook-driven auth flows. Do not use for native iOS/Swift, native Android/Kotlin, or web framework projects.

clerk/clerk-expo-patterns

Expo / React Native patterns with Clerk — SecureStore token cache, OAuth deep linking, useAuth in native, Expo Router protected routes, push notifications with user context. Triggers on: expo clerk, clerk react native, SecureStore token cache, expo router auth, OAuth deep link clerk, mobile auth clerk.

clerk/clerk-nextjs-patterns

Advanced Next.js patterns - middleware, Server Actions, caching with Clerk.

clerk/clerk-nuxt-patterns

Nuxt 3 auth patterns with @clerk/nuxt - middleware, composables, server API routes, SSR. Triggers on: Nuxt auth, useAuth composable, clerkMiddleware Nuxt, server API Clerk, Nuxt route protection.

clerk/clerk-orgs

Clerk Organizations for B2B SaaS - create multi-tenant apps with org switching, role-based access, verified domains, and enterprise SSO. Use for team workspaces, RBAC, org-based routing, member management.

clerk/clerk-react-patterns

React SPA auth patterns with @clerk/react for Vite/CRA - ClerkProvider setup, useAuth/useUser/useClerk hooks, React Router protected routes, custom sign-in flows. Triggers on: Vite Clerk setup, React Router auth, useAuth hook, protected route, custom sign-in form React.

clerk/clerk-react-router-patterns

React Router v7 patterns with Clerk — rootAuthLoader, getAuth in loaders, clerkMiddleware, protected routes, SSR user data, org switching. Triggers on: react-router auth, rootAuthLoader, getAuth loader, react-router protected route, loader authentication, SSR auth react-router.

clerk/clerk-setup

Add Clerk authentication to any project by following the official quickstart guides.

clerk/clerk-swift

Implement Clerk authentication for native Swift and iOS apps using ClerkKit and ClerkKitUI source-guided patterns. Use for prebuilt AuthView or custom native flows. Do not use for Expo or React Native projects.

clerk/clerk-tanstack-patterns

TanStack React Start auth patterns with @clerk/tanstack-react-start - createServerFn, beforeLoad guards, loaders, Vinxi server. Triggers on: TanStack auth, createServerFn clerk, beforeLoad protection, TanStack Start middleware.

clerk/clerk-testing

E2E testing for Clerk apps. Use with Playwright or Cypress for auth flow tests.

clerk/clerk-vue-patterns

Vue 3 patterns with Clerk — composables (useAuth, useUser, useClerk, useOrganization), Vue Router guards, Pinia auth store integration. Triggers on: vue clerk, useAuth vue, clerk composables, vue router clerk guard, pinia auth clerk. For Nuxt, use clerk-nuxt-patterns instead.

関連スキル