rakibtweets / dev_overflow_nextjs13

Dev Overflow is a problem-solving community platform designed to enhance user engagement and streamline the job application process. Built with Next.js, Clerk, and MongoDB, this platform addresses real-world challenges by providing a user-friendly interface and efficient workflows.
https://dev-overflow-nextjs13-rakibtweets.vercel.app/
14 stars 6 forks source link

401 Unauthorised when processing a Clerk Webhook in Next.js #2

Open Abhijeet0230 opened 9 months ago

Abhijeet0230 commented 9 months ago

bro can u tell me how did u resolve this issue? 0

when i sync clerk data to my back end using webhook and do all steps i recive 401 error on vercel Log

this is app/api/webhook/route.ts

/ eslint-disable camelcase / import { Webhook } from "svix"; import { headers } from "next/headers"; import { WebhookEvent } from "@clerk/nextjs/server"; import { createUser, updateUser, deleteUser } from "@/lib/actions/user.action"; import { NextResponse } from "next/server";

export async function POST(req: Request) { // You can find this in the Clerk Dashboard -> Webhooks -> choose the webhook // TODO: add your webhook secret to .env.loca 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, }); }

// Get the event type const eventType = evt.type;

console.log({ eventType });

// Handle the event if (eventType === "user.created") { const { id, email_addresses, image_url, username, first_name, last_name } = evt.data;

// Create a new user in your database
const mongoUser = await createUser({
  clerkId: id,
  name: `${first_name}${last_name ? ` ${last_name}` : ""}`,
  username: username!,
  email: email_addresses[0].email_address,
  picture: image_url,
});

return NextResponse.json({ message: "OK", user: mongoUser });

}

if (eventType === "user.updated") { const { id, email_addresses, image_url, username, first_name, last_name } = evt.data;

// Update a user in database
const mongoUser = await updateUser({
  clerkId: id,
  updateData: {
    name: `${first_name}${last_name ? ` ${last_name}` : ""}`,
    username: username!,
    email: email_addresses[0].email_address,
    picture: image_url,
  },
  path: `/profile/${id}`,
});

return NextResponse.json({ message: "OK", user: mongoUser });

}

if (eventType === "user.deleted") { const { id } = evt.data;

// Delete a user in database
const deletedUser = await deleteUser({ clerkId: id! });

return NextResponse.json({ message: "OK", user: deletedUser });

}

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

middleware.ts

import { authMiddleware } from "@clerk/nextjs";

export default authMiddleware({ publicRoutes: [ "/", "/api/webhook", "question/:id", "/tags", "/tags/:id", "/profile/:id", "/community", "/jops", ], ignoredRoutes: ["/api/webhook", "/api/chatgpt"], });

export const config = { matcher: ["/((?!.+\.[\w]+$|_next).)", "/", "/(api|trpc)(.)"], };

after deploy my app in vercel and copy url on clerk endpoint then clerk faild and i get 401 [post] api/webhook

what shoud i do to solve this 401 warnning

i try to change ignoredRoutes once i add it and delete it, once change webhooksecret in .envlocal and add env variables on vercel and re-deploy and nothing change

Screenshot 2024-01-09 at 1 52 48 AM
rakibtweets commented 9 months ago

add webhook url endpoint in clerk account. Hopefully it will solve your issue

Abhijeet0230 commented 9 months ago

Bro I have added the webhook url endpoint in clerk webhooks....then also it is showing the same warning....please help ....they r no resources also on internet which could help

On Tue, 9 Jan, 2024, 8:14 pm Rakib Hasan, @.***> wrote:

add webhook url endpoint in clerk account. Hopefully it will solve your issue

— Reply to this email directly, view it on GitHub https://github.com/rakibtweets/dev_overflow_nextjs13/issues/2#issuecomment-1883180619, or unsubscribe https://github.com/notifications/unsubscribe-auth/AY2RZVHF74MXHTPQMFU2KEDYNVJV5AVCNFSM6AAAAABBSAX6IWVHI2DSMVQWIX3LMV43OSLTON2WKQ3PNVWWK3TUHMYTQOBTGE4DANRRHE . You are receiving this because you authored the thread.Message ID: @.***>

