How to attribute signups and Stripe payments to campaigns in a Next.js app

Capture campaign UTMs, identify signups, and record one-time Stripe payments in Next.js. Compare first-touch and last-touch campaign credit in Amplitude. Allow about 60 minutes.

  • Next.js 16
  • App Router
  • Unified SDK 1.x
  • Stripe 23.1.0
  • 60 min

Chris Tam · Last updated 13 November 2026

I use product analytics to connect a campaign visit, account creation, and Stripe payment under one user ID. That gives me separate answers for which campaign attracted a signup and which campaign preceded payment.

In this tutorial, I build a standalone demo that creates a local account and sells a $20 report export through Stripe sandbox Checkout. Account creation generates an ID and cookie session without email or password; the export is simulated. Checkout and the signed webhook use Stripe's test environment.

What you'll build

I arrive through campaign A, create a demo account, return through campaign B, and complete a $20 test purchase. Amplitude receives Signup Completed and Payment Completed on the same user. I compare first-touch and last-touch credit in a seven-day window.

This example handles one-time USD card payments. It measures gross paid USD as a numeric property; subscriptions, renewals, delayed payment methods, refunds, fulfillment, and net revenue accounting need their own handlers.

Every custom application file is included. The local account database makes the demo runnable without another tutorial. In an existing app I keep its real authentication, routes, providers, instrumentation, and consent controls, and connect its validated session to the checkout route. I do not deploy the demo account mechanism as production authentication.

Prerequisites

  • Node.js 24, Corepack, and pnpm. The local account store uses Node's built-in SQLite and needs a persistent local filesystem.
  • An Amplitude test project and project API key. In Settings > Projects > the project > General, I select Manage beside API Key. Browser and server use the same project.
  • A Stripe sandbox account, Stripe CLI, and a one-time $20 USD Price. I enable cards and disable Adaptive Pricing so the test remains USD.

Sign up for free to get an Amplitude project API key. Data Tables and attribution are available on current plans; Free and Plus allow one channel view. I compare models sequentially in that view, avoiding a dependency on a mixed-model six-column layout. Older plan access can differ.

1. Create the standalone app

I use the Next.js installation guide for the browser and server SDK packages. I create the directory, then save the complete setup files below.

Terminal

Terminal
mkdir nextjs-stripe-demo
cd nextjs-stripe-demo

package.json

package.json
{
  "name": "nextjs-stripe-attribution-2026-11-12",
  "private": true,
  "scripts": {
    "dev": "next dev",
    "build": "next build --webpack",
    "start": "next start",
    "typecheck": "tsc --noEmit"
  },
  "engines": {
    "node": ">=24.0.0"
  },
  "packageManager": "pnpm@10.21.0+sha512.da3337267e400fdd3d479a6c68079ac6db01d8ca4f67572083e722775a796788a7a9956613749e000fac20d424b594f7a791a5f4e2e13581c5ef947f26968a40",
  "dependencies": {
    "@amplitude/unified": "1.2.1",
    "next": "16.4.5",
    "react": "19.3.0",
    "react-dom": "19.3.0",
    "@amplitude/analytics-node": "1.5.82",
    "stripe": "23.1.0",
    "server-only": "0.0.1"
  },
  "devDependencies": {
    "@types/node": "24.10.0",
    "@types/react": "19.2.18",
    "@types/react-dom": "19.2.7",
    "typescript": "5.9.3"
  }
}

pnpm-workspace.yaml

pnpm-workspace.yaml
packages:
  - .
minimumReleaseAge: 10080
trustPolicy: no-downgrade

tsconfig.json

tsconfig.json
{
  "compilerOptions": {
    "target": "ES2022",
    "lib": [
      "dom",
      "dom.iterable",
      "esnext"
    ],
    "allowJs": true,
    "skipLibCheck": true,
    "strict": true,
    "noEmit": true,
    "esModuleInterop": true,
    "module": "esnext",
    "moduleResolution": "bundler",
    "resolveJsonModule": true,
    "isolatedModules": true,
    "jsx": "react-jsx",
    "incremental": true,
    "plugins": [
      {
        "name": "next"
      }
    ],
    "baseUrl": ".",
    "paths": {
      "@/*": [
        "./*"
      ]
    }
  },
  "include": [
    "next-env.d.ts",
    "**/*.ts",
    "**/*.tsx",
    ".next/types/**/*.ts",
    ".next/dev/types/**/*.ts"
  ],
  "exclude": [
    "node_modules"
  ]
}

.gitignore

.gitignore
node_modules/
.next/
data/
.env*
!.env.example
*.tsbuildinfo

.env.example

.env.example
NEXT_PUBLIC_AMPLITUDE_API_KEY=your-project-api-key
AMPLITUDE_API_KEY=your-project-api-key
AMPLITUDE_SERVER_ZONE=US
STRIPE_SECRET_KEY=sk_test_your_sandbox_secret
STRIPE_PRICE_ID=price_your_20_usd_one_time_price
STRIPE_WEBHOOK_SECRET=whsec_from_stripe_listen
APP_URL=http://localhost:3000

app/layout.tsx

app/layout.tsx
// Keep existing fonts, metadata, authentication and providers when merging.
import type { ReactNode } from 'react';
export default function RootLayout({ children }: { children: ReactNode }) {
  return <html lang="en"><body><main>{children}</main></body></html>;
}

I enable the pinned package manager and install the dependencies, then fill .env.local with test-project credentials.

Terminal

Terminal
corepack enable
pnpm install
cp .env.example .env.local

I commit the generated lockfile for reproducible installs and use pnpm install --frozen-lockfile afterward. The Amplitude project API key is public with a limited ingestion scope. Stripe secret keys and webhook signing secrets remain server-only. I keep .env.local out of version control.

The app stores local account state under data/. For a deployed service I replace the local SQLite file with shared durable storage and use the app's real authentication. A serverless deployment with ephemeral files cannot preserve these demo sessions.

2. Capture campaigns in the browser

I initialize Unified once before the app becomes interactive, using Next.js's instrumentation-client entry. I capture attribution as both user and event properties. I disable Analytics remote configuration so project settings cannot replace this demo's local attribution configuration.

