Kekoo
Kekoo

Reputation: 43

504 Gateway Timeout when try to POST request to api route in NEXT.JS application deployed on VERCEL

when try to post a request to api/webhooks I get 504 error gateway timeout and on vercel log I get Task timed out after 10.02 seconds

this code is a webhook between my clerk and my MongoDB

[POST] [middleware: "middleware"] /api/webhooks status=200 then get [POST] /api/webhooks status=504

api/webhooks/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 { NextRequest, NextResponse } from "next/server";

export async function POST(req: NextRequest) {
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 NextResponse.json({ message: "OK" });
}

middleware.ts

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

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

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

photo_1 photo_2photo_3photo_4 what should I do on Vercel or on my code? before I had a 401 unauthorized but when turn of vercel authorization its gone and 504 get

Upvotes: 3

Views: 671

Answers (2)

After adding access from anywhere in mongoDB cluster this issue was also solved.

In cluster, click on NETWORK ACCESS > ADD IP ADDRESS > ALLOW ACCESS FROM ANYWHERE

It will add this ip: 0.0.0.0/0 and that's all.

example

Upvotes: 0

otariuS
otariuS

Reputation: 11

I had the same issue and the problem was that I forgot to add access from anywhere in MongoDB hope that's the case

Upvotes: 1

Related Questions