Skip to content

Conversation

@jnsdls
Copy link
Member

@jnsdls jnsdls commented Oct 3, 2025

TL;DR

Added Google Click ID (gclid) tracking to Stripe checkout sessions for conversion attribution.

What changed?

  • Modified the middleware to capture gclid from URL search parameters and store it in a cookie with a 7-day expiration
  • Updated the Stripe checkout process to retrieve the gclid cookie value and include it in the Stripe checkout session metadata
  • Enhanced cookie handling in the middleware to support additional cookie options like maxAge, httpOnly, etc.

How to test?

  1. Visit the dashboard with a URL containing a gclid parameter (e.g., ?gclid=test123)
  2. Verify the gclid cookie is set in your browser
  3. Proceed to checkout and complete a payment
  4. Verify in Stripe dashboard that the checkout session includes the gclid in its metadata

Why make this change?

This change enables proper attribution of conversions to Google Ads campaigns. By tracking the gclid through the user journey to payment, we can accurately measure which ad campaigns are driving successful conversions, improving our marketing analytics and ROI measurement.

Summary by CodeRabbit

  • New Features

    • Automatically captures Google ad click ID (gclid) from the landing page, stores it for 7 days, and passes it through checkout to improve campaign attribution and analytics. No UI changes.
  • Refactor

    • Updated internal cookie handling to more reliably set and forward cookies across navigation and checkout flows. No impact on user workflows.

@vercel
Copy link

vercel bot commented Oct 3, 2025

The latest updates on your projects. Learn more about Vercel for GitHub.

Project Deployment Preview Comments Updated (UTC)
thirdweb-www Ready Ready Preview Comment Oct 3, 2025 7:11pm
4 Skipped Deployments
Project Deployment Preview Comments Updated (UTC)
docs-v2 Skipped Skipped Oct 3, 2025 7:11pm
nebula Skipped Skipped Oct 3, 2025 7:11pm
thirdweb_playground Skipped Skipped Oct 3, 2025 7:11pm
wallet-ui Skipped Skipped Oct 3, 2025 7:11pm

@vercel vercel bot temporarily deployed to Preview – thirdweb_playground October 3, 2025 19:03 Inactive
@vercel vercel bot temporarily deployed to Preview – wallet-ui October 3, 2025 19:03 Inactive
@changeset-bot
Copy link

changeset-bot bot commented Oct 3, 2025

⚠️ No Changeset found

Latest commit: 5dcd4cc

Merging this PR will not cause a version bump for any packages. If these changes should not result in a new version, you're good to go. If these changes should result in a version bump, you need to add a changeset.

This PR includes no changesets

When changesets are added to this PR, you'll see the packages that this PR includes changesets for and the associated semver types

Click here to learn what changesets are, and how to add one.

Click here if you're a maintainer who wants to add a changeset to this PR

@vercel vercel bot temporarily deployed to Preview – docs-v2 October 3, 2025 19:03 Inactive
@vercel vercel bot temporarily deployed to Preview – nebula October 3, 2025 19:03 Inactive
@jnsdls jnsdls marked this pull request as ready for review October 3, 2025 19:03
@jnsdls jnsdls requested review from a team as code owners October 3, 2025 19:03
@github-actions github-actions bot added the Dashboard Involves changes to the Dashboard. label Oct 3, 2025
Copy link
Member Author

jnsdls commented Oct 3, 2025


How to use the Graphite Merge Queue

Add either label to this PR to merge it via the merge queue:

  • merge-queue - adds this PR to the back of the merge queue
  • hotfix - for urgent hot fixes, skip the queue and merge this PR next

You must have a Graphite account in order to use the merge queue. Sign up using this link.

An organization admin has enabled the Graphite Merge Queue in this repository.

Please do not merge from GitHub as this will restart CI on PRs being processed by the merge queue.

This stack of pull requests is managed by Graphite. Learn more about stacking.

