### Install All Project Dependencies
Source: https://github.com/dubinc/dub/blob/main/packages/hubspot-app/README.md
Installs all necessary dependencies for the project within the HubSpot environment.
```bash
pnpm hs project install-deps
```
--------------------------------
### Install @dub/embed-core Package
Source: https://github.com/dubinc/dub/blob/main/packages/embeds/core/README.md
Use this command to install the package. Ensure you have pnpm installed.
```bash
pnpm i @dub/embed-core
```
--------------------------------
### Install @dub/ui Package
Source: https://github.com/dubinc/dub/blob/main/packages/ui/README.md
Use this command to install the @dub/ui package into your project. Ensure you have pnpm installed.
```bash
pnpm i @dub/ui
```
--------------------------------
### Start Local Development
Source: https://github.com/dubinc/dub/blob/main/packages/hubspot-app/README.md
Sets up a test environment and starts local development for the HubSpot project.
```bash
pnpm hs project dev
```
--------------------------------
### Install Dependencies
Source: https://github.com/dubinc/dub/blob/main/packages/hubspot-app/README.md
Use this command to install project dependencies using pnpm.
```bash
pnpm install
```
--------------------------------
### Install @dub/utils Package
Source: https://github.com/dubinc/dub/blob/main/packages/utils/README.md
Use this command to install the @dub/utils package in your project.
```bash
pnpm i @dub/utils
```
--------------------------------
### Start Stripe App Locally
Source: https://github.com/dubinc/dub/blob/main/packages/stripe-app/README.md
Use this command to run the Stripe app in your local development environment. Ensure you have completed the initial setup steps.
```bash
stripe apps start
```
--------------------------------
### Install @dub/better-auth Plugin
Source: https://github.com/dubinc/dub/blob/main/apps/web/guides/better-auth.md
Install the @dub/better-auth plugin using npm, yarn, pnpm, or bun.
```bash
npm install @dub/better-auth
```
```bash
yarn add @dub/better-auth
```
```bash
pnpm add @dub/better-auth
```
```bash
bun add @dub/better-auth
```
--------------------------------
### Install @dub/embed-react Package
Source: https://github.com/dubinc/dub/blob/main/packages/embeds/react/README.md
Use this command to install the @dub/embed-react package. Ensure you have pnpm installed.
```bash
pnpm i @dub/embed-react
```
--------------------------------
### Get CLI help
Source: https://github.com/dubinc/dub/blob/main/packages/cli/README.md
Display help information for all available commands or a specific command.
```bash
pnpm start help
```
--------------------------------
### Install Playwright Browsers
Source: https://github.com/dubinc/dub/blob/main/apps/web/playwright/README.md
Installs the Chromium browser for Playwright. Run this command once.
```sh
pnpm --filter web exec playwright install chromium
```
--------------------------------
### Making an Authenticated GET Request with Node.js
Source: https://github.com/dubinc/dub/blob/main/apps/web/guides/rest-api.md
Example of how to make a GET request to the /links endpoint using Node.js fetch. Requires the Authorization header for authentication.
```javascript
const response = await fetch("https://api.dub.co/links", {
method: "GET",
headers: {
Authorization: "Bearer dub_xxxxxx",
},
});
const data = await response.json();
```
--------------------------------
### Install Appwrite Node.js SDK
Source: https://github.com/dubinc/dub/blob/main/apps/web/guides/appwrite.md
Install the Appwrite Node.js SDK using npm. This is required for interacting with Appwrite services in your Next.js application.
```bash
npm i node-appwrite
```
--------------------------------
### Verify CLI installation
Source: https://github.com/dubinc/dub/blob/main/packages/cli/README.md
Check if the dub-cli has been installed and linked correctly by running the version command.
```bash
dub -v
```
--------------------------------
### Authentication and Example Request
Source: https://github.com/dubinc/dub/blob/main/apps/web/guides/rest-api.md
Details on how to authenticate API requests using a Bearer token and an example of fetching links.
```APIDOC
## Authentication
Authentication to Dub's API is performed via the `Authorization` header with a Bearer token. To authenticate, you need to include the `Authorization` header with the word `Bearer` followed by your API key in your requests.
```bash
Authorization: Bearer dub_xxxxxx
```
## GET /links
### Description
Fetches a list of all links associated with your account.
### Method
GET
### Endpoint
https://api.dub.co/links
### Request Example
```javascript
const response = await fetch("https://api.dub.co/links", {
method: "GET",
headers: {
Authorization: "Bearer dub_xxxxxx",
},
});
const data = await response.json();
```
### Response
#### Success Response (200)
- **links** (array) - A list of link objects.
- **count** (integer) - The total number of links.
#### Response Example
```json
{
"links": [
{
"id": "clt8z7f5o000008l4f8z8f8z8",
"url": "https://example.com",
"slug": "example",
"clicks": 100,
"createdAt": "2023-01-01T12:00:00.000Z",
"updatedAt": "2023-01-01T12:00:00.000Z"
}
],
"count": 1
}
```
```
--------------------------------
### Install Dub Analytics Package
Source: https://github.com/dubinc/dub/blob/main/apps/web/guides/react.md
Use npm to add the `@dub/analytics` package to your project dependencies.
```bash
npm install @dub/analytics
```
--------------------------------
### Start MailHog Service
Source: https://github.com/dubinc/dub/blob/main/apps/web/playwright/README.md
Starts the MailHog service using Docker Compose, which is used for email verification during the signup process.
```sh
docker-compose -f apps/web/docker-compose.yml up -d mailhog
```
--------------------------------
### Run Dev Seed Script
Source: https://github.com/dubinc/dub/blob/main/README.md
Use this script to seed the database with development data. It can be run with or without truncating existing data. Ensure you are in the 'apps/web' directory and have pnpm installed.
```bash
cd apps/web
pnpm run script dev/seed
```
```bash
cd apps/web
pnpm run script dev/seed --truncate
```
--------------------------------
### Add Dub Analytics Script to Framer Head
Source: https://github.com/dubinc/dub/blob/main/apps/web/guides/framer.md
Paste this script into the 'Start of head tag' section in your Framer project's General settings to enable Dub analytics.
```html
```
--------------------------------
### Append Dub ID to Stripe Payment Link URL
Source: https://github.com/dubinc/dub/blob/main/apps/web/guides/stripe-payment-links.md
When redirecting users to a marketing site, install the @dub/analytics SDK. Then, append the `dub_id` value as the `client_reference_id` parameter to your Stripe payment links, prefixed with `dub_id_`.
```javascript
https://buy.stripe.com/xxxxxx?client_reference_id=dub_id_xxxxxxxxxxxxxx
```
--------------------------------
### Appwrite User Sign-up and Dub Lead Tracking
Source: https://github.com/dubinc/dub/blob/main/apps/web/guides/appwrite.md
Use this server action to create a new user account with Appwrite, establish a session, and track leads with Dub if a 'dub_id' cookie is present. Ensure Appwrite admin client and Dub integration are set up.
```javascript
import { ID } from "node-appwrite";
import { createAdminClient, getLoggedInUser } from "@/lib/server/appwrite";
import { cookies } from "next/headers";
import { redirect } from "next/navigation";
import { addDubLead } from "@/lib/server/dub";
async function signUpWithEmail(formData: any) {
"use server";
// Get sign up info from form
const email = formData.get("email");
const password = formData.get("password");
const name = formData.get("name");
// Create account and session using Appwrite
const { account } = await createAdminClient();
const user = await account.create(ID.unique(), email, password, name);
const session = await account.createEmailPasswordSession(email, password);
(await cookies()).set("my-custom-session", session.secret, {
path: "/",
httpOnly: true,
sameSite: "strict",
secure: true,
});
// Check if Dub ID is present in cookies and track lead if found
const dub_id = (await cookies()).get("dub_id")?.value;
if (dub_id) {
addDubLead(user, dub_id);
(await cookies()).delete("dub_id");
}
// Redirect to success page
redirect("/auth/success");
}
export default async function SignUpPage() {
// Verify active user session and redirect to success page if found
const user = await getLoggedInUser();
if (user) redirect("/auth/success");
return (
<>
>
);
}
```
--------------------------------
### Configure Environment Variables for Appwrite and Dub
Source: https://github.com/dubinc/dub/blob/main/apps/web/guides/appwrite.md
Set up necessary environment variables for Appwrite endpoint, project ID, API key, and Dub API key. These are crucial for authentication and connection.
```bash
NEXT_PUBLIC_APPWRITE_ENDPOINT=https://cloud.appwrite.io/v1
NEXT_PUBLIC_APPWRITE_PROJECT=
NEXT_APPWRITE_KEY=
NEXT_DUB_API_KEY=
```
--------------------------------
### Run E2E Tests (Headed)
Source: https://github.com/dubinc/dub/blob/main/apps/web/playwright/README.md
Executes E2E tests with the browser visible. Ensure the dev server is running.
```sh
pnpm --filter web test:e2e:headed
```
--------------------------------
### Navigate to CLI directory
Source: https://github.com/dubinc/dub/blob/main/packages/cli/README.md
Change directory to the 'cli' folder within the cloned repository to access CLI commands.
```bash
cd packages/cli
```
--------------------------------
### Upload Project to HubSpot
Source: https://github.com/dubinc/dub/blob/main/packages/hubspot-app/README.md
Uploads the current project to your HubSpot account. Replace `` with your actual account ID.
```bash
pnpm hs project upload --account=
```
--------------------------------
### Initialize Dub Referral Embed
Source: https://github.com/dubinc/dub/blob/main/packages/embeds/core/src/example/index.html
Initialize the Dub embed by providing the root DOM element and your embed token. Ensure the DOM is fully loaded before initialization.
```javascript
document.addEventListener("DOMContentLoaded", () => {
const embed = Dub.init({
root: document.getElementById("root"),
token: "dub_embed_", // Add your token here
});
});
```
--------------------------------
### Create Appwrite Admin Client
Source: https://github.com/dubinc/dub/blob/main/apps/web/guides/appwrite.md
Initialize an Appwrite client with administrative privileges using an API key. This client is used for server-side operations requiring elevated permissions.
```javascript
"use server";
import { Client, Account } from "node-appwrite";
import { cookies } from "next/headers";
export async function createAdminClient() {
const client = new Client()
.setEndpoint(process.env.NEXT_PUBLIC_APPWRITE_ENDPOINT as string)
.setProject(process.env.NEXT_PUBLIC_APPWRITE_PROJECT as string)
.setKey(process.env.NEXT_APPWRITE_KEY as string);
return {
get account() {
return new Account(client);
},
};
}
```
--------------------------------
### Build CLI package
Source: https://github.com/dubinc/dub/blob/main/packages/cli/README.md
Build the CLI package for production or testing. This command compiles the project without watch mode.
```bash
pnpm build
```
--------------------------------
### Implement `trackLead` Server Action
Source: https://github.com/dubinc/dub/blob/main/apps/web/guides/clerk.md
This server action handles tracking lead conversion events. It reads the `dub_id` cookie, sends the lead event to Dub, updates the user's metadata in Clerk, and clears the `dub_id` cookie.
```javascript
"use server";
import { dub } from "@/lib/dub";
import { clerkClient } from "@clerk/nextjs/server";
import { cookies } from "next/headers";
export async function trackLead({
id,
name,
email,
avatar,
}: {
id: string;
name?: string | null;
email?: string | null;
avatar?: string | null;
}) {
try {
const cookieStore = await cookies();
const dubId = cookieStore.get("dub_id")?.value;
if (dubId) {
// Send lead event to Dub
await dub.track.lead({
clickId: dubId,
eventName: "Sign Up",
customerExternalId: id,
customerName: name,
customerEmail: email,
customerAvatar: avatar,
});
// Delete the dub_id cookie
cookieStore.set("dub_id", "", {
expires: new Date(0),
});
}
const clerk = await clerkClient();
await clerk.users.updateUser(id, {
publicMetadata: {
dubClickId: dubId || "n/a",
},
});
return { ok: true };
} catch (error) {
console.error("Error in trackLead:", error);
return { ok: false, error: (error as Error).message };
}
}
```
--------------------------------
### Run E2E Tests (Headless)
Source: https://github.com/dubinc/dub/blob/main/apps/web/playwright/README.md
Executes E2E tests in headless mode, which is the default behavior. Ensure the dev server is running.
```sh
pnpm --filter web test:e2e
```
--------------------------------
### Run CLI command
Source: https://github.com/dubinc/dub/blob/main/packages/cli/README.md
Execute an available CLI command. Replace '[command]' with the desired command, e.g., 'shorten', 'links', etc.
```bash
pnpm start [command]
```
--------------------------------
### Initialize Dub Analytics in React Root Layout
Source: https://github.com/dubinc/dub/blob/main/apps/web/guides/react.md
Import and render the `` component from `@dub/analytics/react` within your root layout component to track conversions. This is particularly useful for frameworks like Next.js.
```jsx
import { Analytics as DubAnalytics } from '@dub/analytics/react';
export default function RootLayout({
children,
}: Readonly<{
children: React.ReactNode;
}>) {
return (
{children}
);
}
```
--------------------------------
### Configure NextAuth signIn Event for Lead Tracking
Source: https://github.com/dubinc/dub/blob/main/apps/web/guides/next-auth.md
Use the `signIn` event in NextAuth to detect new users. If a `dub_id` cookie exists, track a lead event with Dub and then delete the cookie. This associates new sign-ups with their original referral source.
```javascript
// app/api/auth/[...nextauth]/options.ts
import type { NextAuthOptions } from "next-auth";
import { cookies } from "next/headers";
import { dub } from "@/lib/dub";
export const authOptions: NextAuthOptions = {
...otherAuthOptions, // your other NextAuth options
events: {
async signIn(message) {
// if it's a new sign up
if (message.isNewUser) {
// check if dub_id cookie is present
const dub_id = cookies().get("dub_id")?.value;
if (dub_id) {
// send lead event to Dub
await dub.track.lead({
clickId: dub_id,
eventName: "Sign Up",
customerExternalId: user.id,
customerName: user.name,
customerEmail: user.email,
customerAvatar: user.image,
});
// delete the dub_id cookie
cookies().set("dub_id", "", {
expires: new Date(0),
});
}
}
},
},
};
```
--------------------------------
### Link CLI globally
Source: https://github.com/dubinc/dub/blob/main/packages/cli/README.md
Link the locally built CLI package globally on your system. This allows you to run 'dub' commands from any directory.
```bash
npm link
```
--------------------------------
### Run E2E Tests (Interactive UI Mode)
Source: https://github.com/dubinc/dub/blob/main/apps/web/playwright/README.md
Executes E2E tests in interactive UI mode, allowing for real-time interaction and debugging. Ensure the dev server is running.
```sh
pnpm --filter web test:e2e:ui
```
--------------------------------
### Track Lead Event with Segment Node.js SDK
Source: https://github.com/dubinc/dub/blob/main/apps/web/guides/segment-track-lead.md
Use this snippet to track a 'Sign Up' event for a user. Ensure the `clickId` is retrieved from cookies and included in the traits for proper forwarding to Dub. Requires the `@segment/analytics-node` SDK.
```javascript
import { Analytics } from "@segment/analytics-node";
const segment = new Analytics({
writeKey: "",
});
const cookieStore = await cookies();
const clickId = cookieStore.get("dub_id")?.value;
segment.track({
userId: id,
event: "Sign Up",
context: {
traits: {
name,
email,
avatar,
clickId,
},
},
integrations: {
All: true,
},
});
```
--------------------------------
### Configure E2E Environment Variables
Source: https://github.com/dubinc/dub/blob/main/apps/web/playwright/README.md
Sets essential environment variables in `apps/web/.env` for E2E tests, including partner credentials, SMTP settings for MailHog, and the Playwright base URL.
```sh
# Required for login tests (seeded user)
E2E_PARTNER_EMAIL=partner1@dub-internal-test.com
E2E_PARTNER_PASSWORD=password
# SMTP must point to MailHog — signup tests read OTP emails from it
SMTP_HOST=localhost
SMTP_PORT=1025
# RESEND_API_KEY must NOT be set, otherwise emails go to Resend instead of MailHog
# Optional — defaults to http://partners.localhost:8888
PLAYWRIGHT_BASE_URL=http://partners.localhost:8888
```
--------------------------------
### Environment Variables for Clerk and Dub
Source: https://github.com/dubinc/dub/blob/main/apps/web/guides/clerk.md
Set these environment variables in your application to authenticate with Clerk and Dub. Obtain your Clerk publishable and secret keys from the Clerk dashboard and your Dub API key from d.to.
```bash
NEXT_PUBLIC_CLERK_PUBLISHABLE_KEY=your_publishable_key
CLERK_SECRET_KEY=your_secret_key
DUB_API_KEY=your_api_key
```
--------------------------------
### Track Sale with Dub TypeScript SDK
Source: https://github.com/dubinc/dub/blob/main/apps/web/guides/manual-track-sale.md
Use the Dub TypeScript SDK in Node.js to track a sale event. Ensure the DUB_API_KEY environment variable is set or provide the token directly. The amount should be in cents.
```typescript
import { Dub } from "dub";
const dub = new Dub({
// optional, defaults to the DUB_API_KEY environment variable
token: process.env.DUB_API_KEY,
});
await dub.track.sale({
customerExternalId: "cus_oFUYbZYqHFR0knk0MjsMC6b0",
amount: 3000, // sale amount in cents
currency: "usd",
paymentProcessor: "stripe",
eventName: "Invoice paid",
invoiceId: "INV_1234567890",
});
```
--------------------------------
### Track Lead Conversion in Auth0 afterCallback
Source: https://github.com/dubinc/dub/blob/main/apps/web/guides/auth0.md
Implement lead tracking logic within the `afterCallback` function. This snippet checks for new users, looks for the `dub_id` cookie, sends lead data to Dub if found, and then removes the cookie. Ensure `dub` is imported and configured.
```javascript
import { handleAuth, handleCallback, type Session } from "@auth0/nextjs-auth0";
import { cookies } from "next/headers";
import { dub } from "@/lib/dub";
const afterCallback = async (req: Request, session: Session) => {
const userExists = await getUser(session.user.email);
if (!userExists) {
createUser(session.user);
// check if dub_id cookie is present
const clickId = cookies().get("dub_id")?.value;
if (clickId) {
// send lead event to Dub
await dub.track.lead({
clickId,
eventName: "Sign Up",
customerExternalId: session.user.id,
customerName: session.user.name,
customerEmail: session.user.email,
customerAvatar: session.user.image,
});
// delete the dub_id cookie
cookies().set("dub_id", "", {
expires: new Date(0),
});
}
return session;
}
};
export default handleAuth({
callback: handleCallback({ afterCallback }),
});
```
--------------------------------
### Build CLI in watch mode
Source: https://github.com/dubinc/dub/blob/main/packages/cli/README.md
Build the CLI package in watch mode for development. This command automatically recompiles changes as you make them.
```bash
pnpm dev
```
--------------------------------
### Configure Better Auth with Dub Analytics
Source: https://github.com/dubinc/dub/blob/main/apps/web/guides/better-auth.md
Add the dubAnalytics plugin to your better-auth configuration. Ensure you have initialized the Dub client and imported necessary modules.
```typescript
import { dubAnalytics } from "@dub/better-auth";
import { betterAuth } from "better-auth";
import { Dub } from "dub";
const dub = new Dub();
export const auth = betterAuth({
plugins: [
dubAnalytics({
dubClient: dub,
}),
],
});
```
--------------------------------
### Authentication Header Format
Source: https://github.com/dubinc/dub/blob/main/apps/web/guides/rest-api.md
To authenticate with Dub's API, include the Authorization header with 'Bearer' followed by your API key.
```bash
Authorization: Bearer dub_xxxxxx
```
--------------------------------
### Create Stripe Customer with Dub Metadata
Source: https://github.com/dubinc/dub/blob/main/apps/web/guides/stripe-customers.md
Use this snippet when creating a new Stripe customer to include the user's unique ID and the Dub click event ID in the metadata. This is useful for initial customer onboarding.
```javascript
import { stripe } from "@/lib/stripe";
const user = {
id: "user_123",
email: "user@example.com",
teamId: "team_xxxxxxxxx",
};
const dub_id = req.headers.get("dub_id");
await stripe.customers.create({
email: user.email,
name: user.name,
metadata: {
dubCustomerExternalId: user.id,
dubClickId: dub_id,
},
});
```
--------------------------------
### Track Lead with Dub TypeScript SDK
Source: https://github.com/dubinc/dub/blob/main/apps/web/guides/manual-track-lead.md
Use the Dub TypeScript SDK to track lead events in Node.js. Ensure the DUB_API_KEY environment variable is set or provide the token directly.
```typescript
import {
Dub
} from "dub";
const dub = new Dub({
// optional, defaults to the DUB_API_KEY environment variable
token: process.env.DUB_API_KEY,
});
await dub.track.lead({
clickId: "rLnWe1uz9t282v7g",
eventName: "Sign up",
customerExternalId: "cus_oFUYbZYqHFR0knk0MjsMC6b0",
customerName: "John Doe",
customerEmail: "john.doe@example.com",
customerAvatar: "https://example.com/avatar.png",
});
```
--------------------------------
### List Connected Accounts
Source: https://github.com/dubinc/dub/blob/main/packages/hubspot-app/README.md
Lists all HubSpot accounts that are currently connected to the project.
```bash
pnpm hs account list
```
--------------------------------
### Run dub CLI command
Source: https://github.com/dubinc/dub/blob/main/packages/cli/README.md
Execute a dub CLI command after it has been globally linked. Replace '[command]' with the desired command.
```bash
dub [command]
```
--------------------------------
### Create Appwrite Session Client for SSR
Source: https://github.com/dubinc/dub/blob/main/apps/web/guides/appwrite.md
Create a client instance for Appwrite sessions, essential for Server-Side Rendering (SSR) applications. This function retrieves session information from cookies.
```javascript
"use server";
import { Client, Account } from "node-appwrite";
import { cookies } from "next/headers";
export async function createSessionClient() {
const client = new Client()
.setEndpoint(process.env.NEXT_PUBLIC_APPWRITE_ENDPOINT as string)
.setProject(process.env.NEXT_PUBLIC_APPWRITE_PROJECT as string);
const session = (await cookies()).get("my-custom-session");
if (!session || !session.value) {
throw new Error("No session");
}
client.setSession(session.value);
return {
get account() {
return new Account(client);
},
};
}
```
--------------------------------
### Implement `trackLead` API Route
Source: https://github.com/dubinc/dub/blob/main/apps/web/guides/clerk.md
An alternative to the server action, this API route handles lead tracking. It reads the `dub_id` cookie from the request, sends the lead event to Dub, updates Clerk user metadata, and clears the `dub_id` cookie in the response.
```javascript
// This is an API route
import { NextRequest, NextResponse } from "next/server";
export async function POST(req: NextRequest) {
// read dub_id from the request cookies
const dubId = req.cookies.get("dub_id")?.value;
if (dubId) {
// Send lead event to Dub
await dub.track.lead({
clickId: dubId,
eventName: "Sign Up",
customerExternalId: id,
customerName: name,
customerEmail: email,
customerAvatar: avatar,
});
}
const clerk = await clerkClient();
await clerk.users.updateUser(id, {
publicMetadata: {
dubClickId: dubId || "n/a",
},
});
const res = NextResponse.json({ ok: true });
// Delete the dub_id cookie
res.cookies.set("dub_id", "", {
expires: new Date(0),
});
return res;
}
```
--------------------------------
### Add New Feature
Source: https://github.com/dubinc/dub/blob/main/packages/hubspot-app/README.md
Use this command to add a new feature to the HubSpot app.
```bash
pnpm hs project add
```
--------------------------------
### Extend @dub/analytics with Clerk's useUser Hook
Source: https://github.com/dubinc/dub/blob/main/apps/web/guides/clerk.md
This client-side component extends the @dub/analytics package to track lead events using Clerk's `useUser` hook. It sends user details to a server action upon initial load if the user's Dub ID hasn't been persisted.
```javascript
"use client";
import { trackLead } from "@/actions/track-lead";
import { useUser } from "@clerk/nextjs";
import { Analytics, AnalyticsProps } from "@dub/analytics/react";
import { useEffect } from "react";
export function DubAnalytics(props: AnalyticsProps) {
const { user } = useUser();
useEffect(() => {
if (!user || user.publicMetadata.dubClickId) return;
// if the user is loaded but hasn't been persisted to Dub yet, track the lead event
trackLead({
id: user.id,
name: user.fullName!,
email: user.primaryEmailAddress?.emailAddress,
avatar: user.imageUrl,
}).then(async (res) => {
if (res.ok) await user.reload();
else console.error(res.error);
});
// you can also use an API route instead of a server action
/*
fetch("/api/track-lead", {
method: "POST",
body: JSON.stringify({
id: user.id,
name: user.fullName,
email: user.primaryEmailAddress?.emailAddress,
avatar: user.imageUrl,
}),
}).then(res => {
if (res.ok) await user.reload();
else console.error(res.statusText);
});
*/
}, [user]);
return ;
}
```
--------------------------------
### Track Lead Conversion in Supabase Auth Callback
Source: https://github.com/dubinc/dub/blob/main/apps/web/guides/supabase.md
This JavaScript code snippet, intended for a Next.js API route, handles the Supabase authentication callback. It checks for a `dub_id` cookie and if the user is newly created. If both conditions are met, it tracks a lead event using `dub.track.lead` and deletes the cookie. Ensure `dub` is imported from '@/lib/dub' and Supabase client is set up.
```javascript
// app/api/auth/callback/route.ts
import { dub } from "@/lib/dub";
import { createClient } from "@/lib/supabase/server";
import { waitUntil } from "@vercel/functions";
import { cookies } from "next/headers";
import { NextResponse } from "next/server";
export async function GET(request: Request) {
const { searchParams, origin } = new URL(request.url);
const code = searchParams.get("code");
// if "next" is in param, use it as the redirect URL
const next = searchParams.get("next") ?? "/";
if (code) {
const supabase = createClient(cookies());
const { data, error } = await supabase.auth.exchangeCodeForSession(code);
if (!error) {
const { user } = data;
const dub_id = cookies().get("dub_id")?.value;
// if the user is created in the last 10 minutes, consider them new
const isNewUser =
new Date(user.created_at) > new Date(Date.now() - 10 * 60 * 1000);
// if the user is new and has a dub_id cookie, track the lead
if (dub_id && isNewUser) {
waitUntil(
dub.track.lead({
clickId: dub_id,
eventName: "Sign Up",
customerExternalId: user.id,
customerName: user.user_metadata.name,
customerEmail: user.email,
customerAvatar: user.user_metadata.avatar_url,
}),
);
// delete the clickId cookie
cookies().delete("dub_id");
}
return NextResponse.redirect(`${origin}${next}`);
}
}
// return the user to an error page with instructions
return NextResponse.redirect(`${origin}/auth/auth-code-error`);
}
```
--------------------------------
### Set Stripe Pricing Table Client Reference ID
Source: https://github.com/dubinc/dub/blob/main/apps/web/guides/stripe-payment-links.md
For Stripe Pricing Tables, pass the Dub click ID as a `client-reference-id` attribute to the `stripe-pricing-table` element. Ensure the `stripe-pricing-table.js` script is included.
```html
We offer plans that help any business!
```
--------------------------------
### Track Sale with Dub REST API
Source: https://github.com/dubinc/dub/blob/main/apps/web/guides/manual-track-sale.md
Track a sale event using the Dub REST API with a POST request. Include your API key in the Authorization header and provide sale details in the JSON request body. The amount should be in cents.
```javascript
const response = await fetch("https://api.dub.co/track/sale", {
method: "POST",
headers: {
Authorization: "Bearer dub_xxxxxx",
"Content-Type": "application/json",
},
body: JSON.stringify({
customerExternalId: "cus_oFUYbZYqHFR0knk0MjsMC6b0",
amount: 3000, // sale amount in cents
paymentProcessor: "stripe",
eventName: "Invoice paid",
invoiceId: "INV_1234567890",
currency: "usd",
}),
});
const data = await response.json();
```
--------------------------------
### Track Sale Event with Node.js SDK
Source: https://github.com/dubinc/dub/blob/main/apps/web/guides/segment-track-sale.md
Use the `@segment/analytics-node` SDK to send sale event data to Segment. Ensure properties like userId, order_id, currency, and revenue are included in the payload. Segment forwards this data to Dub based on your configured mappings.
```javascript
import { Analytics } from "@segment/analytics-node";
const segment = new Analytics({
writeKey: "",
});
segment.track({
userId: id,
event: "Order Completed",
properties: {
payment_processor: "stripe",
order_id: "ORD_123",
currency: "USD",
revenue: 1000,
},
integrations: {
All: true,
},
});
```
--------------------------------
### Add Dub Client-Side Script to GTM
Source: https://github.com/dubinc/dub/blob/main/apps/web/guides/gtm-client-sdk.md
Paste this script into the Custom HTML field in Google Tag Manager to initialize Dub analytics. Ensure it's configured to load on all pages.
```html
```
--------------------------------
### Track Sale Event on Order Confirmation Page
Source: https://github.com/dubinc/dub/blob/main/apps/web/guides/gtm-track-sale.md
Use this Custom HTML tag to track sales when users land on an order confirmation page. Ensure `customer_id` and `amount` are passed as URL query parameters. This method is more reliable and less prone to ad blocker interference.
```html
```
--------------------------------
### Seed Test User
Source: https://github.com/dubinc/dub/blob/main/apps/web/playwright/README.md
Creates a seeded test user in the local database required for login tests. Ensure the dev server is running before executing.
```sh
tsx apps/web/playwright/seed.ts
```
--------------------------------
### Send Lead Data to Dub Analytics
Source: https://github.com/dubinc/dub/blob/main/apps/web/guides/appwrite.md
Utilize the Dub client to track lead conversion events. This function sends user details and a unique click ID to Dub for analysis.
```javascript
import type { Models } from "node-appwrite";
import { Dub } from "dub";
const dub = new Dub({
token: process.env.NEXT_DUB_API_KEY,
});
export function addDubLead(
user: Models.User,
dub_id: string,
) {
dub.track.lead({
clickId: dub_id,
eventName: "Sign Up",
customerExternalId: user.$id,
customerName: user.name,
customerEmail: user.email,
});
}
```
--------------------------------
### Root Layout with DubAnalytics Component
Source: https://github.com/dubinc/dub/blob/main/apps/web/guides/clerk.md
Integrate the `DubAnalytics` component into your application's root layout to ensure analytics tracking is active for all users.
```javascript
import { DubAnalytics } from "@/components/dub-analytics";
export default function RootLayout({
children,
}: {
children: React.ReactNode;
}) {
return (
{children}
);
}
```
--------------------------------
### Track Lead with Dub REST API
Source: https://github.com/dubinc/dub/blob/main/apps/web/guides/manual-track-lead.md
Track lead events using the Dub REST API. Include your API key in the Authorization header and send lead data as a JSON payload.
```javascript
const response = await fetch("https://api.dub.co/track/lead", {
method: "POST",
headers: {
Authorization: "Bearer dub_xxxxxx",
"Content-Type": "application/json",
},
body: JSON.stringify({
clickId: "rLnWe1uz9t282v7g",
eventName: "Sign up",
customerExternalId: "cus_oFUYbZYqHFR0knk0MjsMC6b0",
customerName: "John Doe",
customerEmail: "john.doe@example.com",
customerAvatar: "https://example.com/avatar.png",
}),
});
const data = await response.json();
```
--------------------------------
### Add Dub Analytics Script to HTML
Source: https://github.com/dubinc/dub/blob/main/apps/web/guides/manual-client-sdk.md
Include this script in the `` section of your HTML file to enable Dub analytics tracking. It should be added similarly to other JavaScript snippets like Google Analytics.
```html
```
--------------------------------
### Update Stripe Customer with Dub Metadata
Source: https://github.com/dubinc/dub/blob/main/apps/web/guides/stripe-customers.md
Use this snippet to update an existing Stripe customer's metadata with the user's ID and the Dub click event ID. This is helpful if the customer already exists in Stripe but needs to be associated with a new click event.
```javascript
import { stripe } from "@/lib/stripe";
const user = {
id: "user_123",
email: "user@example.com",
teamId: "team_xxxxxxxxx",
};
const dub_id = req.headers.get("dub_id");
await stripe.customers.update(user.id, {
metadata: {
dubCustomerExternalId: user.id,
dubClickId: dub_id,
},
});
```
--------------------------------
### Dub API Base URL
Source: https://github.com/dubinc/dub/blob/main/apps/web/guides/rest-api.md
The base URL for all API endpoints. Ensure all requests are made to this address.
```bash
https://api.dub.co
```
--------------------------------
### Track Sale Event from Checkout Form
Source: https://github.com/dubinc/dub/blob/main/apps/web/guides/gtm-track-sale.md
Implement this Custom HTML tag to track sales immediately upon checkout form submission. You must customize the DOM selectors to match your form's element IDs. This method might be less reliable due to ad blockers.
```html
```
--------------------------------
### Create Stripe Checkout Session with Custom Customer ID
Source: https://github.com/dubinc/dub/blob/main/apps/web/guides/stripe-checkout.md
When creating a Stripe checkout session, pass your database's unique user ID as `dubCustomerExternalId` within the `metadata` field. This is crucial for Dub to link purchases back to the correct user and click event.
```javascript
import { stripe } from "@/lib/stripe";
const user = {
id: "user_123",
email: "user@example.com",
teamId: "team_xxxxxxxxx",
};
const priceId = "price_xxxxxxxxx";
const stripeSession = await stripe.checkout.sessions.create({
customer_email: user.email,
success_url: "https://app.domain.com/success",
line_items: [{ price: priceId, quantity: 1 }],
mode: "subscription",
client_reference_id: user.teamId,
metadata: {
dubCustomerExternalId: user.id, // the unique user ID of the customer in your database
},
});
```
--------------------------------
### Add Custom Claim to Clerk Session Token
Source: https://github.com/dubinc/dub/blob/main/apps/web/guides/clerk.md
Configure a custom claim in your Clerk session token to include user metadata. This allows you to pass relevant user information to your application.
```json
{
"metadata": "{{user.public_metadata}}"
}
```
--------------------------------
### Integrate Dub Analytics Component in Next.js Root Layout
Source: https://github.com/dubinc/dub/blob/main/apps/web/guides/appwrite.md
Add the DubAnalytics component to your Next.js app's root layout to enable analytics tracking. Ensure the component is placed within the body.
```javascript
import type { Metadata } from "next";
import { Analytics as DubAnalytics } from "@dub/analytics/react";
export const metadata: Metadata = {
title: "Appwrite Dub Leads Example",
description: "Appwrite Dub Leads Tracking example app with Next.js",
};
export default function RootLayout({
children,
}: Readonly<{ children: React.ReactNode }>) {
return (
{children}
);
}
```
--------------------------------
### Track Lead Event on Thank You Page with GTM
Source: https://github.com/dubinc/dub/blob/main/apps/web/guides/gtm-track-lead.md
Use this Custom HTML tag in GTM to track lead events when a user lands on a thank-you page. It captures email and name from URL parameters and dub_id from a GTM variable.
```html
```
--------------------------------
### Track Lead Event on Form Submission with GTM
Source: https://github.com/dubinc/dub/blob/main/apps/web/guides/gtm-track-lead.md
This Custom HTML tag in GTM tracks lead events immediately upon form submission. It retrieves form data using DOM selectors and the dub_id from a GTM variable.
```html
```
=== COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.