lib/amplitude.ts

lib/amplitude.ts
// lib/amplitude.ts
'use client';
// Keep lines other Next.js pages added here: replay masking and sampling
// (/build/nextjs-session-replay), experiment configuration
// (/build/nextjs-feature-flags), and engagement options
// (/build/nextjs-guides-surveys). Merge into your existing initAll call.
import * as amplitude from '@amplitude/unified';

declare global {
  var __campaignAmplitudeReady: Promise<void> | undefined;
}

export function amplitudeReady(): Promise<void> {
  if (typeof window === 'undefined') return Promise.resolve();
  if (!globalThis.__campaignAmplitudeReady) {
    const key = process.env.NEXT_PUBLIC_AMPLITUDE_API_KEY;
    if (!key) return Promise.reject(new Error('Missing Amplitude API key'));
    globalThis.__campaignAmplitudeReady = amplitude.initAll(key, {
      analytics: {
        remoteConfig: { fetchRemoteConfig: false },
        autocapture: {
          pageViews: true,
          attribution: { trackingMethod: ['userProperty', 'eventProperty'] },
        },
      },
      sessionReplay: { sampleRate: 0 },
      engagement: { skip: true },
    });
  }
  return globalThis.__campaignAmplitudeReady;
}

if (typeof window !== 'undefined') {
  void amplitudeReady().catch(console.error);
}

export { amplitude };

// Bound the UI wait; the SDK may finish queued work after the UI continues.
export async function bestEffortAnalytics(work: () => Promise<unknown>): Promise<void> {
  let timer: ReturnType<typeof setTimeout> | undefined;
  try {
    await Promise.race([
      work(),
      new Promise((_, reject) => { timer = setTimeout(() => reject(new Error('Analytics wait timed out')), 1500); }),
    ]);
  } catch (error) { console.error('Browser analytics unavailable', error); }
  finally { clearTimeout(timer); }
}

instrumentation-client.ts

instrumentation-client.ts
import './lib/amplitude';

For an existing app, I merge these options and the readiness helper into its existing singleton. I preserve replay sampling/masking, feature flags, guides and surveys, and consent decisions. This standalone configuration sets recording to zero and skips guides and surveys initialization. A consent-controlled site initializes only after its required consent signal.

For EU data residency I add serverZone: 'EU' at the top level of initAll, and set AMPLITUDE_SERVER_ZONE=EU for the server helper. I use the EU project's key in both variables.

Why. The first campaign event must happen before redirects remove the UTMs. I keep campaign values in the landing URL until initialization and check them in Instrumentation Explorer. I do not add a second manual page-view hook.

3. Create a demo account and identify its signup

I generate an account ID on the server and store a random session token in an HTTP-only cookie. The browser cannot supply the account ID used by Checkout. This local demo has no email verification, password, or account recovery; in production the existing auth system owns those responsibilities.

lib/store.ts

lib/store.ts
import { DatabaseSync } from "node:sqlite";
import { mkdirSync } from "node:fs";
import { randomUUID } from "node:crypto";

// One local database; use a shared durable database and a worker when deploying.
const state = globalThis as typeof globalThis & { attributionDB?: DatabaseSync };
export function db() {
  if (!state.attributionDB) {
    mkdirSync("data", { recursive: true });
    const sql = new DatabaseSync("data/attribution.sqlite");
    sql.exec(`
      PRAGMA journal_mode=WAL;
      PRAGMA busy_timeout=5000;
      CREATE TABLE IF NOT EXISTS accounts (id TEXT PRIMARY KEY, token TEXT UNIQUE NOT NULL);
    `);
    state.attributionDB = sql;
  }
  return state.attributionDB;
}
export function findAccount(token?: string) {
  return (token ? db().prepare("SELECT id FROM accounts WHERE token = ?").get(token) : undefined) as { id: string } | undefined;
}
export function createAccount() {
  const account = { id: randomUUID(), token: randomUUID() };
  db().prepare("INSERT INTO accounts (id, token) VALUES (?, ?)").run(account.id, account.token);
  return account;
}

lib/session.ts

lib/session.ts
import { cookies } from "next/headers";
import { findAccount } from "./store";

export async function accountFromCookie() {
  return findAccount((await cookies()).get("stripe_attribution_demo_session")?.value);
}
export function checkOrigin(request: Request) {
  if (request.headers.get("origin") !== new URL(process.env.APP_URL!).origin) {
    throw new Error("Unexpected request origin");
  }
}

export async function getCurrentUser() { return (await accountFromCookie()) ?? null; }

app/api/account/route.ts

app/api/account/route.ts
import { NextResponse } from "next/server";
import { accountFromCookie, checkOrigin } from "../../../lib/session";
import { createAccount } from "../../../lib/store";

export const runtime = "nodejs";
export async function GET() {
  return NextResponse.json({ userId: (await accountFromCookie())?.id ?? null }, {
    headers: { "Cache-Control": "no-store" },
  });
}
export async function POST(request: Request) {
  try { checkOrigin(request); } catch { return new Response("Invalid origin", { status: 403 }); }
  const existing = await accountFromCookie();
  if (existing) return NextResponse.json({ userId: existing.id, created: false });
  const account = createAccount();
  const response = NextResponse.json({ userId: account.id, created: true });
  response.cookies.set("stripe_attribution_demo_session", account.token, {
    httpOnly: true, sameSite: "lax", path: "/", maxAge: 86400,
    secure: new URL(process.env.APP_URL!).protocol === "https:",
  });
  return response;
}

lib/amplitude-user-id.ts

lib/amplitude-user-id.ts
// lib/amplitude-user-id.ts
export function amplitudeUserId(accountId: string): string {
  if (!accountId.trim()) throw new Error('An account ID is required');
  return `user-${accountId}`;
}

lib/signup-attribution.ts

lib/signup-attribution.ts
// lib/signup-attribution.ts
'use client';
import { amplitude, amplitudeReady, bestEffortAnalytics } from '@/lib/amplitude';
import { amplitudeUserId } from '@/lib/amplitude-user-id';