@coderabbitai
Copy link
Contributor

coderabbitai bot commented Oct 3, 2025

Walkthrough

Adds gclid capture and propagation: middleware parses gclid from query and sets a cookie with options; Stripe action reads gclid from cookies and conditionally includes it as metadata when creating a Checkout Session. Middleware refactors cookie-setting to support value+options tuples and updates related function signatures and calls.

Changes

Cohort / File(s) Summary
Stripe checkout metadata
apps/dashboard/src/@/actions/stripe-actions.ts
Imports cookies and headers from next/headers; reads gclid from cookies(); conditionally adds metadata: { gclid } to Stripe Checkout Session creation; no public API changes.
Middleware cookie handling and gclid
apps/dashboard/src/middleware.ts
Introduces CookiesToSet type supporting [value] or [value, options]; migrates all cookie-setting to res.cookies.set(name, value, options); extracts gclid from search params and sets a 7‑day cookie with options (httpOnly: false, sameSite: lax, secure: true); updates rewrite/redirect signatures to accept CookiesToSet; refactors internal usage accordingly.

Sequence Diagram(s)

sequenceDiagram
  autonumber
  participant U as User
  participant MW as Next.js Middleware
  participant B as Browser
  participant SA as Stripe Action

  U->>MW: HTTP request with ?gclid=...
  MW->>B: Response with Set-Cookie gclid=... (7d, options)
  Note over MW,B: Cookie options: httpOnly=false, sameSite=lax, secure=true

  U->>SA: Initiate checkout (request includes cookies)
  SA->>SA: Read gclid via cookies()
  alt gclid present
    SA->>Stripe: Create Checkout Session (metadata.gclid)
  else gclid absent
    SA->>Stripe: Create Checkout Session (no gclid metadata)
  end
Loading

Estimated code review effort

🎯 3 (Moderate) | ⏱️ ~25 minutes

Pre-merge checks and finishing touches

❌ Failed checks (2 warnings)
Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 25.00% which is insufficient. The required threshold is 80.00%. You can run @coderabbitai generate docstrings to improve docstring coverage.
Description Check ⚠️ Warning The pull request description is entirely missing and does not follow the required template sections for title, reviewer notes, and testing instructions as specified in the repository’s description template. Please add a descriptive PR description that includes a properly formatted title in the “[SDK/Dashboard/Portal] Feature/Fix: Concise title” style, a Notes for the reviewer section highlighting any important changes, and a How to test section outlining steps to verify the implementation.
✅ Passed checks (1 passed)
Check name Status Explanation
Title Check ✅ Passed The pull request title clearly summarizes the main change, which is adding Google Click ID tracking to the Stripe checkout process, in a concise and focused manner.
✨ Finishing touches
  • 📝 Generate docstrings
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Post copyable unit tests in a comment
  • Commit unit tests in branch Add_Google_Click_ID_tracking_to_Stripe_checkout

Comment @coderabbitai help to get the list of available commands and usage tips.

@codecov
Copy link

codecov bot commented Oct 3, 2025

Codecov Report

✅ All modified and coverable lines are covered by tests.
✅ Project coverage is 56.07%. Comparing base (ef9cf34) to head (5dcd4cc).
⚠️ Report is 1 commits behind head on main.

Additional details and impacted files
@@           Coverage Diff           @@
##             main    #8180   +/-   ##
=======================================
  Coverage   56.07%   56.07%           
=======================================
  Files         905      905           
  Lines       59228    59228           
  Branches     4124     4124           
=======================================
  Hits        33212    33212           
  Misses      25912    25912           
  Partials      104      104           
Flag Coverage Δ
packages 56.07% <ø> (ø)
🚀 New features to boost your workflow:
  • ❄️ Test Analytics: Detect flaky tests, report on failures, and find test suite problems.
  • 📦 JS Bundle Analysis: Save yourself from yourself by tracking and limiting bundle sizes in JS merges.

