javad
javad

Reputation: 23

syncing clerk with supabase using prisma + t3 stack and webhooks

I want to sync my user table to supabase when users authenticate with clerk. I'm using t3 stack and ngrok for pointing my localhost:3000 to and address.

this is my user.ts file which is in src/pages/api/webhooks/user.ts :

import type { IncomingHttpHeaders } from "http";
import type { NextApiRequest, NextApiResponse } from "next";
import { Webhook, type WebhookRequiredHeaders } from "svix";
import type {  } from "svix"
import { buffer } from "micro";
import { prisma } from "~/server/db";

// Disable the bodyParser so we can access the raw
// request body for verification.
export const config = {
  api: {
    bodyParser: false,
  },
};

const webhookSecret: string = process.env.WEBHOOK_SECRET || "";

export default async function handler(
  req: NextApiRequestWithSvixRequiredHeaders,
  res: NextApiResponse
) {
  
  const payload = (await buffer(req)).toString();
  const headers = req.headers;
  const wh = new Webhook(webhookSecret);
  let evt: Event | null = null;
  try {
    evt = wh.verify(payload, headers) as Event;
  } catch (_) {
    return res.status(400).json({});
  }


 // Handle the webhook
  const eventType: EventType = evt.type;
  
   if (eventType === "user.created" || eventType === "user.updated") {
    console.log("hello")
   const { id, ...attributes } = evt.data;
   console.log(id)
   await prisma.user.upsert({
     where: { external_id: id as string },
     create: {
       external_id: id as string,
       attributes,
     },
     update: { attributes },
   });
 }

  res.json({});
}

type NextApiRequestWithSvixRequiredHeaders = NextApiRequest & {
  headers: IncomingHttpHeaders & WebhookRequiredHeaders;
};

// Generic (and naive) way for the Clerk event
// payload type.
type Event = {
  data: Record<string, string | number>;
  object: "event";
  type: EventType;
};

type EventType = "user.created" | "user.updated" | "*";

ngrok works

enter image description here

and when I check webhooks section in clerk website, it is sending user.created to the endpoint containing user data and giving me success message. enter image description here

but as you can see i console.log in two section in my user.ts but nothing happens in console and of course it not updating my database. I also has my endpoint secret in my .env file.

I'm expecting my console to show something and after that I have to be able to update and create my user in the database.

Upvotes: 0

Views: 682

Answers (1)

Hamed MP
Hamed MP

Reputation: 5503

From ngrok logs, it seems your endpoint is set to {ngrok url}/api/webhooks but the webhook API defined in src/pages/api/webhooks/user.ts which makes the endpoint be {ngrok url}/api/webhooks/user.

I hope it's helpful.

Upvotes: 0

Related Questions