Community코딩 & 개발github.com

clerk/clerk-webhooks

Clerk 웹훅을 사용한 실시간 이벤트 처리 및 데이터 동기화. 프레임워크별 패키지의 verifyWebhook으로 검증합니다. 사용자, 세션, 조직, 결제 이벤트를 처리합니다. 데이터베이스 동기화, 알림, 통합 등 이벤트 기반 기능을 구축합니다.

clerk-webhooks란 무엇인가요?

이 스킬은 Clerk의 웹훅을 활용하여 사용자 인증, 세션, 조직, 결제 및 구독과 같은 실시간 이벤트를 안전하게 수신하고 처리하는 방법을 제공합니다. 각 프레임워크(Next.js, Express, Fastify 등)에 특화된 `verifyWebhook` 함수를 사용하여 웹훅 페이로드를 검증함으로써 보안을 유지합니다. 개발자는 이 가이드를 통해 사용자 생성/업데이트/삭제, 조직 변경, 결제 성공/실패 등 다양한 이벤트를 구독하고, 데이터베이스 동기화, 알림 전송, 서드파티 통합과 같은 이벤트 기반 기능을 구현할 수 있습니다. Clerk SDK와 긴밀하게 통합되어 있어 복잡한 인증 로직 없이도 안정적이고 확장 가능한 이벤트 기반 아키텍처를 구축하는 데 유용합니다.

지원 대상~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 웹훅을 사용한 실시간 이벤트 처리 및 데이터 동기화. 프레임워크별 패키지의 verifyWebhook으로 검증합니다. 사용자, 세션, 조직, 결제 이벤트를 처리합니다. 데이터베이스 동기화, 알림, 통합 등 이벤트 기반 기능을 구축합니다.

개요

Clerk 웹훅은 사용자 인증, 세션, 조직, 결제와 관련된 실시간 이벤트를 애플리케이션에 전달합니다. 이를 통해 Clerk의 이벤트를 수신하고 데이터베이스 동기화, 알림 전송, 외부 시스템과의 통합 등 다양한 작업을 수행할 수 있습니다.

지원되는 웹훅 이벤트

다음은 주요 웹훅 이벤트 목록입니다:

  • user.created - 새 사용자가 생성됨
  • user.updated - 사용자 정보가 업데이트됨
  • user.deleted - 사용자가 삭제됨
  • session.created - 새 세션이 생성됨
  • session.ended - 세션이 종료됨
  • organization.created - 조직 생성됨
  • organization.updated - 조직 정보 업데이트됨
  • organization.deleted - 조직 삭제됨
  • organizationMembership.created - 조직 멤버십 추가됨
  • organizationMembership.deleted - 조직 멤버십 제거됨
  • billing.* - 구독 및 결제 관련 이벤트

설치 및 설정

1. Clerk SDK 설치

선택한 프레임워크에 따라 적절한 Clerk 패키지를 설치합니다:

npm install @clerk/nextjs
# 또는
npm install @clerk/express
# 또는
npm install @clerk/fastify

2. 웹훅 엔드포인트 생성

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 from Clerk Dashboard to .env or .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 occurred -- no svix headers', {
      status: 400
    })
  }

  // 본문 가져오기
  const payload = await req.json()
  const body = JSON.stringify(payload)

  // Svix 웹훅 검증 객체 생성
  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) {
    console.error('Error verifying webhook:', err)
    return new Response('Error occurred', {
      status: 400
    })
  }

  // 이벤트 타입에 따른 처리
  const { type } = evt
  
  switch (type) {
    case 'user.created':
      // 사용자 생성 시 처리 로직
      break
    case 'user.updated':
      // 사용자 업데이트 처리 로직
      break
    case 'user.deleted':
      // 사용자 삭제 처리 로직
      break
    default:
      console.log(`처리되지 않은 이벤트 타입: ${type}`)
  }

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

환경 변수 설정

.env.local 파일에 Clerk 웹훅 시크릿을 추가하세요:

CLERK_WEBHOOK_SECRET=whsec_your_webhook_secret

보안 고려사항

  • 항상 웹훅 페이로드를 검증하세요. verifyWebhook을 사용하면 자동으로 처리됩니다.
  • 웹훅 시크릿은 환경 변수로 안전하게 관리하세요.
  • HTTPS 엔드포인트를 사용하세요.
  • 이벤트 처리는 멱등성(idempotency)을 보장하도록 설계하세요.

모범 사례

  1. 데이터베이스 동기화: 사용자 정보를 로컬 데이터베이스와 동기화할 때 웹훅을 사용하세요.
  2. 비동기 처리: 시간이 오래 걸리는 작업은 큐 시스템을 사용하여 처리하세요.
  3. 에러 처리: 웹훅 처리 실패 시 적절한 로깅과 재시도 메커니즘을 구현하세요.
  4. 테스트: Clerk Dashboard에서 웹훅 테스트를 통해 엔드포인트를 검증하세요.

추가 자료

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.

관련 스킬