Reputation: 103
I'm currently working on a personal project with Nextjs (T3 stack) and i'm stuck implementing the synchronization between Clerk users and a user table inside my Supabase DB.
My objective is to have a Users
table (which I already defined in my schema.prisma
) that contains both the user_id provided by Clerk and a custom int variable. I found about Clerk Webhooks and tried to implement one following the documentation provided by Clerk. Removing unnecesary details, my script contains the following code:
import { Webhook } from "svix";
import { headers } from "next/headers";
import { type WebhookEvent } from "@clerk/nextjs/server";
export async function POST(req: Request) {
console.log("RECEIVED WEBHOOK REQUEST")
const CLERK_WEBHOOK_SECRET = process.env.CLERK_WEBHOOK_SECRET;
if (!CLERK_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()) as Record<string, unknown>;
const body = JSON.stringify(payload);
// Create a new SVIX instance with your secret.
const wh = new Webhook(CLERK_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,
});
}
if (evt) {
try {
if (evt.type === "user.updated") {
console.log("USER UPDATED")
console.log(evt)
// database action
}
// Same for user.created and user.deleted
return new Response("", { status: 201 });
} catch (err) {
console.error(err);
return new Response("Error occured -- processing webhook data", {
status: 500,
});
}
}
}
The path to this code is /pages/api/webhooks/clerkWebhooks.ts
.
I also edited my middleware.ts
file to include the new route:
...
export default authMiddleware({
publicRoutes: ["/","/api/webhooks(.*)"],
ignoredRoutes: ["/"],
});
...
However, when I test my webhook, I get no console logs.
Any help or hint will be appreciated. Thanks in advance.
Is my location of the clerkWebhook.ts file appropiate?
Is my middleware.ts file correctly pointing to the new route of the clerkWebhook?
Why am I not getting console logs when testing?
Upvotes: 0
Views: 353
Reputation: 26
I had a similar issue, turn '/pages/api/webhooks/clerkWebhooks.ts' to '/pages/api/webhooks'
Upvotes: 0