Swapnil Dwivedi
Swapnil Dwivedi

Reputation: 1

Clerk Webhook not getting trigger and mongodb not updating

Im making my project and using clerk for authenication and i want clerk data to be pushed on my mongodb but its not getting update and there no way to see any error logs as nothing displays on console i have already deployed my url on vercel (im using next with js not ts)

db.js

import mongoose from "mongoose";

const MongoDB_URI = process.env.MongoDB_URI;

if (!MongoDB_URI) {
  throw new Error("Please define MONGODB_URL in your .env file");
}

let cached = global.mongoose;

if (!cached) {
  cached = global.mongoose = { conn: null, promise: null };
}

export const connectDB = async () => {
  if (cached.conn) return cached.conn;

  if (!cached.promise) {
    cached.promise = mongoose.connect(MongoDB_URI, {
      dbName: "clerkauthv5",
      useNewUrlParser: true,
      useUnifiedTopology: true,
    });
  }

  cached.conn = await cached.promise;
  return cached.conn;
};

api/webhooks/clerk

import { Webhook } from "svix";
import { headers } from "next/headers";
import {User} from "../../../../../modals/user.modal";
import { connectDB } from "@/libs/db";

export async function POST(req) {
  // Clerk Webhook Signing Secret from .env
  const WEBHOOK_SECRET = process.env.WEBHOOK_SECRET;

  if (!WEBHOOK_SECRET) {
    return new Response("Error: SIGNING_SECRET is missing", { status: 500 });
  }

  // Connect to MongoDB
  await connectDB();

  // Initialize Svix Webhook verification
  const wh = new Webhook(WEBHOOK_SECRET);

  // Get 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 (!svix_id || !svix_timestamp || !svix_signature) {
    return new Response("Error: Missing Svix headers", { status: 400 });
  }

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

  let event;

  // Verify Clerk Webhook
  try {
    event = wh.verify(body, {
      "svix-id": svix_id,
      "svix-timestamp": svix_timestamp,
      "svix-signature": svix_signature,
    });
  } catch (err) {
    console.error("Webhook verification failed:", err);
    return new Response("Error: Invalid Webhook Signature", { status: 400 });
  }

  // Extract event data
  const { id, type, data } = event;
  console.log(`Received webhook: ${type} for user ${id}`);

  // If a new user is created, store metadata in MongoDB
  if (type === "user.created") {
    try {
      const newUser = new User({
        clerkId: data.id,
        email: data.email_addresses[0].email_address, // Extract email
        name: `${data.first_name} ${data.last_name}`,
        metadata: data.public_metadata || {},
      });

      await newUser.save();
      console.log("New user saved to DB:", newUser);
    } catch (error) {
      console.error("Error saving user:", error);
      return new Response("Error saving user", { status: 500 });
      }
  }

  return new Response("Webhook processed successfully", { status: 200 });
}

modals

import mongoose from "mongoose";

const UserSchema = new mongoose.Schema({
  clerkId: { type: String, required: true, unique: true },
  email: { type: String, required: true },
  name: { type: String, required: true },
  metadata: { type: Object, default: {} },
});

export default mongoose.models.User || mongoose.model("User", UserSchema);

actions

"use server"
import User from "../modals/user.modal.js";
import { connect } from "../src/libs/db.js";

export async function createUser(user) {
    try {
        await connect();
        const newUser = new User(user);
        // Save the new user to the database
        const savedUser = await newUser.save();
        return JSON.parse(JSON.stringify(savedUser));
    }
    catch(err){
        console.error(err);
        return err;
    }
}

i tried triggering the webhook after creating new user but nothing happens i want to get all user metadata on my mongodb

Upvotes: 0

Views: 19

Answers (0)

Related Questions