Copy link
Contributor

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 1

Caution

Some comments are outside the diff and can’t be posted inline due to platform limitations.

⚠️ Outside diff range comments (3)
apps/dashboard/src/middleware.ts (3)

46-76: Remove redundant null check.

cookiesToSet is initialized at line 46, so the check at lines 69-71 will always be false and can be removed.

Apply this diff:

         // if its already set - don't set it again
         if (!request.cookies.get(key)) {
-          if (!cookiesToSet) {
-            cookiesToSet = {};
-          }
-
           cookiesToSet[key] = [value];
         }

175-182: Add type safety for optional cookie options.

The code assumes entry[1][1] (cookie options) is always present, but CookiesToSet allows tuples with just [value]. This could pass undefined as the third argument to cookies.set().

Apply this diff to handle both tuple formats safely:

   if (cookiesToSet) {
     const defaultResponse = NextResponse.next();
     for (const entry of Object.entries(cookiesToSet)) {
-      defaultResponse.cookies.set(entry[0], entry[1][0], entry[1][1]);
+      const [value, options] = entry[1];
+      if (options) {
+        defaultResponse.cookies.set(entry[0], value, options);
+      } else {
+        defaultResponse.cookies.set(entry[0], value);
+      }
     }

     return defaultResponse;
   }

191-233: Apply the same type safety fix in helper functions.

The same issue with optional cookie options exists in both rewrite() (line 202) and redirect() (line 228). Apply the same pattern as suggested for the main flow.

Apply this diff:

 function rewrite(
   request: NextRequest,
   relativePath: string,
   cookiesToSet: CookiesToSet,
 ) {
   const url = request.nextUrl.clone();
   url.pathname = relativePath;
   const res = NextResponse.rewrite(url);

   if (cookiesToSet) {
     for (const entry of Object.entries(cookiesToSet)) {
-      res.cookies.set(entry[0], entry[1][0], entry[1][1]);
+      const [value, options] = entry[1];
+      if (options) {
+        res.cookies.set(entry[0], value, options);
+      } else {
+        res.cookies.set(entry[0], value);
+      }
     }
   }

   return res;
 }

 function redirect(
   request: NextRequest,
   relativePath: string,
   options:
     | {
         searchParams?: string;
         permanent?: boolean;
         cookiesToSet?: CookiesToSet;
       }
     | undefined,
 ) {
   const permanent = options?.permanent ?? false;
   const url = request.nextUrl.clone();
   url.pathname = relativePath;
   url.search = options?.searchParams ? `?${options.searchParams}` : "";
   const res = NextResponse.redirect(url, permanent ? 308 : undefined);

   if (options?.cookiesToSet) {
     for (const entry of Object.entries(options.cookiesToSet)) {
-      res.cookies.set(entry[0], entry[1][0], entry[1][1]);
+      const [value, options] = entry[1];
+      if (options) {
+        res.cookies.set(entry[0], value, options);
+      } else {
+        res.cookies.set(entry[0], value);
+      }
     }
   }

   return res;
 }
🧹 Nitpick comments (1)
apps/dashboard/src/middleware.ts (1)

10-22: Consider aligning CookiesToSet options with Next.js cookie API.

The current type definition only includes httpOnly, sameSite, secure, and maxAge, but Next.js cookies().set() supports additional options like path, domain, and expires. This could limit flexibility if you need to set cookies with specific paths or domains in the future.

Consider expanding the type to include all standard cookie options:

 type CookiesToSet = Record<
   string,
   | [string]
   | [
       string,
       {
         httpOnly: boolean;
         sameSite?: "lax" | "strict" | "none";
         secure: boolean;
         maxAge: number;
+        path?: string;
+        domain?: string;
+        expires?: Date;
       },
     ]
 >;
📜 Review details

Configuration used: CodeRabbit UI

Review profile: CHILL

Plan: Pro