// Call only after your app confirms that it created a new account.
export async function trackSignup(accountId: string): Promise<void> {
  await bestEffortAnalytics(async () => {
    await amplitudeReady();
    const userId = amplitudeUserId(accountId);
    amplitude.setUserId(userId);
    const result = await amplitude.track({
      event_type: 'Signup Completed',
      insert_id: `signup-${userId}`,
    }).promise;
    if (result.code !== 200) console.error('Signup analytics:', result.message);
  });
}

app/page.tsx

app/page.tsx
// Keep your existing routes and auth; this is the standalone demo home.
'use client';
import { useEffect, useState } from 'react';
import { CheckoutButton } from '@/components/CheckoutButton';
import { amplitude, amplitudeReady, bestEffortAnalytics } from '@/lib/amplitude';
import { amplitudeUserId } from '@/lib/amplitude-user-id';
import { trackSignup } from '@/lib/signup-attribution';
export default function Home() {
  const [accountId, setAccountId] = useState<string | null>(null);
  const [busy, setBusy] = useState(true);
  const [message, setMessage] = useState('');
  useEffect(() => {
    void (async () => {
      try {
        const response = await fetch('/api/account');
        if (!response.ok) throw new Error('Account lookup failed');
        const { userId } = await response.json();
        setAccountId(userId);
        if (userId) {
          await bestEffortAnalytics(async () => { await amplitudeReady(); amplitude.setUserId(amplitudeUserId(userId)); });
        }
      } catch { setMessage('Could not load the demo account. Reload to retry.'); }
      finally { setBusy(false); }
    })();
  }, []);
  async function signup() {
    setBusy(true); setMessage('');
    try {
      const response = await fetch('/api/account', { method: 'POST' });
      if (!response.ok) throw new Error('Demo signup failed');
      const { userId, created } = await response.json();
      setAccountId(userId);
      if (created) await trackSignup(userId);
    } catch (error) { setMessage(String(error)); }
    finally { setBusy(false); }
  }
  return <>
    <h1>Campaign checkout demo</h1>
    <p>I can create a local demo account and buy a $20 report export in Stripe's sandbox.</p>
    <p>The account is a generated ID with a cookie session. No email or password is collected.</p>
    <p>{accountId ? `Account: ${amplitudeUserId(accountId)}` : 'No demo account yet'}</p>
    <button disabled={busy || !!accountId} onClick={signup}>Create demo account</button>
    {accountId && <CheckoutButton accountId={accountId} />}
    <p role="status">{message}</p>
  </>;
}

Only a response with created: true triggers signup tracking. I cap browser analytics waits at 1.5 seconds so a pending SDK request does not hold signup or Checkout indefinitely. That deadline does not cancel queued events or prove their delivery. Restoring a cookie after reload sets the same canonical user-... identity without a new signup event. The prefix keeps even short database IDs above Amplitude's five-character minimum. An existing app keeps its established ID format instead of creating new profiles.

setUserId links subsequent activity to the identified user while retaining anonymous browser history. I never reset merely because a session is loading. In a production sign-out handler I preserve other products' cleanup, close active guides and surveys if present, call reset(), then clear experiment variants.

Browser signup tracking can be blocked independently of successful account creation. If I need a server-authoritative signup metric, I extend the account-creation transaction with a server delivery path and the client/server identity pattern.

MCP. I use Amplitude MCP to inspect the existing event taxonomy before introducing signup or payment names in an established project.

4. Create Checkout from the server session

I create a one-time payment Session using only the account from the validated cookie and the Price from server configuration. The client sends no account ID, Price, amount, or redirect URL. The origin check rejects cross-origin form submissions.

lib/stripe.ts

lib/stripe.ts
// lib/stripe.ts
import 'server-only';
import Stripe from 'stripe';

export function stripeClient(): Stripe {
  const key = process.env.STRIPE_SECRET_KEY;
  if (!key?.startsWith('sk_test_') && !key?.startsWith('rkcs_test_')) {
    throw new Error('Use a Stripe sandbox test secret key');
  }
  return new Stripe(key, { apiVersion: '2026-10-28.endive' });
}

app/api/checkout/route.ts

app/api/checkout/route.ts
// app/api/checkout/route.ts
import { getCurrentUser } from '@/lib/session';
import { amplitudeUserId } from '@/lib/amplitude-user-id';
import { stripeClient } from '@/lib/stripe';

export const runtime = 'nodejs';

export async function POST(request: Request) {
  const appUrl = process.env.APP_URL;
  const price = process.env.STRIPE_PRICE_ID;
  if (!appUrl || !price) {
    return Response.json({ error: 'Checkout is not configured' }, { status: 500 });
  }
  // The browser cannot choose the account, price, or return URL.
  if (request.headers.get('origin') !== new URL(appUrl).origin) {
    return new Response('Invalid origin', { status: 403 });
  }
  const user = await getCurrentUser();
  if (!user) return new Response('Sign in first', { status: 401 });

  try {
  const session = await stripeClient().checkout.sessions.create({
    mode: 'payment',
    adaptive_pricing: { enabled: false },
    allowed_payment_method_types: ['card'],
    line_items: [{ price, quantity: 1 }],
    metadata: { amplitude_user_id: amplitudeUserId(user.id) },
    success_url: new URL('/?checkout=success', appUrl).toString(),
    cancel_url: new URL('/?checkout=cancelled', appUrl).toString(),
  });
  if (!session.url) {
    return Response.json({ error: 'No Checkout URL returned' }, { status: 502 });
  }
  return Response.json({ url: session.url });
  } catch (error) {
    console.error("Checkout failed", error);
    return new Response("Checkout unavailable", { status: 502 });
  }
}

components/CheckoutButton.tsx

components/CheckoutButton.tsx
// components/CheckoutButton.tsx
'use client';
import { useState } from 'react';
import { amplitude, amplitudeReady, bestEffortAnalytics } from '@/lib/amplitude';
import { amplitudeUserId } from '@/lib/amplitude-user-id';

export function CheckoutButton({ accountId }: { accountId: string }) {
  const [busy, setBusy] = useState(false);
  const [error, setError] = useState('');

  async function checkout() {
    setBusy(true);
    setError('');
    try {
      // Keep checkout usable even if browser analytics is blocked.
      await bestEffortAnalytics(async () => {
        await amplitudeReady();
        amplitude.setUserId(amplitudeUserId(accountId));
        await amplitude.track('Checkout Started').promise;
      });
      const response = await fetch('/api/checkout', { method: 'POST' });
      if (!response.ok) throw new Error('Could not start checkout. Try again.');
      const { url } = await response.json();
      window.location.assign(url);
    } catch (checkoutError) {
      setError(checkoutError instanceof Error ? checkoutError.message : 'Checkout failed');
      setBusy(false);
    }
  }

  return <>
    <button onClick={checkout} disabled={busy}>
      {busy ? 'Opening checkout...' : 'Buy for $20'}
    </button>
    {error && <p role="alert">{error}</p>}
  </>;
}

The Stripe client rejects live keys and explicitly pins API version 2026-10-28.endive with stripe@23.1.0. I set allowed_payment_method_types: ['card'] and disable Adaptive Pricing for this USD-only test. I put the canonical ID in Checkout Session metadata because the webhook consumes that object.

Why. Metadata does not copy automatically across every Stripe object. An invoice or PaymentIntent handler would need its own metadata contract. Checkout Started measures intent; only the verified paid Session produces Payment Completed. The demo purchase does not deliver a report export.

5. Accept the signed paid-session webhook

I use one payment-ingestion path. If an existing Stripe integration already sends these payments to Amplitude, I reuse it and adapt the chart rather than count both streams.

The helper sends Payment Completed with amount_usd. It checks the per-event upload result after flushing. The helper sets one total upload attempt and a request timeout; a failure returns HTTP 500 for Stripe to retry.

lib/payment-analytics.ts

lib/payment-analytics.ts
// lib/payment-analytics.ts
import 'server-only';
import { createInstance } from '@amplitude/analytics-node';
import type Stripe from 'stripe';

const billing = createInstance();
let ready: Promise<void> | undefined;

export async function recordPayment(session: Stripe.Checkout.Session, time: number) {
  const userId = session.metadata?.amplitude_user_id;
  if (!userId || userId.length < 5) throw new Error('Missing Amplitude user ID');
  if (session.currency !== 'usd' || session.amount_total == null) {
    throw new Error('This example requires a USD payment amount');
  }
  const key = process.env.AMPLITUDE_API_KEY;
  if (!key) throw new Error('Missing AMPLITUDE_API_KEY');
  ready ??= billing.init(key, { requestTimeoutMillis: 3000, flushMaxRetries: 1, serverZone: process.env.AMPLITUDE_SERVER_ZONE === 'EU' ? 'EU' : 'US' }).promise;
  await ready;

  const pending = billing.track('Payment Completed', {
    checkout_session_id: session.id,
    amount_usd: session.amount_total / 100,
    currency: 'USD',
  }, {
    user_id: userId,
    // Stable on both webhook redelivery and a separate event for this Session.
    device_id: `stripe-${session.id}`,
    insert_id: `checkout-paid-${session.id}`,
    time,
    session_id: -1,
  });
  await billing.flush().promise;
  const result = await pending.promise;
  if (result.code !== 200) throw new Error(`Amplitude upload failed: ${result.code}`);
}

app/api/stripe/webhook/route.ts

app/api/stripe/webhook/route.ts
// app/api/stripe/webhook/route.ts
import type Stripe from 'stripe';
import { stripeClient } from '@/lib/stripe';
import { recordPayment } from '@/lib/payment-analytics';

export const runtime = 'nodejs';

export async function POST(request: Request) {
  const signature = request.headers.get('stripe-signature');
  const secret = process.env.STRIPE_WEBHOOK_SECRET;
  if (!secret) return new Response('Webhook is not configured', { status: 500 });
  if (!signature) return new Response('Missing signature', { status: 400 });

  let event: Stripe.Event;
  try {
    event = stripeClient().webhooks.constructEvent(
      await request.text(), signature, secret,
    );
  } catch {
    return new Response('Invalid signature', { status: 400 });
  }
  if (event.livemode) return new Response('Test mode only', { status: 400 });
  if (event.type !== 'checkout.session.completed') {
    return Response.json({ received: true });
  }
  // Retrieve through the pinned API version instead of assuming the event snapshot's shape.
  let session: Stripe.Checkout.Session;
  try { session = await stripeClient().checkout.sessions.retrieve(event.data.object.id); }
  catch { return new Response('Retry Session lookup', { status: 500 }); }
  if (session.livemode) return new Response('Test mode only', { status: 400 });
  if (session.mode !== 'payment' || session.payment_status !== 'paid') {
    return Response.json({ received: true });
  }
  try {
    await recordPayment(session, event.created * 1000);
    return Response.json({ received: true });
  } catch (error) {
    console.error('Payment analytics failed', error);
    // A failed upload remains a failed delivery, so Stripe can retry it.
    return new Response('Retry payment analytics', { status: 500 });
  }
}

I verify the signature against the original raw body. I accept only checkout.session.completed from test mode, retrieve the Session with the pinned API version, and require mode: payment, payment_status: paid, USD, and the metadata ID. Retrieving the object avoids assuming the webhook snapshot uses the SDK's API version. I still configure a deployed endpoint with 2026-10-28.endive, its own signing secret, and only the required event.

amount_usd is an ordinary numeric property for Property Sum, not a built-in Amplitude revenue event. The stable device_id and insert_id are delivery identifiers for Amplitude's seven-day deduplication window; user_id joins the browser journey. session_id: -1 keeps the asynchronous payment out of a browser session, and the timestamp comes from the original Stripe event.

Why. Completing flush().promise establishes that an upload attempt finished, not that Amplitude accepted the event. I also require a result code of 200. Stable keys protect retries within the documented seven-day window. A production system needs durable delivery state or an outbox for longer replay/recovery guarantees. This demo makes no exactly-once delivery claim beyond those boundaries.

I run the app and CLI listener in separate terminals.

Terminal 1

