Skip to content

armgit / dub

Public Imported from GitHub
0

The modern link attribution platform. Loved by world-class engineering teams at Twilio, Zillow, Jobber, Vercel, Raycast, and more.

Segment integration

Kiran K1ea53becdb11
diff --git a/apps/web/app/api/integrations/uninstall/route.ts b/apps/web/app/api/integrations/uninstall/route.ts
index b33dd3e2dc..336e381dfa 100644
--- a/apps/web/app/api/integrations/uninstall/route.ts
+++ b/apps/web/app/api/integrations/uninstall/route.ts
@@ -2,11 +2,12 @@ import { DubApiError } from "@/lib/api/errors";
import { withWorkspace } from "@/lib/auth";
import { uninstallSlackIntegration } from "@/lib/integrations/slack/uninstall";
import { prisma } from "@/lib/prisma";
+import { deleteWebhook } from "@/lib/webhook/api";
import { NextResponse } from "next/server";
// DELETE /api/integrations/uninstall - uninstall an installation by id
export const DELETE = withWorkspace(
- async ({ searchParams, session }) => {
+ async ({ searchParams, session, workspace }) => {
const { installationId } = searchParams;
const installation = await prisma.installedIntegration.findUnique({
@@ -48,6 +49,16 @@ export const DELETE = withWorkspace(
});
}
+ const credentials = installation?.credentials as any;
+
+ // if the integration has added a webhook, delete it
+ if ("webhookId" in credentials) {
+ await deleteWebhook({
+ webhookId: credentials.webhookId,
+ workspaceId: workspace.id,
+ });
+ }
+
return NextResponse.json({ id: installationId });
},
{
diff --git a/apps/web/app/api/webhooks/[webhookId]/route.ts b/apps/web/app/api/webhooks/[webhookId]/route.ts
index 093f1a487c..c2eb1961b1 100644
--- a/apps/web/app/api/webhooks/[webhookId]/route.ts
+++ b/apps/web/app/api/webhooks/[webhookId]/route.ts
@@ -3,7 +3,7 @@ import { linkCache } from "@/lib/api/links/cache";
import { parseRequestBody } from "@/lib/api/utils";
import { withWorkspace } from "@/lib/auth";
import { prisma } from "@/lib/prisma";
-import { updateWebhookStatusForWorkspace } from "@/lib/webhook/api";
+import { deleteWebhook } from "@/lib/webhook/api";
import { webhookCache } from "@/lib/webhook/cache";
import { transformWebhook } from "@/lib/webhook/transform";
import { isLinkLevelWebhook } from "@/lib/webhook/utils";
@@ -247,52 +247,11 @@ export const DELETE = withWorkspace(
async ({ workspace, params }) => {
const { webhookId } = params;
- const linkWebhooks = await prisma.linkWebhook.findMany({
- where: {
- webhookId,
- },
- select: {
- linkId: true,
- },
- });
-
- await prisma.webhook.delete({
- where: {
- id: webhookId,
- projectId: workspace.id,
- },
+ await deleteWebhook({
+ webhookId,
+ workspaceId: workspace.id,
});
- waitUntil(
- (async () => {
- const links = await prisma.link.findMany({
- where: {
- id: { in: linkWebhooks.map(({ linkId }) => linkId) },
- },
- include: {
- webhooks: {
- select: {
- webhookId: true,
- },
- },
- },
- });
-
- const formatedLinks = links.map((link) => {
- return {
- ...link,
- webhookIds: link.webhooks.map((webhook) => webhook.webhookId),
- };
- });
-
- await Promise.all([
- updateWebhookStatusForWorkspace({ workspace }),
- linkCache.mset(formatedLinks),
- webhookCache.delete(webhookId),
- ]);
- })(),
- );
-
return NextResponse.json({
id: webhookId,
});
diff --git a/apps/web/app/api/webhooks/route.ts b/apps/web/app/api/webhooks/route.ts
index 2e9dfd1858..ac9b68983a 100644
--- a/apps/web/app/api/webhooks/route.ts
+++ b/apps/web/app/api/webhooks/route.ts
@@ -98,7 +98,9 @@ export const POST = withWorkspace(
waitUntil(
Promise.allSettled([
- updateWebhookStatusForWorkspace({ workspace }),
+ updateWebhookStatusForWorkspace({
+ workspaceId: workspace.id,
+ }),
sendEmail({
email: session.user.email,
diff --git a/apps/web/app/app.dub.co/(dashboard)/[slug]/settings/integrations/[integrationSlug]/page-client.tsx b/apps/web/app/app.dub.co/(dashboard)/[slug]/settings/integrations/[integrationSlug]/page-client.tsx
index fe080759bd..8bb0543c99 100644
--- a/apps/web/app/app.dub.co/(dashboard)/[slug]/settings/integrations/[integrationSlug]/page-client.tsx
+++ b/apps/web/app/app.dub.co/(dashboard)/[slug]/settings/integrations/[integrationSlug]/page-client.tsx
@@ -1,6 +1,8 @@
"use client";
import { getIntegrationInstallUrl } from "@/lib/actions/get-integration-install-url";
+import { SegmentSettings } from "@/lib/integrations/segment/components/settings";
+import { SlackSettings } from "@/lib/integrations/slack/components/settings";
import useWorkspace from "@/lib/swr/use-workspace";
import { InstalledIntegrationInfoProps } from "@/lib/types";
import { useUninstallIntegrationModal } from "@/ui/modals/uninstall-integration-modal";
@@ -31,10 +33,11 @@ import {
cn,
formatDate,
getPrettyUrl,
+ SEGMENT_INTEGRATION_ID,
SLACK_INTEGRATION_ID,
STRIPE_INTEGRATION_ID,
} from "@dub/utils";
-import { BookOpenText, ChevronLeft, Trash, Webhook } from "lucide-react";
+import { BookOpenText, ChevronLeft, Trash } from "lucide-react";
import { useAction } from "next-safe-action/hooks";
import Link from "next/link";
import { useState } from "react";
@@ -64,9 +67,16 @@ export default function IntegrationPageClient({
const { UninstallIntegrationModal, setShowUninstallIntegrationModal } =
useUninstallIntegrationModal({
- integration: integration,
+ integration,
});
+ const integrationSettings = {
+ [SLACK_INTEGRATION_ID]: SlackSettings,
+ [SEGMENT_INTEGRATION_ID]: SegmentSettings,
+ };
+
+ const SettingsComponent = integrationSettings[integration.id] || null;
+
return (
<MaxWidthWrapper className="grid max-w-screen-lg gap-8">
{integration.installed && <UninstallIntegrationModal />}
@@ -290,38 +300,7 @@ export default function IntegrationPageClient({
)}
</div>
- {integration.installed && integration.id === SLACK_INTEGRATION_ID && (
- <SlackWebhookSettings webhookId={integration.credentials?.webhookId!} />
- )}
+ {SettingsComponent && <SettingsComponent {...integration} />}
</MaxWidthWrapper>
);
}
-
-const SlackWebhookSettings = ({ webhookId }: { webhookId: string }) => {
- const { slug } = useWorkspace();
-
- if (!webhookId) {
- return null;
- }
-
- return (
- <div className="w-full rounded-lg border border-gray-200 bg-white">
- <div className="flex items-center gap-x-2 border-b border-gray-200 px-6 py-4">
- <Webhook className="size-4" />
- <p className="text-sm font-medium text-gray-700">Configure webhook</p>
- </div>
-
- <div className="flex items-center justify-between p-6">
- <p className="text-sm leading-normal text-gray-600">
- Customize your Slack notifications by configuring webhook settings.
- You can choose which events to send to Slack and disable the
- notifications.
- </p>
-
- <Link href={`/${slug}/settings/webhooks/${webhookId}/edit`}>
- <Button className="w-fit" text="Update" variant="secondary" />
- </Link>
- </div>
- </div>
- );
-};
diff --git a/apps/web/app/app.dub.co/(dashboard)/[slug]/settings/integrations/[integrationSlug]/page.tsx b/apps/web/app/app.dub.co/(dashboard)/[slug]/settings/integrations/[integrationSlug]/page.tsx
index a7ec2f33b7..1c7f4560e8 100644
--- a/apps/web/app/app.dub.co/(dashboard)/[slug]/settings/integrations/[integrationSlug]/page.tsx
+++ b/apps/web/app/app.dub.co/(dashboard)/[slug]/settings/integrations/[integrationSlug]/page.tsx
@@ -1,6 +1,4 @@
-import { SlackCredential } from "@/lib/integrations/slack/type";
import { prisma } from "@/lib/prisma";
-import { SLACK_INTEGRATION_ID } from "@dub/utils";
import { notFound } from "next/navigation";
import IntegrationPageClient from "./page-client";
@@ -45,16 +43,10 @@ export default async function IntegrationPage({
}
const installed = integration.installations.length > 0;
- let credentials: Record<string, string> = {};
- if (integration.id === SLACK_INTEGRATION_ID && installed) {
- const slackCredentials = integration.installations[0]
- .credentials as SlackCredential;
-
- credentials = {
- webhookId: slackCredentials?.incomingWebhook?.webhookId,
- };
- }
+ const credentials = installed
+ ? integration.installations[0]?.credentials
+ : undefined;
return (
<IntegrationPageClient
diff --git a/apps/web/lib/actions/enable-disable-webhook.ts b/apps/web/lib/actions/enable-disable-webhook.ts
index ec82278fad..4a5c89d792 100644
--- a/apps/web/lib/actions/enable-disable-webhook.ts
+++ b/apps/web/lib/actions/enable-disable-webhook.ts
@@ -50,7 +50,9 @@ export const enableOrDisableWebhook = authActionClient
waitUntil(
(async () => {
await Promise.all([
- updateWebhookStatusForWorkspace({ workspace }),
+ updateWebhookStatusForWorkspace({
+ workspaceId: workspace.id,
+ }),
webhookCache.set(updatedWebhook),
]);
diff --git a/apps/web/lib/integrations/segment/components/settings.tsx b/apps/web/lib/integrations/segment/components/settings.tsx
new file mode 100644
index 0000000000..e36e1c9226
--- /dev/null
+++ b/apps/web/lib/integrations/segment/components/settings.tsx
@@ -0,0 +1,109 @@
+"use client";
+
+import useWorkspace from "@/lib/swr/use-workspace";
+import { InstalledIntegrationInfoProps } from "@/lib/types";
+import { Button, Webhook } from "@dub/ui";
+import { useAction } from "next-safe-action/hooks";
+import { useState } from "react";
+import { toast } from "sonner";
+import { installSegmentAction } from "../install";
+
+type SegmentSettingsProps = InstalledIntegrationInfoProps & {
+ credentials: {
+ writeKey?: string;
+ };
+};
+
+export const SegmentSettings = ({
+ installed,
+ credentials,
+}: SegmentSettingsProps) => {
+ const { id: workspaceId } = useWorkspace();
+ const [writeKey, setWriteKey] = useState(credentials?.writeKey);
+
+ const { executeAsync, isExecuting } = useAction(installSegmentAction, {
+ async onSuccess() {
+ toast.success("Segment integration enabled successfully.");
+ },
+ onError({ error }) {
+ toast.error(error.serverError || "Failed to enable Segment integration.");
+ },
+ });
+
+ const onSubmit = async (e: React.FormEvent<HTMLFormElement>) => {
+ e.preventDefault();
+
+ if (!workspaceId) {
+ return;
+ }
+
+ if (!writeKey) {
+ toast.error("Write key is required.");
+ return;
+ }
+
+ await executeAsync({
+ workspaceId,
+ writeKey,
+ });
+ };
+
+ return (
+ <div className="w-full rounded-lg border border-gray-200 bg-white">
+ <div className="flex items-center gap-x-2 border-b border-gray-200 px-6 py-4">
+ <Webhook className="size-4" />
+ <p className="text-sm font-medium text-gray-700">
+ Send events to Segment
+ </p>
+ </div>
+
+ <div className="p-6">
+ <p className="text-sm leading-normal text-gray-600">
+ To send click events to Segment, you need to add your Segment write
+ key below.{" "}
+ <a
+ href="https://segment.com/docs/connections/find-writekey/"
+ target="_blank"
+ rel="noopener noreferrer"
+ className="text-gray-500 underline underline-offset-4 hover:text-gray-700"
+ >
+ Learn about
+ </a>{" "}
+ how to locate your write key.
+ </p>
+
+ <form className="mt-4 flex items-end gap-2" onSubmit={onSubmit}>
+ <div className="flex-1">
+ <label htmlFor="writeKey" className="flex items-center space-x-2">
+ <h2 className="text-sm font-medium text-gray-900">
+ Segment write key
+ </h2>
+ </label>
+ <div className="relative mt-2 rounded-md shadow-sm">
+ <input
+ className="w-full rounded-md border-gray-300 text-gray-900 placeholder-gray-400 focus:border-gray-500 focus:outline-none focus:ring-gray-500 sm:text-sm"
+ placeholder="Enter your write key"
+ required
+ type="text"
+ autoComplete="off"
+ name="writeKey"
+ value={writeKey}
+ onChange={(e) => setWriteKey(e.target.value)}
+ readOnly={installed?.id ? true : false}
+ />
+ </div>
+ </div>
+
+ <Button
+ type="submit"
+ variant="primary"
+ text="Enable Segment"
+ className="w-fit"
+ loading={isExecuting}
+ disabled={installed?.id ? true : false || !writeKey}
+ />
+ </form>
+ </div>
+ </div>
+ );
+};
diff --git a/apps/web/lib/integrations/segment/install.ts b/apps/web/lib/integrations/segment/install.ts
new file mode 100644
index 0000000000..943ede9640
--- /dev/null
+++ b/apps/web/lib/integrations/segment/install.ts
@@ -0,0 +1,40 @@
+"use server";
+
+import { authActionClient } from "@/lib/actions/safe-action";
+import { addWebhook } from "@/lib/webhook/api";
+import { SEGMENT_INTEGRATION_ID } from "@dub/utils";
+import { revalidatePath } from "next/cache";
+import { z } from "zod";
+import { installIntegration } from "../install";
+
+const schema = z.object({
+ writeKey: z.string().min(1).max(40),
+ workspaceId: z.string(),
+});
+
+export const installSegmentAction = authActionClient
+ .schema(schema)
+ .action(async ({ parsedInput, ctx }) => {
+ const { workspace, user } = ctx;
+ const { writeKey } = parsedInput;
+
+ const webhook = await addWebhook({
+ name: "Segment",
+ url: "https://api.segment.io/v1/track",
+ triggers: ["link.clicked"],
+ workspace,
+ secret: writeKey, // TODO (Kiran): Might need rethink this
+ });
+
+ await installIntegration({
+ integrationId: SEGMENT_INTEGRATION_ID,
+ userId: user.id,
+ workspaceId: workspace.id,
+ credentials: {
+ writeKey,
+ webhookId: webhook.id,
+ },
+ });
+
+ revalidatePath(`/${workspace.slug}/settings/integrations/segment`);
+ });
diff --git a/apps/web/lib/integrations/segment/transform.ts b/apps/web/lib/integrations/segment/transform.ts
new file mode 100644
index 0000000000..81a15b7626
--- /dev/null
+++ b/apps/web/lib/integrations/segment/transform.ts
@@ -0,0 +1,107 @@
+import { ClickEventWebhookData } from "@/lib/webhook/types";
+
+export const formatEventForSegment = (data: ClickEventWebhookData) => {
+ const { click, link } = data;
+
+ return {
+ event: "Link clicked",
+ anonymousId: click.id,
+ context: {
+ link,
+ click,
+ campaign: {
+ ...(link.utm_campaign && { name: link.utm_campaign }),
+ ...(link.utm_source && { source: link.utm_source }),
+ ...(link.utm_medium && { medium: link.utm_medium }),
+ ...(link.utm_term && { term: link.utm_term }),
+ ...(link.utm_content && { content: link.utm_content }),
+ },
+ },
+ integrations: {
+ Dub: {
+ name: "Dub",
+ version: "1.0.0",
+ },
+ },
+ };
+};
+
+// {
+// "anonymousId": "507f191e810c19729de860ea",
+// "context": {
+// "active": true,
+// "app": {
+// "name": "InitechGlobal",
+// "version": "545",
+// "build": "3.0.1.545",
+// "namespace": "com.production.segment"
+// },
+
+// "ip": "8.8.8.8",
+// "library": {
+// "name": "analytics.js",
+// "version": "2.11.1"
+// },
+// "locale": "en-US",
+// "network": {
+// "bluetooth": false,
+// "carrier": "T-Mobile US",
+// "cellular": true,
+// "wifi": false
+// },
+// "os": {
+// "name": "iPhone OS",
+// "version": "8.1.3"
+// },
+// "page": {
+// "path": "/academy/",
+// "referrer": "",
+// "search": "",
+// "title": "Analytics Academy",
+// "url": "https://segment.com/academy/"
+// },
+// "referrer": {
+// "id": "ABCD582CDEFFFF01919",
+// "type": "dataxu"
+// },
+// "screen": {
+// "width": 320,
+// "height": 568,
+// "density": 2
+// },
+// "groupId": "12345",
+// "timezone": "Europe/Amsterdam",
+// "userAgent": "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/113.0.0.0 Safari/537.36",
+// "userAgentData": {
+// "brands": [
+// {
+// "brand": "Google Chrome",
+// "version": "113"
+// },
+// {
+// "brand": "Chromium",
+// "version": "113"
+// },
+// {
+// "brand": "Not-A.Brand",
+// "version": "24"
+// }
+// ],
+// "mobile": false,
+// "platform": "macOS"
+// }
+// },
+// "integrations": {
+// "All": true,
+// "Mixpanel": false,
+// "Salesforce": false
+// },
+// "event": "Report Submitted",
+// "messageId": "022bb90c-bbac-11e4-8dfc-aa07a5b093db",
+// "receivedAt": "2015-12-10T04:08:31.909Z",
+// "sentAt": "2015-12-10T04:08:31.581Z",
+// "timestamp": "2015-12-10T04:08:31.905Z",
+// "type": "track",
+// "userId": "97980cfea0067",
+// "version": 2
+// }
diff --git a/apps/web/lib/integrations/segment/utils.ts b/apps/web/lib/integrations/segment/utils.ts
new file mode 100644
index 0000000000..194af490e1
--- /dev/null
+++ b/apps/web/lib/integrations/segment/utils.ts
@@ -0,0 +1,5 @@
+export const createSegmentBasicAuthHeader = (writeKey: string) => {
+ const encoded = Buffer.from(`${writeKey}:`).toString("base64");
+
+ return `Basic ${encoded}`;
+};
diff --git a/apps/web/lib/integrations/slack/components/settings.tsx b/apps/web/lib/integrations/slack/components/settings.tsx
new file mode 100644
index 0000000000..a56c60d29c
--- /dev/null
+++ b/apps/web/lib/integrations/slack/components/settings.tsx
@@ -0,0 +1,46 @@
+"use client";
+
+import useWorkspace from "@/lib/swr/use-workspace";
+import { InstalledIntegrationInfoProps } from "@/lib/types";
+import { Button, Webhook } from "@dub/ui";
+import Link from "next/link";
+
+type SlackSettingsProps = InstalledIntegrationInfoProps & {
+ credentials: {
+ webhookId?: string;
+ };
+};
+
+export const SlackSettings = ({
+ installed,
+ credentials,
+}: SlackSettingsProps) => {
+ const { slug } = useWorkspace();
+
+ if (!installed || !credentials) {
+ return null;
+ }
+
+ const { webhookId } = credentials;
+
+ return (
+ <div className="w-full rounded-lg border border-gray-200 bg-white">
+ <div className="flex items-center gap-x-2 border-b border-gray-200 px-6 py-4">
+ <Webhook className="size-4" />
+ <p className="text-sm font-medium text-gray-700">Configure webhook</p>
+ </div>
+
+ <div className="flex items-center justify-between p-6">
+ <p className="text-sm leading-normal text-gray-600">
+ Customize your Slack notifications by configuring webhook settings.
+ You can choose which events to send to Slack and disable the
+ notifications.
+ </p>
+
+ <Link href={`/${slug}/settings/webhooks/${webhookId}/edit`}>
+ <Button className="w-fit" text="Update" variant="secondary" />
+ </Link>
+ </div>
+ </div>
+ );
+};
diff --git a/apps/web/lib/types.ts b/apps/web/lib/types.ts
index 9c85cd4c15..e2c68704b7 100644
--- a/apps/web/lib/types.ts
+++ b/apps/web/lib/types.ts
@@ -4,6 +4,7 @@ import { DirectorySyncProviders } from "@boxyhq/saml-jackson";
import {
Link,
PayoutStatus,
+ Prisma,
ProgramEnrollmentStatus,
Project,
SaleStatus,
@@ -286,7 +287,7 @@ export type InstalledIntegrationInfoProps = Pick<
image: string | null;
};
} | null;
- credentials?: Record<string, string>;
+ credentials?: Prisma.JsonValue;
};
export type WebhookTrigger = keyof typeof WEBHOOK_TRIGGER_DESCRIPTIONS;
diff --git a/apps/web/lib/webhook/api.ts b/apps/web/lib/webhook/api.ts
index cdcd1abb29..9787b613f2 100644
--- a/apps/web/lib/webhook/api.ts
+++ b/apps/web/lib/webhook/api.ts
@@ -12,6 +12,8 @@ import { waitUntil } from "@vercel/functions";
import { WebhookTrigger } from "../types";
import { createWebhookSecret } from "./secret";
+// TODO (Kiran): move the methods to individual files
+
export async function addWebhook({
name,
url,
@@ -102,23 +104,80 @@ export async function addWebhook({
}
export const updateWebhookStatusForWorkspace = async ({
- workspace,
+ workspaceId,
}: {
- workspace: Pick<Project, "id">;
+ workspaceId: string;
}) => {
const activeWebhooksCount = await prisma.webhook.count({
where: {
- projectId: workspace.id,
+ projectId: workspaceId,
disabledAt: null,
},
});
await prisma.project.update({
where: {
- id: workspace.id,
+ id: workspaceId,
},
data: {
webhookEnabled: activeWebhooksCount > 0,
},
});
};
+
+export const deleteWebhook = async ({
+ webhookId,
+ workspaceId,
+}: {
+ webhookId: string;
+ workspaceId: string;
+}) => {
+ const linkWebhooks = await prisma.linkWebhook.findMany({
+ where: {
+ webhookId,
+ },
+ select: {
+ linkId: true,
+ },
+ });
+
+ await prisma.webhook.delete({
+ where: {
+ id: webhookId,
+ projectId: workspaceId,
+ },
+ });
+
+ waitUntil(
+ (async () => {
+ const links = await prisma.link.findMany({
+ where: {
+ id: { in: linkWebhooks.map(({ linkId }) => linkId) },
+ },
+ include: {
+ webhooks: {
+ select: {
+ webhookId: true,
+ },
+ },
+ },
+ });
+
+ const formatedLinks = links.map((link) => {
+ return {
+ ...link,
+ webhookIds: link.webhooks.map((webhook) => webhook.webhookId),
+ };
+ });
+
+ await Promise.all([
+ updateWebhookStatusForWorkspace({
+ workspaceId,
+ }),
+
+ linkCache.mset(formatedLinks),
+ webhookCache.delete(webhookId),
+ ]);
+ })(),
+ );
+};
diff --git a/apps/web/lib/webhook/failure.ts b/apps/web/lib/webhook/failure.ts
index b4f182eb37..9e04d9c1a2 100644
--- a/apps/web/lib/webhook/failure.ts
+++ b/apps/web/lib/webhook/failure.ts
@@ -50,9 +50,7 @@ export const handleWebhookFailure = async (webhookId: string) => {
// Update the project webhookEnabled flag
updateWebhookStatusForWorkspace({
- workspace: {
- id: webhook.projectId,
- },
+ workspaceId: webhook.projectId,
}),
]);
}
diff --git a/apps/web/lib/webhook/qstash.ts b/apps/web/lib/webhook/qstash.ts
index e1094a3043..04d91f938f 100644
--- a/apps/web/lib/webhook/qstash.ts
+++ b/apps/web/lib/webhook/qstash.ts
@@ -2,6 +2,8 @@ import { qstash } from "@/lib/cron";
import { webhookPayloadSchema } from "@/lib/webhook/schemas";
import { APP_DOMAIN_WITH_NGROK } from "@dub/utils";
import { Webhook, WebhookReceiver } from "@prisma/client";
+import { formatEventForSegment } from "../integrations/segment/transform";
+import { createSegmentBasicAuthHeader } from "../integrations/segment/utils";
import { WebhookTrigger } from "../types";
import z from "../zod";
import { createWebhookSignature } from "./signature";
@@ -56,6 +58,13 @@ const publishWebhookEventToQStash = async ({
headers: {
"Dub-Signature": signature,
"Upstash-Hide-Headers": "true",
+
+ // Integration specific headers
+ ...(receiver === "segment" && {
+ "Upstash-Forward-Authorization": createSegmentBasicAuthHeader(
+ webhook.secret,
+ ),
+ }),
},
callback: callbackUrl.href,
failureCallback: callbackUrl.href,
@@ -76,9 +85,12 @@ const transformPayload = ({
payload: z.infer<typeof webhookPayloadSchema>;
receiver: WebhookReceiver;
}) => {
- if (receiver === "slack") {
- return generateSlackMessage(payload.event, payload.data);
+ switch (receiver) {
+ case "slack":
+ return generateSlackMessage(payload.event, payload.data);
+ case "segment":
+ return formatEventForSegment(payload.data);
+ default:
+ return payload;
}
-
- return payload;
};
diff --git a/apps/web/lib/webhook/utils.ts b/apps/web/lib/webhook/utils.ts
index fe30d40770..a16bb788a4 100644
--- a/apps/web/lib/webhook/utils.ts
+++ b/apps/web/lib/webhook/utils.ts
@@ -5,6 +5,7 @@ const webhookReceivers: Record<string, WebhookReceiver> = {
"hooks.zapier.com": "zapier",
"make.com": "make",
"hooks.slack.com": "slack",
+ "api.segment.io": "segment",
};
export const isLinkLevelWebhook = (webhook: Pick<Webhook, "triggers">) => {
diff --git a/apps/web/prisma/schema/webhook.prisma b/apps/web/prisma/schema/webhook.prisma
index 0d672bdbfe..6ef4e0aca2 100644
--- a/apps/web/prisma/schema/webhook.prisma
+++ b/apps/web/prisma/schema/webhook.prisma
@@ -3,6 +3,7 @@ enum WebhookReceiver {
zapier
make
slack
+ segment
}
model Webhook {
diff --git a/apps/web/ui/modals/uninstall-integration-modal.tsx b/apps/web/ui/modals/uninstall-integration-modal.tsx
index 79556c2dd1..4696556d58 100644
--- a/apps/web/ui/modals/uninstall-integration-modal.tsx
+++ b/apps/web/ui/modals/uninstall-integration-modal.tsx
@@ -90,6 +90,7 @@ function UninstallIntegrationModal({
},
).then(async (res) => {
if (res.status === 200) {
+ setShowUninstallIntegrationModal(false);
router.refresh();
toast.success("Successfully removed integration!");
} else {
diff --git a/apps/web/ui/webhooks/webhook-events.tsx b/apps/web/ui/webhooks/webhook-events.tsx
index eee7cf82eb..810299338c 100644
--- a/apps/web/ui/webhooks/webhook-events.tsx
+++ b/apps/web/ui/webhooks/webhook-events.tsx
@@ -35,8 +35,16 @@ const WebhookEvent = ({ event }: { event: WebhookEventProps }) => {
useEffect(() => {
if (highlighter) {
+ let responseBodyDecoded = event.response_body;
+
+ try {
+ responseBodyDecoded = JSON.parse(event.response_body);
+ } catch {
+ // If it's not JSON, just use the original response body
+ }
+
const responseBodyHtml = highlighter.codeToHtml(
- JSON.stringify(event.response_body, null, 2),
+ JSON.stringify(responseBodyDecoded, null, 2),
{
theme: "min-light",
lang: "json",
diff --git a/packages/utils/src/constants/integrations.ts b/packages/utils/src/constants/integrations.ts
index b09dabc288..755df9105e 100644
--- a/packages/utils/src/constants/integrations.ts
+++ b/packages/utils/src/constants/integrations.ts
@@ -1,2 +1,3 @@
export const SLACK_INTEGRATION_ID = "clzu59rx9000110bm5fnlzwuj";
export const STRIPE_INTEGRATION_ID = "clzra1ya60001wnj4a89zcg9h";
+export const SEGMENT_INTEGRATION_ID = "cm481uged0001eh6uotzmcphy";