Disabled knowledge base sources:

  • Linear integration is disabled by default for public repositories

You can enable these sources in your CodeRabbit configuration.

📥 Commits

Reviewing files that changed from the base of the PR and between ef9cf34 and 5dcd4cc.

📒 Files selected for processing (2)
  • apps/dashboard/src/@/actions/stripe-actions.ts (3 hunks)
  • apps/dashboard/src/middleware.ts (7 hunks)
🧰 Additional context used
📓 Path-based instructions (4)
**/*.{ts,tsx}

📄 CodeRabbit inference engine (CLAUDE.md)

**/*.{ts,tsx}: Write idiomatic TypeScript with explicit function declarations and return types
Limit each file to one stateless, single-responsibility function for clarity
Re-use shared types from @/types or local types.ts barrels
Prefer type aliases over interface except for nominal shapes
Avoid any and unknown unless unavoidable; narrow generics when possible
Choose composition over inheritance; leverage utility types (Partial, Pick, etc.)
Comment only ambiguous logic; avoid restating TypeScript in prose

**/*.{ts,tsx}: Use explicit function declarations and explicit return types in TypeScript
Limit each file to one stateless, single‑responsibility function
Re‑use shared types from @/types where applicable
Prefer type aliases over interface except for nominal shapes
Avoid any and unknown unless unavoidable; narrow generics when possible
Prefer composition over inheritance; use utility types (Partial, Pick, etc.)
Lazy‑import optional features and avoid top‑level side‑effects to reduce bundle size

Files:

  • apps/dashboard/src/middleware.ts
  • apps/dashboard/src/@/actions/stripe-actions.ts
**/*.{ts,tsx,js,jsx}

📄 CodeRabbit inference engine (CLAUDE.md)

Load heavy dependencies inside async paths to keep initial bundle lean (lazy loading)

Files:

  • apps/dashboard/src/middleware.ts
  • apps/dashboard/src/@/actions/stripe-actions.ts
apps/{dashboard,playground-web}/**/*.{ts,tsx}

📄 CodeRabbit inference engine (CLAUDE.md)

apps/{dashboard,playground-web}/**/*.{ts,tsx}: Import UI primitives from @/components/ui/* (Button, Input, Select, Tabs, Card, Sidebar, Badge, Separator) in dashboard and playground apps
Use NavLink for internal navigation with automatic active states in dashboard and playground apps
Use Tailwind CSS only – no inline styles or CSS modules
Use cn() from @/lib/utils for conditional class logic
Use design system tokens (e.g., bg-card, border-border, text-muted-foreground)
Server Components (Node edge): Start files with import "server-only";
Client Components (browser): Begin files with 'use client';
Always call getAuthToken() to retrieve JWT from cookies on server side
Use Authorization: Bearer header – never embed tokens in URLs
Return typed results (e.g., Project[], User[]) – avoid any
Wrap client-side data fetching calls in React Query (@tanstack/react-query)
Use descriptive, stable queryKeys for React Query cache hits
Configure staleTime/cacheTime in React Query based on freshness (default ≥ 60s)
Keep tokens secret via internal API routes or server actions
Never import posthog-js in server components

Files:

  • apps/dashboard/src/middleware.ts
  • apps/dashboard/src/@/actions/stripe-actions.ts
apps/{dashboard,playground}/**/*.{ts,tsx}

📄 CodeRabbit inference engine (AGENTS.md)

apps/{dashboard,playground}/**/*.{ts,tsx}: Import UI primitives from @/components/ui/_ (e.g., Button, Input, Tabs, Card)
Use NavLink for internal navigation to get active state handling
Use Tailwind CSS for styling; no inline styles
Merge class names with cn() from @/lib/utils for conditional classes
Stick to design tokens (e.g., bg-card, border-border, text-muted-foreground)
Server Components must start with import "server-only"; use next/headers, server‑only env, heavy data fetching, and redirect() where appropriate
Client Components must start with 'use client'; handle interactivity with hooks and browser APIs
Server-side data fetching: call getAuthToken() from cookies, send Authorization: Bearer <token> header, and return typed results (avoid any)
Client-side data fetching: wrap calls in React Query with descriptive, stable queryKeys and set sensible staleTime/cacheTime (≥ 60s default); keep tokens secret via internal routes or server actions
Do not import posthog-js in server components (client-side only)