Abhijeet0230 commented 9 months ago

Bro in the endpoint ...we just have to add /api/webhook na?

On Tue, 9 Jan, 2024, 8:21 pm Abhijeet Singh, @.***> wrote:

Bro I have added the webhook url endpoint in clerk webhooks....then also it is showing the same warning....please help ....they r no resources also on internet which could help

On Tue, 9 Jan, 2024, 8:14 pm Rakib Hasan, @.***> wrote:

add webhook url endpoint in clerk account. Hopefully it will solve your issue

— Reply to this email directly, view it on GitHub https://github.com/rakibtweets/dev_overflow_nextjs13/issues/2#issuecomment-1883180619, or unsubscribe https://github.com/notifications/unsubscribe-auth/AY2RZVHF74MXHTPQMFU2KEDYNVJV5AVCNFSM6AAAAABBSAX6IWVHI2DSMVQWIX3LMV43OSLTON2WKQ3PNVWWK3TUHMYTQOBTGE4DANRRHE . You are receiving this because you authored the thread.Message ID: @.***>

rakibtweets commented 9 months ago

hen also it is showing the same warning....please help ....they r no resources also on internet which could help

I think you have done it wrong way,, let me guide you step 1: Deploy your branch to vercel step 2: Get the webhook url and add to clerk webhook step 3: select filter events like user event (user.created, user.delete, user.updates). Hope this will work for you. for more details follow this links

  1. clerk webhook
  2. Sync Clerk Data
Abhijeet0230 commented 9 months ago

Bro is there anyway I can talk to u?? ....I literally have done the same things ...same steps .....but still it is giving 401 error.....

On Tue, 9 Jan, 2024, 8:39 pm Rakib Hasan, @.***> wrote:

hen also it is showing the same warning....please help ....they r no resources also on internet which could help

I think you have done it wrong way,, let me guide you step 1: Deploy your branch to vercel step 2: Get the webhook url and add to clerk webhook step 3: select filter events like user event (user.created, user.delete, user.updates). Hope this will work for you. for more details follow this links

  1. clerk webhook https://clerk.com/docs/integrations/webhooks?_gl=1*1wowqw8*_ga*MzAxODAxMzY4LjE2OTE0MjkyMzY.*_ga_1WMF5X234K*MTcwNDgxMTEzOC4xNy4xLjE3MDQ4MTIwMzAuMC4wLjA.*_gcl_au*MTIwMzU0OTg5Ny4xNjk5MjYxNDMz
  2. Sync Clerk Data https://clerk.com/docs/users/sync-data

— Reply to this email directly, view it on GitHub https://github.com/rakibtweets/dev_overflow_nextjs13/issues/2#issuecomment-1883228207, or unsubscribe https://github.com/notifications/unsubscribe-auth/AY2RZVE4XU4URWXR7DOZ3NDYNVMSPAVCNFSM6AAAAABBSAX6IWVHI2DSMVQWIX3LMV43OSLTON2WKQ3PNVWWK3TUHMYTQOBTGIZDQMRQG4 . You are receiving this because you authored the thread.Message ID: @.***>

aayush-1412 commented 8 months ago

hey @Abhijeet0230 I was facing the same issue but was able to resolve it. Here is what you can try-

  1. Turn off the vercel authentication from the project settings.
  2. Add "/api/webhook" in publicRoutes in middleware.ts and remove it from ignoredRoutes.
HFaustt commented 7 months ago

i've been stuck on this for two days now, I'm not getting any POST requests when i check my vercel logs, and I made sure that I've done all the steps correctly...

HFaustt commented 7 months ago

@aayush-1412 I just tried your suggestion and it worked... man I've been stuck on this for too long, many thanks!!