Terminal 1
pnpm dev

Terminal 2

Terminal 2
stripe listen --events checkout.session.completed --forward-to localhost:3000/api/stripe/webhook

I copy the listener's whsec_... value into .env.local, then restart the app. The listener secret differs from a deployed endpoint's secret. The webhook stays outside login redirects and retains signature verification. I keep order fulfillment separate from analytics acknowledgement.

6. Compare first-touch and last-touch credit

I create one data table after the test events arrive. I compare the models sequentially within the same channel view.

  1. I select Create > Chart > Data Table and add Signup Completed measured as Event Totals.
  2. I add Payment Completed as Event Totals, then another Payment Completed metric as Property Sum of amount_usd.
  3. In Select property I choose the event property utm_campaign as the outermost group-by. I do not group by the user property initial_utm_campaign.
  4. In each metric's menu I select Attribution, choose First Touch, set a seven-day lookback, and Apply. I note those three values.
  5. In the same three columns I switch Attribution to Last Touch with the same seven-day lookback and compare the values. I keep the date range fixed and include both conversions.

Report contract

Report contract
Group by: event property utm_campaign (outermost)
Metrics:  Signup Completed / Event Totals
          Payment Completed / Event Totals
          Payment Completed / Property Sum(amount_usd)
Pass 1:   First Touch, 7-day lookback
Pass 2:   Last Touch, 7-day lookback

The attribution model looks back through earlier events for that user. The server payment does not need to copy the browser's UTMs, but both streams must resolve to the same user in the same project.

First Touch means the first property value inside the conversion's lookback window, not necessarily the first campaign in that person's lifetime. The SDK's initial_utm_campaign user property is a separate mechanism. Event Totals count conversions; repeat buyers can contribute multiple payments. Unique-user metrics answer a different question, and unique users can overlap attribution groups.

Verify it worked

I use a fresh private session in the test project and keep its browser storage throughout the journey.

  1. I open http://localhost:3000/?utm_source=google&utm_medium=cpc&utm_campaign=campaign-a, confirm a page view containing utm_campaign: campaign-a in Instrumentation Explorer, then select Create demo account.
  2. I confirm Signup Completed has the displayed canonical account ID. Reloading restores that ID without another signup.
  3. In the same browser I open http://localhost:3000/?utm_source=newsletter&utm_medium=email&utm_campaign=campaign-b, confirm the campaign B page view, and select Buy for $20.
  4. I complete sandbox Checkout with Stripe's test card 4242 4242 4242 4242, a future expiry, and a valid test CVC. I never use real card details in test mode.
  5. I check browser analytics POSTs for HTTP 200 in Network, and event contents in Instrumentation Explorer. I check the CLI/server for a signed paid Session delivery acknowledged with HTTP 200. A generic stripe trigger event lacks the app's account metadata, so I use Checkout through the app.
  6. In Users > User Profiles I search the exact canonical ID. After processing, I expect the anonymous campaign A visit, signup, campaign B visit, and one payment to resolve to that person. The payment must have amount_usd: 20 and currency: USD.
  7. I compare the table values below by switching models within the same view. They are expected results for the controlled journey, not results already observed by this tutorial.
  • campaign-a. Signups: first: 1 Signups: last: 1 Payments: first: 1 Payments: last: 0 USD: first: 20 USD: last: 0
  • campaign-b. Signups: first: 0 Signups: last: 0 Payments: first: 0 Payments: last: 1 USD: first: 0 USD: last: 20

The signup precedes campaign B, so both signup models credit A. The payment follows B, so First Touch credits A and Last Touch credits B. I keep both visits inside seven days and avoid extra campaigns. To check retries I resend the same event to a deployed test endpoint within seven days and confirm the payment count stays one. Cancelling or leaving Checkout unpaid must not add a payment.

Troubleshooting

Payments appear on another user

I compare the signup ID, displayed account ID, and Session's metadata.amplitude_user_id. Prefix, casing, and project must match. A Stripe Customer ID is not the app's account ID.

Campaign rows show none

I check the first landing event in Instrumentation Explorer before signup. It must carry the event property utm_campaign. I verify event-property attribution, browser storage, the outermost group-by, and the conversion's lookback window.

Checkout returns but no payment arrives

I inspect webhook delivery instead of trusting the return URL. The listener must be running, the Price must be one-time USD, and the Session must be paid in test mode. The server needs its own AMPLITUDE_API_KEY.

The webhook returns HTTP 400

I check the correct signing secret and raw request body. This demo also rejects live-mode events. A CLI listener and a registered endpoint use different secrets.

The webhook returns HTTP 500

I check Session retrieval, USD currency, metadata, and the Amplitude result. I fix the cause before redelivery. Failure is not successful ingestion.

Payments are doubled

I look for another Stripe source or browser purchase event in the same metric. Replays beyond seven days need durable deduplication state; the stable keys alone do not establish that guarantee.

Full code reference

These complete files match the numbered steps. The example lockfile pins the dependency tree; Next.js generates next-env.d.ts on first run.

package.json

package.json
{
  "name": "nextjs-stripe-attribution-2026-11-12",
  "private": true,
  "scripts": {
    "dev": "next dev",
    "build": "next build --webpack",
    "start": "next start",
    "typecheck": "tsc --noEmit"
  },
  "engines": {
    "node": ">=24.0.0"
  },
  "packageManager": "pnpm@10.21.0+sha512.da3337267e400fdd3d479a6c68079ac6db01d8ca4f67572083e722775a796788a7a9956613749e000fac20d424b594f7a791a5f4e2e13581c5ef947f26968a40",
  "dependencies": {
    "@amplitude/unified": "1.2.1",
    "next": "16.4.5",
    "react": "19.3.0",
    "react-dom": "19.3.0",
    "@amplitude/analytics-node": "1.5.82",
    "stripe": "23.1.0",
    "server-only": "0.0.1"
  },
  "devDependencies": {
    "@types/node": "24.10.0",
    "@types/react": "19.2.18",
    "@types/react-dom": "19.2.7",
    "typescript": "5.9.3"
  }
}

pnpm-workspace.yaml