Files:

  • apps/dashboard/src/middleware.ts
  • apps/dashboard/src/@/actions/stripe-actions.ts
🧠 Learnings (1)
📚 Learning: 2025-08-29T15:37:38.513Z
Learnt from: CR
PR: thirdweb-dev/js#0
File: AGENTS.md:0-0
Timestamp: 2025-08-29T15:37:38.513Z
Learning: Applies to apps/{dashboard,playground}/**/*.{ts,tsx} : Server Components must start with `import "server-only"`; use `next/headers`, server‑only env, heavy data fetching, and `redirect()` where appropriate

Applied to files:

  • apps/dashboard/src/@/actions/stripe-actions.ts
⏰ Context from checks skipped due to timeout of 90000ms. You can increase the timeout in your CodeRabbit configuration to a maximum of 15 minutes (900000ms). (5)
  • GitHub Check: E2E Tests (pnpm, vite)
  • GitHub Check: Size
  • GitHub Check: Unit Tests
  • GitHub Check: Lint Packages
  • GitHub Check: Analyze (javascript)
🔇 Additional comments (4)
apps/dashboard/src/middleware.ts (1)

41-41: LGTM!

Destructuring searchParams upfront improves readability and reduces repetitive property access.

apps/dashboard/src/@/actions/stripe-actions.ts (3)

3-3: LGTM!

The addition of cookies import from next/headers is appropriate for this server-side action and aligns with the coding guidelines for server components.

Based on learnings.


91-92: LGTM!

The gclid retrieval is implemented correctly with proper async handling and optional chaining to handle missing cookies gracefully.


123-124: LGTM! Verify metadata placement aligns with attribution requirements.

The conditional metadata attachment is implemented correctly. The gclid is being set on subscription_data.metadata, which will attach it to the Stripe subscription object for long-term attribution tracking.

If you need to track the gclid on the checkout session itself (for immediate conversion tracking), you might also want to add it at the session level:

const session = await stripe.checkout.sessions.create({
  // ... existing config
  metadata: gclid ? { gclid } : undefined,
  subscription_data: {
    // ... existing config
    metadata: gclid ? { gclid } : undefined,
  },
});

However, this is only necessary if your attribution logic needs session-level metadata. The current implementation on subscription_data is sufficient for tracking which ad led to the subscription.

@github-actions
Copy link
Contributor

github-actions bot commented Oct 3, 2025

size-limit report 📦

Path Size Loading time (3g) Running time (snapdragon) Total time
thirdweb (esm) 64.6 KB (0%) 1.3 s (0%) 290 ms (+261.87% 🔺) 1.6 s
thirdweb (cjs) 365.75 KB (0%) 7.4 s (0%) 865 ms (+15.56% 🔺) 8.2 s
thirdweb (minimal + tree-shaking) 5.73 KB (0%) 115 ms (0%) 99 ms (+2106.3% 🔺) 213 ms
thirdweb/chains (tree-shaking) 526 B (0%) 11 ms (0%) 34 ms (+1573.37% 🔺) 44 ms
thirdweb/react (minimal + tree-shaking) 19.13 KB (0%) 383 ms (0%) 100 ms (+2185.52% 🔺) 482 ms

@jnsdls jnsdls merged commit 4a30b9c into main Oct 3, 2025
25 checks passed
@jnsdls jnsdls deleted the Add_Google_Click_ID_tracking_to_Stripe_checkout branch October 3, 2025 22:05
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

Dashboard Involves changes to the Dashboard.

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants