💬

【Drizzle ORM】NextJs14 と Drizzle ORM【#5 Clerk Webhook】

2024/07/11に公開

【#5 Clerk Webhook】

YouTube: https://youtu.be/inEjiResS2E
https://youtu.be/inEjiResS2E

今回は前回作成したドメインをClerkのダッシュボードに登録して、
Clerkのwebhookを使用できるようにします。

https://clerk.com/docs/integrations/webhooks/sync-data

Webhookのテストを実行する際には、
NextJSとngrokを両方起動しておく必要があります。

.env.local
DATABASE_URL=postgresql://myapp_owner:HyS.............

NEXT_PUBLIC_CLERK_PUBLISHABLE_KEY=pk_test_ZGV.........
CLERK_SECRET_KEY=sk_test_4l...............

WEBHOOK_SECRET=whsec_ZO..................
npm install svix
app/api/webhooks/clerk/route.ts
import { Webhook } from 'svix'
import { headers } from 'next/headers'
import { WebhookEvent } from '@clerk/nextjs/server'

export async function POST(req: Request) {

  // You can find this in the Clerk Dashboard -> Webhooks -> choose the endpoint
  const WEBHOOK_SECRET = process.env.WEBHOOK_SECRET

  if (!WEBHOOK_SECRET) {
    throw new Error('Please add WEBHOOK_SECRET from Clerk Dashboard to .env or .env.local')
  }

  // Get the headers
  const headerPayload = headers();
  const svix_id = headerPayload.get("svix-id");
  const svix_timestamp = headerPayload.get("svix-timestamp");
  const svix_signature = headerPayload.get("svix-signature");

  // If there are no headers, error out
  if (!svix_id || !svix_timestamp || !svix_signature) {
    return new Response('Error occured -- no svix headers', {
      status: 400
    })
  }

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

  // Create a new Svix instance with your secret.
  const wh = new Webhook(WEBHOOK_SECRET);

  let evt: WebhookEvent

  // Verify the payload with the headers
  try {
    evt = wh.verify(body, {
      "svix-id": svix_id,
      "svix-timestamp": svix_timestamp,
      "svix-signature": svix_signature,
    }) as WebhookEvent
  } catch (err) {
    console.error('Error verifying webhook:', err);
    return new Response('Error occured', {
      status: 400
    })
  }

  // Do something with the payload
  // For this guide, you simply log the payload to the console
  const { id } = evt.data;
  const eventType = evt.type;
  console.log(`Webhook with and ID of ${id} and type of ${eventType}`)
  console.log('Webhook body:', body)

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

Discussion