The modern link attribution platform. Loved by world-class engineering teams at Twilio, Zillow, Jobber, Vercel, Raycast, and more.
TypeScript clickhousemysqlnextjsopen-sourceplanetscaleprismatailwindcsstinybirdtypescriptupstashvercel
Queue HubSpot webhook events to QStash for async processing (#3785)
Kiran K7eeabf81c363
diff --git a/apps/web/app/(ee)/api/hubspot/webhook/process/route.ts b/apps/web/app/(ee)/api/hubspot/webhook/process/route.tsnew file mode 100644index 0000000000..b55bff9a0c--- /dev/null+++ b/apps/web/app/(ee)/api/hubspot/webhook/process/route.ts@@ -0,0 +1,168 @@+import { captureWebhookLog } from "@/lib/api-logs/capture-webhook-log";+import { handleAndReturnErrorResponse } from "@/lib/api/errors";+import { withAxiom } from "@/lib/axiom/server";+import { verifyQstashSignature } from "@/lib/cron/verify-qstash";+import { hubSpotOAuthProvider } from "@/lib/integrations/hubspot/oauth";+import {+ hubSpotSettingsSchema,+ hubSpotWebhookSchema,+} from "@/lib/integrations/hubspot/schema";+import { trackHubSpotLeadEvent } from "@/lib/integrations/hubspot/track-lead";+import { trackHubSpotSaleEvent } from "@/lib/integrations/hubspot/track-sale";+import { WorkspaceProps } from "@/lib/types";+import { prisma } from "@dub/prisma";+import { logAndRespond } from "../../../cron/utils";++// POST /api/hubspot/webhook/process – process individual webhook event+export const POST = withAxiom(async (req) => {+ const startTime = Date.now();++ let body: any;+ let workspace:+ | Pick<WorkspaceProps, "id" | "stripeConnectId" | "webhookEnabled">+ | undefined;++ try {+ const rawBody = await req.text();++ await verifyQstashSignature({+ req,+ rawBody,+ });++ body = JSON.parse(rawBody);++ const { objectTypeId, portalId, subscriptionType } =+ hubSpotWebhookSchema.parse(body);++ // Find the installation+ const installation = await prisma.installedIntegration.findFirst({+ where: {+ integration: {+ slug: "hubspot",+ },+ credentials: {+ path: "$.hub_id",+ equals: portalId,+ },+ },+ include: {+ project: {+ select: {+ id: true,+ stripeConnectId: true,+ webhookEnabled: true,+ },+ },+ },+ });++ if (!installation) {+ return logAndRespond(+ `[HubSpot] Installation is not found for portalId ${portalId}.`,+ );+ }++ workspace = installation.project;++ // Refresh the access token if needed+ const authToken =+ await hubSpotOAuthProvider.refreshTokenForInstallation(installation);++ if (!authToken) {+ return logAndRespond(+ `[HubSpot] Authentication token is not found or valid for portalId ${portalId}.`,+ );+ }++ const settings = hubSpotSettingsSchema.parse(installation.settings ?? {});++ console.log("[HubSpot] Integration settings", settings);++ let response = "";++ // Contact events+ if (objectTypeId === "0-1") {+ const isContactCreated = subscriptionType === "object.creation";++ const isLifecycleStageChanged =+ subscriptionType === "object.propertyChange" &&+ settings.leadTriggerEvent === "lifecycleStageReached";++ if (isContactCreated || isLifecycleStageChanged) {+ response = await trackHubSpotLeadEvent({+ payload: body,+ workspace,+ authToken,+ settings,+ });+ } else {+ response = `Skipping contact event: subscriptionType "${subscriptionType}" does not match the configured leadTriggerEvent "${settings.leadTriggerEvent}".`;+ }+ }++ // Deal event+ else if (objectTypeId === "0-3") {+ const isDealCreated =+ subscriptionType === "object.creation" &&+ settings.leadTriggerEvent === "dealCreated";++ const isDealUpdated = subscriptionType === "object.propertyChange";++ // Track the final lead event+ if (isDealCreated) {+ response = await trackHubSpotLeadEvent({+ payload: body,+ workspace,+ authToken,+ settings,+ });+ }++ // Track the sale event when deal is closed won+ else if (isDealUpdated) {+ response = await trackHubSpotSaleEvent({+ payload: body,+ workspace,+ authToken,+ settings,+ });+ }+ }++ // Unknown object type+ else {+ response = `Unknown objectTypeId ${objectTypeId}.`;+ }++ await captureWebhookLog({+ workspaceId: workspace.id,+ method: "POST",+ path: "/hubspot/webhook",+ statusCode: 200,+ duration: Date.now() - startTime,+ requestBody: body,+ responseBody: response,+ userAgent: req.headers.get("user-agent"),+ });++ return logAndRespond(response);+ } catch (error) {+ const response = handleAndReturnErrorResponse(error);++ if (workspace) {+ await captureWebhookLog({+ workspaceId: workspace.id,+ method: "POST",+ path: "/hubspot/webhook",+ statusCode: response.status,+ duration: Date.now() - startTime,+ requestBody: body,+ responseBody: response,+ userAgent: req.headers.get("user-agent"),+ });+ }++ return response;+ }+});diff --git a/apps/web/app/(ee)/api/hubspot/webhook/route.ts b/apps/web/app/(ee)/api/hubspot/webhook/route.tsindex 7750415416..d0540b1efb 100644--- a/apps/web/app/(ee)/api/hubspot/webhook/route.ts+++ b/apps/web/app/(ee)/api/hubspot/webhook/route.ts@@ -1,26 +1,16 @@-import { captureWebhookLog } from "@/lib/api-logs/capture-webhook-log";import { DubApiError, handleAndReturnErrorResponse } from "@/lib/api/errors";import { withAxiom } from "@/lib/axiom/server";-import { hubSpotOAuthProvider } from "@/lib/integrations/hubspot/oauth";-import {- hubSpotSettingsSchema,- hubSpotWebhookSchema,-} from "@/lib/integrations/hubspot/schema";-import { trackHubSpotLeadEvent } from "@/lib/integrations/hubspot/track-lead";-import { trackHubSpotSaleEvent } from "@/lib/integrations/hubspot/track-sale";-import { prisma } from "@dub/prisma";-import { waitUntil } from "@vercel/functions";+import { qstash } from "@/lib/cron";+import { APP_DOMAIN_WITH_NGROK } from "@dub/utils";import crypto from "crypto";-import { NextResponse } from "next/server";+import { logAndRespond } from "../../cron/utils";const HUBSPOT_CLIENT_SECRET = process.env.HUBSPOT_CLIENT_SECRET || "";// POST /api/hubspot/webhook – listen to webhook events from Hubspotexport const POST = withAxiom(async (req) => {- const startTime = Date.now();-try {- const rawPayload = await req.text();+ const rawBody = await req.text();const signature = req.headers.get("X-HubSpot-Signature");// Verify webhook signature@@ -39,7 +29,7 @@ export const POST = withAxiom(async (req) => {}// Create expected hash: client_secret + request_body- const sourceString = HUBSPOT_CLIENT_SECRET + rawPayload;+ const sourceString = HUBSPOT_CLIENT_SECRET + rawBody;const expectedHash = crypto.createHash("sha256").update(sourceString)@@ -53,163 +43,27 @@ export const POST = withAxiom(async (req) => {});}- const payload = JSON.parse(rawPayload) as any[];-- // HS send multiple events in the same request- // so we need to process each event individually- const results = await Promise.allSettled(payload.map(processWebhookEvent));-- const responseBody = { message: "Webhook received." };- const duration = Date.now() - startTime;-- // Collect log entries from fulfilled results, including failures- const logEntries: Array<{- workspaceId: string;- statusCode: number;- responseBody: unknown;- requestBody: unknown;- }> = [];-- for (let i = 0; i < results.length; i++) {- const r = results[i];- if (r.status !== "fulfilled" || !r.value) {- continue;- }-- const { workspaceId, errorResponse } = r.value;-- logEntries.push({- workspaceId,- statusCode: errorResponse ? errorResponse.status : 200,- responseBody: errorResponse ?? responseBody,- requestBody: payload[i],- });- }+ const events = JSON.parse(rawBody) as any[];+ const finalEvents = Array.isArray(events) ? events : [events];++ // HubSpot can send multiple events in a single request, so we fan them out+ // to QStash and process each event independently in /api/hubspot/webhook/process.+ // This keeps the webhook handler fast and ensures a slow/failing event doesn't+ // block or fail the rest of the batch.+ const qstashResponse = await qstash.batchJSON(+ finalEvents.map((event) => ({+ url: `${APP_DOMAIN_WITH_NGROK}/api/hubspot/webhook/process`,+ body: event,+ })),+ );- waitUntil(- Promise.allSettled(- logEntries.map((entry) =>- captureWebhookLog({- workspaceId: entry.workspaceId,- method: req.method,- path: "/hubspot/webhook",- statusCode: entry.statusCode,- duration,- requestBody: entry.requestBody,- responseBody: entry.responseBody,- userAgent: req.headers.get("user-agent"),- }),- ),- ),+ console.log(+ `[hubspot/webhook] Enqueued ${finalEvents.length} webhook events to be processed.`,+ qstashResponse,);- return NextResponse.json(responseBody);+ return logAndRespond("Webhook received.");} catch (error) {return handleAndReturnErrorResponse(error);}});--// Process individual event, returns workspaceId and error response if failed-async function processWebhookEvent(event: any) {- const { objectTypeId, portalId, subscriptionType } =- hubSpotWebhookSchema.parse(event);-- // Find the installation- const installation = await prisma.installedIntegration.findFirst({- where: {- integration: {- slug: "hubspot",- },- credentials: {- path: "$.hub_id",- equals: portalId,- },- },- include: {- project: true,- },- });-- if (!installation) {- console.error(- `[HubSpot] Installation is not found for portalId ${portalId}.`,- );- return;- }-- const { project: workspace } = installation;-- // Refresh the access token if needed- const authToken =- await hubSpotOAuthProvider.refreshTokenForInstallation(installation);-- if (!authToken) {- console.error(- `[HubSpot] Authentication token is not found or valid for portalId ${portalId}.`,- );- return;- }-- const settings = hubSpotSettingsSchema.parse(installation.settings ?? {});-- console.log("[HubSpot] Event", event);- console.log("[HubSpot] Integration settings", settings);-- try {- // Contact events- if (objectTypeId === "0-1") {- const isContactCreated = subscriptionType === "object.creation";-- const isLifecycleStageChanged =- subscriptionType === "object.propertyChange" &&- settings.leadTriggerEvent === "lifecycleStageReached";-- if (isContactCreated || isLifecycleStageChanged) {- await trackHubSpotLeadEvent({- payload: event,- workspace,- authToken,- settings,- });- }- }-- // Deal event- if (objectTypeId === "0-3") {- const isDealCreated =- subscriptionType === "object.creation" &&- settings.leadTriggerEvent === "dealCreated";-- const isDealUpdated = subscriptionType === "object.propertyChange";-- // Track the final lead event- if (isDealCreated) {- await trackHubSpotLeadEvent({- payload: event,- workspace,- authToken,- settings,- });- }-- // Track the sale event when deal is closed won- else if (isDealUpdated) {- await trackHubSpotSaleEvent({- payload: event,- workspace,- authToken,- settings,- });- }- }- } catch (error) {- return {- workspaceId: workspace.id,- errorResponse: handleAndReturnErrorResponse(error),- };- }-- return {- workspaceId: workspace.id,- };-}diff --git a/apps/web/lib/integrations/hubspot/track-lead.ts b/apps/web/lib/integrations/hubspot/track-lead.tsindex ab619a2ab9..99b14be0ac 100644--- a/apps/web/lib/integrations/hubspot/track-lead.ts+++ b/apps/web/lib/integrations/hubspot/track-lead.ts@@ -1,7 +1,6 @@import { trackLead } from "@/lib/api/conversions/track-lead";import { TrackLeadResponse, WorkspaceProps } from "@/lib/types";import { prisma } from "@dub/prisma";-import { waitUntil } from "@vercel/functions";import * as z from "zod/v4";import { HubSpotAuthToken, HubSpotContact } from "../types";import { HubSpotApi } from "./api";@@ -30,14 +29,13 @@ export const trackHubSpotLeadEvent = async ({const contactInfo = await hubSpotApi.getContact(objectId);if (!contactInfo) {- return;+ return `No contact info found for contact ${objectId}.`;}const { properties } = contactInfo;if (!properties.dub_id) {- console.error(`[HubSpot] No dub_id found for contact ${objectId}.`);- return;+ return `No dub_id found for contact ${objectId}.`;}const customerName =@@ -56,16 +54,14 @@ export const trackHubSpotLeadEvent = async ({});if (trackLeadResult) {- waitUntil(- _updateHubSpotContact({- contact: contactInfo,- trackLeadResult,- hubSpotApi,- }),- );+ await updateHubSpotContact({+ contact: contactInfo,+ trackLeadResult,+ hubSpotApi,+ });}- return trackLeadResult;+ return `Deferred lead tracked for contact ${objectId}.`;}// Track the final lead event@@ -78,7 +74,7 @@ export const trackHubSpotLeadEvent = async ({const deal = await hubSpotApi.getDeal(objectId);if (!deal) {- return;+ return `No deal found for deal ${objectId}.`;}const { properties, associations } = deal;@@ -87,7 +83,7 @@ export const trackHubSpotLeadEvent = async ({const contact = associations?.contacts?.results?.[0];if (!contact) {- return;+ return `No contact found for deal ${objectId}.`;}// HubSpot doesn't return the contact properties in the deal associations,@@ -95,7 +91,7 @@ export const trackHubSpotLeadEvent = async ({const contactInfo = await hubSpotApi.getContact(contact.id);if (!contactInfo) {- return;+ return `No contact info found for contact ${contact.id}.`;}const customer = await prisma.customer.findFirst({@@ -109,10 +105,7 @@ export const trackHubSpotLeadEvent = async ({});if (!customer) {- console.error(- `[HubSpot] No customer found for contact ID ${contactInfo.id} or email ${contactInfo.properties.email}.`,- );- return;+ return `No customer found for contact ID ${contactInfo.id} or email ${contactInfo.properties.email}.`;}const trackLeadResult = await trackLead({@@ -127,16 +120,14 @@ export const trackHubSpotLeadEvent = async ({});if (trackLeadResult) {- waitUntil(- _updateHubSpotContact({- contact: contactInfo,- trackLeadResult,- hubSpotApi,- }),- );+ await updateHubSpotContact({+ contact: contactInfo,+ trackLeadResult,+ hubSpotApi,+ });}- return trackLeadResult;+ return `Lead tracked for deal ${objectId}.`;}// Track the final lead event@@ -147,30 +138,25 @@ export const trackHubSpotLeadEvent = async ({settings.leadTriggerEvent === "lifecycleStageReached") {if (!settings.leadLifecycleStageId) {- console.error(`[HubSpot] leadLifecycleStageId is not set.`);- return;+ return `leadLifecycleStageId is not set.`;}const contactInfo = await hubSpotApi.getContact(objectId);if (!contactInfo) {- return;+ return `No contact info found for contact ${objectId}.`;}if (contactInfo.properties.lifecyclestage !== settings.leadLifecycleStageId) {- console.error(- `[HubSpot] Unknown contact lifecyclestage ${contactInfo.properties.lifecyclestage}. Expected ${settings.leadLifecycleStageId}.`,- );- return;+ return `Unknown contact lifecyclestage ${contactInfo.properties.lifecyclestage}. Expected ${settings.leadLifecycleStageId}.`;}const { properties } = contactInfo;if (!properties.dub_id) {- console.error(`[HubSpot] No dub_id found for contact ${objectId}.`);- return;+ return `No dub_id found for contact ${objectId}.`;}const customer = await prisma.customer.findFirst({@@ -184,10 +170,7 @@ export const trackHubSpotLeadEvent = async ({});if (!customer) {- console.error(- `[HubSpot] No customer found for contact ID ${contactInfo.id} or email ${contactInfo.properties.email}.`,- );- return;+ return `No customer found for contact ID ${contactInfo.id} or email ${contactInfo.properties.email}.`;}const trackLeadResult = await trackLead({@@ -202,21 +185,21 @@ export const trackHubSpotLeadEvent = async ({});if (trackLeadResult) {- waitUntil(- _updateHubSpotContact({- contact: contactInfo,- trackLeadResult,- hubSpotApi,- }),- );+ await updateHubSpotContact({+ contact: contactInfo,+ trackLeadResult,+ hubSpotApi,+ });}- return trackLeadResult;+ return `Lead tracked for contact ${objectId}.`;}++ return `Unknown event: objectTypeId "${objectTypeId}" and subscriptionType "${subscriptionType}".`;};// Update the HubSpot contact with `dub_link` and `dub_partner_email`-export const _updateHubSpotContact = async ({+export const updateHubSpotContact = async ({hubSpotApi,contact,trackLeadResult,@@ -254,6 +237,9 @@ export const _updateHubSpotContact = async ({}if (Object.keys(properties).length === 0) {+ console.log(+ `[HubSpot] No properties to update for contact ${contact.id}. Skipping update.`,+ );return;}diff --git a/apps/web/lib/integrations/hubspot/track-sale.ts b/apps/web/lib/integrations/hubspot/track-sale.tsindex 5e782db5e8..3228450568 100644--- a/apps/web/lib/integrations/hubspot/track-sale.ts+++ b/apps/web/lib/integrations/hubspot/track-sale.ts@@ -21,22 +21,15 @@ export const trackHubSpotSaleEvent = async ({hubSpotSaleEventSchema.parse(payload);if (subscriptionType !== "object.propertyChange") {- console.log(`[HubSpot] Unknown subscriptionType ${subscriptionType}`);- return;+ return `Unknown subscriptionType ${subscriptionType}.`;}if (propertyName !== "dealstage") {- console.log(- `[HubSpot] Unknown propertyName ${propertyName}. Expected dealstage.`,- );- return;+ return `Unknown propertyName ${propertyName}. Expected dealstage.`;}if (propertyValue !== settings.closedWonDealStageId) {- console.error(- `[HubSpot] Unknown propertyValue ${propertyValue}. Expected ${settings.closedWonDealStageId}.`,- );- return;+ return `Unknown propertyValue ${propertyValue}. Expected ${settings.closedWonDealStageId}.`;}const hubSpotApi = new HubSpotApi({@@ -46,22 +39,20 @@ export const trackHubSpotSaleEvent = async ({const deal = await hubSpotApi.getDeal(objectId);if (!deal) {- return;+ return `No deal found for deal ${objectId}`;}const { id: dealId, properties, associations } = deal;if (!properties.amount) {- console.error(`[HubSpot] Amount is not set for deal ${dealId}`);- return;+ return `Amount is not set for deal ${dealId}`;}// Find the contact associated with the dealconst contact = associations?.contacts?.results?.[0];if (!contact) {- console.error(`[HubSpot] No contact associated with deal ${dealId}`);- return;+ return `No contact associated with deal ${dealId}`;}// HubSpot doesn't return the contact properties in the deal associations,@@ -69,7 +60,7 @@ export const trackHubSpotSaleEvent = async ({const contactInfo = await hubSpotApi.getContact(contact.id);if (!contactInfo) {- return;+ return `No contact info found for contact ${contact.id}`;}const customer = await prisma.customer.findFirst({@@ -83,13 +74,10 @@ export const trackHubSpotSaleEvent = async ({});if (!customer) {- console.error(- `[HubSpot] No customer found for contact ID ${contactInfo.id} or email ${contactInfo.properties.email}.`,- );- return;+ return `No customer found for contact ID ${contactInfo.id} or email ${contactInfo.properties.email}.`;}- return await trackSale({+ await trackSale({customerExternalId: customer.externalId!,amount: Number(properties.amount) * 100,eventName: `${properties.dealname} ${properties.dealstage}`,@@ -97,5 +85,8 @@ export const trackHubSpotSaleEvent = async ({invoiceId: dealId,workspace,rawBody: deal,+ metadata: {},});++ return `Sale tracked for deal ${dealId}.`;};