pnpm-workspace.yaml
packages:
  - .
minimumReleaseAge: 10080
trustPolicy: no-downgrade

tsconfig.json

tsconfig.json
{
  "compilerOptions": {
    "target": "ES2022",
    "lib": [
      "dom",
      "dom.iterable",
      "esnext"
    ],
    "allowJs": true,
    "skipLibCheck": true,
    "strict": true,
    "noEmit": true,
    "esModuleInterop": true,
    "module": "esnext",
    "moduleResolution": "bundler",
    "resolveJsonModule": true,
    "isolatedModules": true,
    "jsx": "react-jsx",
    "incremental": true,
    "plugins": [
      {
        "name": "next"
      }
    ],
    "baseUrl": ".",
    "paths": {
      "@/*": [
        "./*"
      ]
    }
  },
  "include": [
    "next-env.d.ts",
    "**/*.ts",
    "**/*.tsx",
    ".next/types/**/*.ts",
    ".next/dev/types/**/*.ts"
  ],
  "exclude": [
    "node_modules"
  ]
}

.gitignore

.gitignore
node_modules/
.next/
data/
.env*
!.env.example
*.tsbuildinfo

.env.example

.env.example
NEXT_PUBLIC_AMPLITUDE_API_KEY=your-project-api-key
AMPLITUDE_API_KEY=your-project-api-key
AMPLITUDE_SERVER_ZONE=US
STRIPE_SECRET_KEY=sk_test_your_sandbox_secret
STRIPE_PRICE_ID=price_your_20_usd_one_time_price
STRIPE_WEBHOOK_SECRET=whsec_from_stripe_listen
APP_URL=http://localhost:3000

app/layout.tsx

app/layout.tsx
// Keep existing fonts, metadata, authentication and providers when merging.
import type { ReactNode } from 'react';
export default function RootLayout({ children }: { children: ReactNode }) {
  return <html lang="en"><body><main>{children}</main></body></html>;
}

lib/amplitude.ts

lib/amplitude.ts
// lib/amplitude.ts
'use client';
// Keep lines other Next.js pages added here: replay masking and sampling
// (/build/nextjs-session-replay), experiment configuration
// (/build/nextjs-feature-flags), and engagement options
// (/build/nextjs-guides-surveys). Merge into your existing initAll call.
import * as amplitude from '@amplitude/unified';

declare global {
  var __campaignAmplitudeReady: Promise<void> | undefined;
}

export function amplitudeReady(): Promise<void> {
  if (typeof window === 'undefined') return Promise.resolve();
  if (!globalThis.__campaignAmplitudeReady) {
    const key = process.env.NEXT_PUBLIC_AMPLITUDE_API_KEY;
    if (!key) return Promise.reject(new Error('Missing Amplitude API key'));
    globalThis.__campaignAmplitudeReady = amplitude.initAll(key, {
      analytics: {
        remoteConfig: { fetchRemoteConfig: false },
        autocapture: {
          pageViews: true,
          attribution: { trackingMethod: ['userProperty', 'eventProperty'] },
        },
      },
      sessionReplay: { sampleRate: 0 },
      engagement: { skip: true },
    });
  }
  return globalThis.__campaignAmplitudeReady;
}

if (typeof window !== 'undefined') {
  void amplitudeReady().catch(console.error);
}

export { amplitude };

// Bound the UI wait; the SDK may finish queued work after the UI continues.
export async function bestEffortAnalytics(work: () => Promise<unknown>): Promise<void> {
  let timer: ReturnType<typeof setTimeout> | undefined;
  try {
    await Promise.race([
      work(),
      new Promise((_, reject) => { timer = setTimeout(() => reject(new Error('Analytics wait timed out')), 1500); }),
    ]);
  } catch (error) { console.error('Browser analytics unavailable', error); }
  finally { clearTimeout(timer); }
}

instrumentation-client.ts

instrumentation-client.ts
import './lib/amplitude';

lib/store.ts

lib/store.ts
import { DatabaseSync } from "node:sqlite";
import { mkdirSync } from "node:fs";
import { randomUUID } from "node:crypto";

// One local database; use a shared durable database and a worker when deploying.
const state = globalThis as typeof globalThis & { attributionDB?: DatabaseSync };
export function db() {
  if (!state.attributionDB) {
    mkdirSync("data", { recursive: true });
    const sql = new DatabaseSync("data/attribution.sqlite");
    sql.exec(`
      PRAGMA journal_mode=WAL;
      PRAGMA busy_timeout=5000;
      CREATE TABLE IF NOT EXISTS accounts (id TEXT PRIMARY KEY, token TEXT UNIQUE NOT NULL);
    `);
    state.attributionDB = sql;
  }
  return state.attributionDB;
}
export function findAccount(token?: string) {
  return (token ? db().prepare("SELECT id FROM accounts WHERE token = ?").get(token) : undefined) as { id: string } | undefined;
}
export function createAccount() {
  const account = { id: randomUUID(), token: randomUUID() };
  db().prepare("INSERT INTO accounts (id, token) VALUES (?, ?)").run(account.id, account.token);
  return account;
}

lib/session.ts

lib/session.ts
import { cookies } from "next/headers";
import { findAccount } from "./store";

export async function accountFromCookie() {
  return findAccount((await cookies()).get("stripe_attribution_demo_session")?.value);
}
export function checkOrigin(request: Request) {
  if (request.headers.get("origin") !== new URL(process.env.APP_URL!).origin) {
    throw new Error("Unexpected request origin");
  }
}

export async function getCurrentUser() { return (await accountFromCookie()) ?? null; }

app/api/account/route.ts

app/api/account/route.ts
import { NextResponse } from "next/server";
import { accountFromCookie, checkOrigin } from "../../../lib/session";
import { createAccount } from "../../../lib/store";

