The modern link attribution platform. Loved by world-class engineering teams at Twilio, Zillow, Jobber, Vercel, Raycast, and more.
TypeScript clickhousemysqlnextjsopen-sourceplanetscaleprismatailwindcsstinybirdtypescriptupstashvercel
Improve efficiency of the webhook processing
Kiran Kc6772d2c5447
diff --git a/apps/web/app/api/cron/shopify/order-paid/route.ts b/apps/web/app/api/cron/shopify/order-paid/route.tsindex 8e96582a3b..fb609460ec 100644--- a/apps/web/app/api/cron/shopify/order-paid/route.ts+++ b/apps/web/app/api/cron/shopify/order-paid/route.ts@@ -36,24 +36,34 @@ export async function POST(req: Request) {"clickId",);+ // clickId is empty, order is not from a Dub link+ if (clickId === "") {+ await redis.del(`shopify:checkout:${checkoutToken}`);++ return new Response(+ `[Shopify] Order is not from a Dub link. Skipping...`,+ );+ }++ // clickId is found, process the order for the new customer+ else if (clickId) {+ await processOrder({+ event,+ workspaceId,+ clickId,+ });++ return new Response("[Shopify] Order event processed successfully.");+ }+// Wait for the click event to come from Shopify pixel- if (!clickId) {+ else {throw new DubApiError({code: "bad_request",message:"[Shopify] Click event not found. Waiting for Shopify pixel event...",});}-- await processOrder({- event,- workspaceId,- clickId,- });-- await redis.del(`shopify:checkout:${checkoutToken}`);-- return new Response("[Shopify] Order event processed successfully.");} catch (error) {return handleAndReturnErrorResponse(error);}diff --git a/apps/web/app/api/shopify/integration/webhook/app-uninstalled.ts b/apps/web/app/api/shopify/integration/webhook/app-uninstalled.tsindex 156d23e6e5..a85c73e432 100644--- a/apps/web/app/api/shopify/integration/webhook/app-uninstalled.ts+++ b/apps/web/app/api/shopify/integration/webhook/app-uninstalled.ts@@ -13,4 +13,6 @@ export async function appUninstalled({ shopDomain }: { shopDomain: string }) {}),redis.del(`shopify:shop:${shopDomain}`),]);++ return "[Shopify] App Uninstalled received.";}diff --git a/apps/web/app/api/shopify/integration/webhook/customers-data-request.ts b/apps/web/app/api/shopify/integration/webhook/customers-data-request.tsindex 1cc1c20f9d..c78fee458b 100644--- a/apps/web/app/api/shopify/integration/webhook/customers-data-request.ts+++ b/apps/web/app/api/shopify/integration/webhook/customers-data-request.ts@@ -31,4 +31,6 @@ export async function customersDataRequest({ event }: { event: any }) {Orders Requested: ${ordersRequested.join(", ")}`,}),);++ return "[Shopify] Customer Data Request received.";}diff --git a/apps/web/app/api/shopify/integration/webhook/customers-redact.ts b/apps/web/app/api/shopify/integration/webhook/customers-redact.tsindex c12ff0c7f9..d67e27ae0f 100644--- a/apps/web/app/api/shopify/integration/webhook/customers-redact.ts+++ b/apps/web/app/api/shopify/integration/webhook/customers-redact.ts@@ -31,4 +31,6 @@ export async function customersRedact({ event }: { event: any }) {Orders to Redact: ${ordersToRedact.join(", ")}`,}),);++ return "[Shopify] Customer Redacted request received.";}diff --git a/apps/web/app/api/shopify/integration/webhook/order-paid.ts b/apps/web/app/api/shopify/integration/webhook/order-paid.tsindex 7dc5e193bf..5020083e14 100644--- a/apps/web/app/api/shopify/integration/webhook/order-paid.ts+++ b/apps/web/app/api/shopify/integration/webhook/order-paid.ts@@ -34,7 +34,7 @@ export async function orderPaid({customerId: customer.id,});- return;+ return "[Shopify] Order event processed successfully.";}// Check the cache to see the pixel event for this checkout token exist before publishing the event to the queue@@ -43,31 +43,40 @@ export async function orderPaid({"clickId",);+ // clickId is empty, order is not from a Dub link+ if (clickId === "") {+ await redis.del(`shopify:checkout:${checkoutToken}`);++ return "[Shopify] Order is not from a Dub link. Skipping...";+ }+// clickId is found, process the order for the new customer- if (clickId) {+ else if (clickId) {await processOrder({event,workspaceId,clickId,});- await redis.del(`shopify:checkout:${checkoutToken}`);-- return;+ return "[Shopify] Order event processed successfully.";}- // Wait for the pixel event to come in so that we can decide if the order is from a Dub link or not- await redis.hset(`shopify:checkout:${checkoutToken}`, {- order: event,- });+ // clickId is not found, we need to wait for the pixel event to come in so that we can decide if the order is from a Dub link or not+ else {+ await redis.hset(`shopify:checkout:${checkoutToken}`, {+ order: event,+ });- await qstash.publishJSON({- url: `${APP_DOMAIN_WITH_NGROK}/api/cron/shopify/order-paid`,- body: {- checkoutToken,- workspaceId,- },- retries: 5,- delay: 3,- });+ await qstash.publishJSON({+ url: `${APP_DOMAIN_WITH_NGROK}/api/cron/shopify/order-paid`,+ body: {+ checkoutToken,+ workspaceId,+ },+ retries: 5,+ delay: 3,+ });++ return "[Shopify] clickId not found, waiting for pixel event to arrive...";+ }}diff --git a/apps/web/app/api/shopify/integration/webhook/route.ts b/apps/web/app/api/shopify/integration/webhook/route.tsindex 687e3f2bbc..653884ccb6 100644--- a/apps/web/app/api/shopify/integration/webhook/route.ts+++ b/apps/web/app/api/shopify/integration/webhook/route.ts@@ -1,7 +1,6 @@import { prisma } from "@dub/prisma";import { log } from "@dub/utils";import crypto from "crypto";-import { NextResponse } from "next/server";import { appUninstalled } from "./app-uninstalled";import { customersDataRequest } from "./customers-data-request";import { customersRedact } from "./customers-redact";@@ -61,31 +60,33 @@ export const POST = async (req: Request) => {);}+ let response = "OK";+try {switch (topic) {case "orders/paid":- await orderPaid({+ response = await orderPaid({event,workspaceId: workspace.id,});break;case "customers/data_request":- await customersDataRequest({+ response = await customersDataRequest({event,});break;case "customers/redact":- await customersRedact({+ response = await customersRedact({event,});break;case "shop/redact":- await shopRedact({+ response = await shopRedact({event,});break;case "app/uninstalled":- await appUninstalled({+ response = await appUninstalled({shopDomain,});break;@@ -96,10 +97,8 @@ export const POST = async (req: Request) => {type: "errors",});- return new Response(- `[Shopify] Webhook handler failed. View logs`,- );+ return new Response(`[Shopify] Webhook handler failed. View logs`);}- return NextResponse.json("OK");+ return new Response(response);};diff --git a/apps/web/app/api/shopify/integration/webhook/shop-redact.ts b/apps/web/app/api/shopify/integration/webhook/shop-redact.tsindex 26fb13141a..ca4220b7c9 100644--- a/apps/web/app/api/shopify/integration/webhook/shop-redact.ts+++ b/apps/web/app/api/shopify/integration/webhook/shop-redact.ts@@ -17,4 +17,6 @@ export async function shopRedact({ event }: { event: any }) {text: `Shop Redacted request received for shop: ${shopDomain}`,}),);++ return "[Shopify] Shop Redacted request received.";}diff --git a/apps/web/app/api/track/shopify/route.ts b/apps/web/app/api/shopify/pixel/route.tssimilarity index 52%rename from apps/web/app/api/track/shopify/route.tsrename to apps/web/app/api/shopify/pixel/route.tsindex b447233234..42eb06f383 100644--- a/apps/web/app/api/track/shopify/route.ts+++ b/apps/web/app/api/shopify/pixel/route.ts@@ -1,8 +1,9 @@import { DubApiError, handleAndReturnErrorResponse } from "@/lib/api/errors";import { parseRequestBody } from "@/lib/api/utils";import { getClickEvent } from "@/lib/tinybird";-import { redis } from "@/lib/upstash";-import { waitUntil } from "@vercel/functions";+import { ratelimit, redis } from "@/lib/upstash";+import { LOCALHOST_IP } from "@dub/utils";+import { ipAddress, waitUntil } from "@vercel/functions";import { NextResponse } from "next/server";export const runtime = "edge";@@ -13,33 +14,41 @@ const CORS_HEADERS = {"Access-Control-Allow-Headers": "Content-Type, Authorization",};-// TODO:-// Add rate limiting-// Finalize the endpoint (Maybe move to /api/shopify/pixel)--// POST /api/track/shopify – Handle the Shopify Pixel events+// POST /api/shopify/pixel – Handle the Shopify Pixel eventsexport const POST = async (req: Request) => {try {const { clickId, checkoutToken } = await parseRequestBody(req);- if (!clickId || !checkoutToken) {+ if (!checkoutToken) {throw new DubApiError({code: "bad_request",- message: "Missing clickId or checkoutToken",+ message: "checkoutToken is required.",+ });+ }++ // Rate limit the request+ const ip = process.env.VERCEL === "1" ? ipAddress(req) : LOCALHOST_IP;+ const { success } = await ratelimit().limit(`shopify-track-pixel:${ip}`);++ if (!success) {+ throw new DubApiError({+ code: "rate_limit_exceeded",+ message: "Don't DDoS me pls 🥺",});}- const clickEvent = await getClickEvent({ clickId });+ // Validate the clickId if provided+ if (clickId) {+ const clickEvent = await getClickEvent({ clickId });- if (!clickEvent || clickEvent.data.length === 0) {- return new Response(- `[Shopify] Click event not found for clickId: ${clickId}`,- );+ if (!clickEvent || clickEvent.data.length === 0) {+ return new Response(`Click event not found for clickId: ${clickId}`);+ }}waitUntil(redis.hset(`shopify:checkout:${checkoutToken}`, {- clickId,+ clickId: clickId || "",}),);diff --git a/apps/web/lib/integrations/shopify/process-order.ts b/apps/web/lib/integrations/shopify/process-order.tsindex 01154bc84c..244a18e6fe 100644--- a/apps/web/lib/integrations/shopify/process-order.ts+++ b/apps/web/lib/integrations/shopify/process-order.ts@@ -9,6 +9,7 @@ import {recordLead,recordSale,} from "@/lib/tinybird";+import { redis } from "@/lib/upstash";import z from "@/lib/zod";import { leadEventSchemaTB } from "@/lib/zod/schemas/leads";import { prisma } from "@dub/prisma";@@ -101,6 +102,7 @@ async function createSale({const amount = Number(orderData.current_subtotal_price) * 100;const currency = orderData.currency;const invoiceId = orderData.confirmation_number;+ const checkoutToken = orderData.checkout_token;const { link_id: linkId, click_id: clickId } = leadData;@@ -161,6 +163,8 @@ async function createSale({},},}),++ redis.del(`shopify:checkout:${checkoutToken}`),]);// for program links@@ -277,9 +281,9 @@ export async function processOrder({workspaceId,customerId,});- }- return new Response("[Shopify] Order event processed successfully.");+ return;+ }} catch (error) {return handleAndReturnErrorResponse(error);}