export const runtime = "nodejs";
export async function GET() {
  return NextResponse.json({ userId: (await accountFromCookie())?.id ?? null }, {
    headers: { "Cache-Control": "no-store" },
  });
}
export async function POST(request: Request) {
  try { checkOrigin(request); } catch { return new Response("Invalid origin", { status: 403 }); }
  const existing = await accountFromCookie();
  if (existing) return NextResponse.json({ userId: existing.id, created: false });
  const account = createAccount();
  const response = NextResponse.json({ userId: account.id, created: true });
  response.cookies.set("stripe_attribution_demo_session", account.token, {
    httpOnly: true, sameSite: "lax", path: "/", maxAge: 86400,
    secure: new URL(process.env.APP_URL!).protocol === "https:",
  });
  return response;
}

lib/amplitude-user-id.ts

lib/amplitude-user-id.ts
// lib/amplitude-user-id.ts
export function amplitudeUserId(accountId: string): string {
  if (!accountId.trim()) throw new Error('An account ID is required');
  return `user-${accountId}`;
}

lib/signup-attribution.ts

lib/signup-attribution.ts
// lib/signup-attribution.ts
'use client';
import { amplitude, amplitudeReady, bestEffortAnalytics } from '@/lib/amplitude';
import { amplitudeUserId } from '@/lib/amplitude-user-id';

// Call only after your app confirms that it created a new account.
export async function trackSignup(accountId: string): Promise<void> {
  await bestEffortAnalytics(async () => {
    await amplitudeReady();
    const userId = amplitudeUserId(accountId);
    amplitude.setUserId(userId);
    const result = await amplitude.track({
      event_type: 'Signup Completed',
      insert_id: `signup-${userId}`,
    }).promise;
    if (result.code !== 200) console.error('Signup analytics:', result.message);
  });
}

app/page.tsx

app/page.tsx
// Keep your existing routes and auth; this is the standalone demo home.
'use client';
import { useEffect, useState } from 'react';
import { CheckoutButton } from '@/components/CheckoutButton';
import { amplitude, amplitudeReady, bestEffortAnalytics } from '@/lib/amplitude';
import { amplitudeUserId } from '@/lib/amplitude-user-id';
import { trackSignup } from '@/lib/signup-attribution';
export default function Home() {
  const [accountId, setAccountId] = useState<string | null>(null);
  const [busy, setBusy] = useState(true);
  const [message, setMessage] = useState('');
  useEffect(() => {
    void (async () => {
      try {
        const response = await fetch('/api/account');
        if (!response.ok) throw new Error('Account lookup failed');
        const { userId } = await response.json();
        setAccountId(userId);
        if (userId) {
          await bestEffortAnalytics(async () => { await amplitudeReady(); amplitude.setUserId(amplitudeUserId(userId)); });
        }
      } catch { setMessage('Could not load the demo account. Reload to retry.'); }
      finally { setBusy(false); }
    })();
  }, []);
  async function signup() {
    setBusy(true); setMessage('');
    try {
      const response = await fetch('/api/account', { method: 'POST' });
      if (!response.ok) throw new Error('Demo signup failed');
      const { userId, created } = await response.json();
      setAccountId(userId);
      if (created) await trackSignup(userId);
    } catch (error) { setMessage(String(error)); }
    finally { setBusy(false); }
  }
  return <>
    <h1>Campaign checkout demo</h1>
    <p>I can create a local demo account and buy a $20 report export in Stripe's sandbox.</p>
    <p>The account is a generated ID with a cookie session. No email or password is collected.</p>
    <p>{accountId ? `Account: ${amplitudeUserId(accountId)}` : 'No demo account yet'}</p>
    <button disabled={busy || !!accountId} onClick={signup}>Create demo account</button>
    {accountId && <CheckoutButton accountId={accountId} />}
    <p role="status">{message}</p>
  </>;
}

lib/stripe.ts

lib/stripe.ts
// lib/stripe.ts
import 'server-only';
import Stripe from 'stripe';

export function stripeClient(): Stripe {
  const key = process.env.STRIPE_SECRET_KEY;
  if (!key?.startsWith('sk_test_') && !key?.startsWith('rkcs_test_')) {
    throw new Error('Use a Stripe sandbox test secret key');
  }
  return new Stripe(key, { apiVersion: '2026-10-28.endive' });
}

app/api/checkout/route.ts

app/api/checkout/route.ts
// app/api/checkout/route.ts
import { getCurrentUser } from '@/lib/session';
import { amplitudeUserId } from '@/lib/amplitude-user-id';
import { stripeClient } from '@/lib/stripe';

export const runtime = 'nodejs';

export async function POST(request: Request) {
  const appUrl = process.env.APP_URL;
  const price = process.env.STRIPE_PRICE_ID;
  if (!appUrl || !price) {
    return Response.json({ error: 'Checkout is not configured' }, { status: 500 });
  }
  // The browser cannot choose the account, price, or return URL.
  if (request.headers.get('origin') !== new URL(appUrl).origin) {
    return new Response('Invalid origin', { status: 403 });
  }
  const user = await getCurrentUser();
  if (!user) return new Response('Sign in first', { status: 401 });

  try {
  const session = await stripeClient().checkout.sessions.create({
    mode: 'payment',
    adaptive_pricing: { enabled: false },
    allowed_payment_method_types: ['card'],
    line_items: [{ price, quantity: 1 }],
    metadata: { amplitude_user_id: amplitudeUserId(user.id) },
    success_url: new URL('/?checkout=success', appUrl).toString(),
    cancel_url: new URL('/?checkout=cancelled', appUrl).toString(),
  });
  if (!session.url) {
    return Response.json({ error: 'No Checkout URL returned' }, { status: 502 });
  }
  return Response.json({ url: session.url });
  } catch (error) {
    console.error("Checkout failed", error);
    return new Response("Checkout unavailable", { status: 502 });
  }
}

components/CheckoutButton.tsx

components/CheckoutButton.tsx
// components/CheckoutButton.tsx
'use client';
import { useState } from 'react';
import { amplitude, amplitudeReady, bestEffortAnalytics } from '@/lib/amplitude';
import { amplitudeUserId } from '@/lib/amplitude-user-id';

export function CheckoutButton({ accountId }: { accountId: string }) {
  const [busy, setBusy] = useState(false);
  const [error, setError] = useState('');

  async function checkout() {
    setBusy(true);
    setError('');
    try {
      // Keep checkout usable even if browser analytics is blocked.
      await bestEffortAnalytics(async () => {
        await amplitudeReady();
        amplitude.setUserId(amplitudeUserId(accountId));
        await amplitude.track('Checkout Started').promise;
      });
      const response = await fetch('/api/checkout', { method: 'POST' });
      if (!response.ok) throw new Error('Could not start checkout. Try again.');
      const { url } = await response.json();
      window.location.assign(url);
    } catch (checkoutError) {
      setError(checkoutError instanceof Error ? checkoutError.message : 'Checkout failed');
      setBusy(false);
    }
  }

  return <>
    <button onClick={checkout} disabled={busy}>
      {busy ? 'Opening checkout...' : 'Buy for $20'}
    </button>
    {error && <p role="alert">{error}</p>}
  </>;
}

lib/payment-analytics.ts

lib/payment-analytics.ts
// lib/payment-analytics.ts
import 'server-only';
import { createInstance } from '@amplitude/analytics-node';
import type Stripe from 'stripe';

const billing = createInstance();
let ready: Promise<void> | undefined;

export async function recordPayment(session: Stripe.Checkout.Session, time: number) {
  const userId = session.metadata?.amplitude_user_id;
  if (!userId || userId.length < 5) throw new Error('Missing Amplitude user ID');
  if (session.currency !== 'usd' || session.amount_total == null) {
    throw new Error('This example requires a USD payment amount');
  }
  const key = process.env.AMPLITUDE_API_KEY;
  if (!key) throw new Error('Missing AMPLITUDE_API_KEY');
  ready ??= billing.init(key, { requestTimeoutMillis: 3000, flushMaxRetries: 1, serverZone: process.env.AMPLITUDE_SERVER_ZONE === 'EU' ? 'EU' : 'US' }).promise;
  await ready;

  const pending = billing.track('Payment Completed', {
    checkout_session_id: session.id,
    amount_usd: session.amount_total / 100,
    currency: 'USD',
  }, {
    user_id: userId,
    // Stable on both webhook redelivery and a separate event for this Session.
    device_id: `stripe-${session.id}`,
    insert_id: `checkout-paid-${session.id}`,
    time,
    session_id: -1,
  });
  await billing.flush().promise;
  const result = await pending.promise;
  if (result.code !== 200) throw new Error(`Amplitude upload failed: ${result.code}`);
}

app/api/stripe/webhook/route.ts

app/api/stripe/webhook/route.ts
// app/api/stripe/webhook/route.ts
import type Stripe from 'stripe';
import { stripeClient } from '@/lib/stripe';
import { recordPayment } from '@/lib/payment-analytics';

export const runtime = 'nodejs';

export async function POST(request: Request) {
  const signature = request.headers.get('stripe-signature');
  const secret = process.env.STRIPE_WEBHOOK_SECRET;
  if (!secret) return new Response('Webhook is not configured', { status: 500 });
  if (!signature) return new Response('Missing signature', { status: 400 });

  let event: Stripe.Event;
  try {
    event = stripeClient().webhooks.constructEvent(
      await request.text(), signature, secret,
    );
  } catch {
    return new Response('Invalid signature', { status: 400 });
  }
  if (event.livemode) return new Response('Test mode only', { status: 400 });
  if (event.type !== 'checkout.session.completed') {
    return Response.json({ received: true });
  }
  // Retrieve through the pinned API version instead of assuming the event snapshot's shape.
  let session: Stripe.Checkout.Session;
  try { session = await stripeClient().checkout.sessions.retrieve(event.data.object.id); }
  catch { return new Response('Retry Session lookup', { status: 500 }); }
  if (session.livemode) return new Response('Test mode only', { status: 400 });
  if (session.mode !== 'payment' || session.payment_status !== 'paid') {
    return Response.json({ received: true });
  }
  try {
    await recordPayment(session, event.created * 1000);
    return Response.json({ received: true });
  } catch (error) {
    console.error('Payment analytics failed', error);
    // A failed upload remains a failed delivery, so Stripe can retry it.
    return new Response('Retry payment analytics', { status: 500 });
  }
}

Hand it to your agent

I provide this tutorial with the following implementation prompt.

Agent prompt

Agent prompt
Build the supplied standalone Next.js Stripe attribution demo, preserving the
agreed title and /build/nextjs-stripe-attribution slug. In an existing app,
merge into the single Amplitude initializer; preserve auth, routes, consent,
replay masking, flags, and other instrumentation. Replace demo accounts with
the real validated server session, keeping the established canonical user ID.
Capture UTMs as event and user properties, identify confirmed signups, and
create a one-time USD Checkout from server identity/Price only. Keep Stripe
secrets server-only and use test mode with the pinned API version. Verify the
raw-body signature, retrieve the Session, accept only paid test-mode payment
Sessions, flush and check the event result, and use stable deduplication keys.
Compare First Touch and Last Touch sequentially in one channel view, both
with a seven-day lookback. Do not claim live ingestion, report results, or
exactly-once delivery without evidence. Report changed files and test limits.
Do not publish or alter a production project.

What this unlocks

Product analytics connects the campaign visit to Signup Completed and Payment Completed for the same person.

Session replay can add journey context after I explicitly configure recording and its privacy controls. Payment acknowledgement still comes from the webhook.

Next steps

FAQ

Is this subscription revenue attribution?

This implementation counts one-time paid Checkout Sessions. Subscription invoice payments, renewals, refunds, and net revenue require different handlers and reporting definitions.

Does the payment need the browser's device ID or UTMs?

The payment uses the same canonical user ID to connect with earlier browser events. Its billing device ID supports delivery deduplication. The report looks back for campaign values on that person's earlier events.

Is first-touch attribution the initial campaign user property?

The chart's First Touch model uses the first property value in its lookback window. initial_utm_campaign records a separate acquisition user property; changing the chart window does not change it.

Can I trust the browser's Checkout return as payment confirmation?

The return page can be skipped or revisited. I count the payment only after the signed webhook and paid Session check.

Follow the campaign journey

Connect campaign visits, signups, and Stripe payments in a test project.