Browse guides
SvelteKit
Add the snippet to app.html and credit Checkout Sessions in a form action.
2 min read · For companies
Read Install tracking first for what the two pieces do.
1. The snippet in app.html
src/app.html
<head>
%sveltekit.head%
<script async src="https://rewards.acme.com/v1/br.js"></script>
</head>2. Credit the checkout in a form action
src/lib/server/betterrewards.ts
import type Stripe from "stripe";
// betterrewards: copy this file into your app. It has no dependencies.
const CLICK_ID = /^clk_[0-9a-f]{32}$/;
/** A click id stored by the snippet, or null. Pass the br_click cookie's value. */
export function clickId(value: string | null | undefined): string | null {
return value && CLICK_ID.test(value) ? value : null;
}
/** Reads the click id from a raw Cookie header. */
export function clickIdFromCookieHeader(header: string | null | undefined): string | null {
const match = header?.match(/(?:^|;\s*)br_click=([^;]+)/);
return clickId(match?.[1] ? decodeURIComponent(match[1]) : null);
}
/** Credits a Checkout Session, and the subscription it starts, to the referring partner. */
export function withReferral(
params: Stripe.Checkout.SessionCreateParams,
id: string | null,
): Stripe.Checkout.SessionCreateParams {
if (!id) return params;
return {
...params,
client_reference_id: params.client_reference_id ?? id,
metadata: { ...params.metadata, br_click_id: id },
...(params.mode === "subscription" && {
subscription_data: {
...params.subscription_data,
metadata: { ...params.subscription_data?.metadata, br_click_id: id },
},
}),
};
}
/** Metadata for stripe.customers.create at signup, so later payments need no cookie. */
export function referralMetadata(id: string | null): Record<string, string> {
return id ? { br_click_id: id } : {};
}src/routes/pricing/+page.server.ts
import { redirect } from "@sveltejs/kit";
import { clickId, withReferral } from "$lib/server/betterrewards";
import { stripe } from "$lib/server/stripe";
export const actions = {
default: async ({ cookies }) => {
const id = clickId(cookies.get("br_click"));
const session = await stripe.checkout.sessions.create(withReferral({
mode: "subscription",
line_items: [{ price: "price_123", quantity: 1 }],
success_url: "https://app.acme.com/welcome",
cancel_url: "https://www.acme.com/pricing",
}, id));
redirect(303, session.url!);
},
};Create Stripe customers at signup? Add metadata: referralMetadata(id) to stripe.customers.create as well. Every later payment of that customer is then credited without the cookie, even weeks later or after Safari has cleared it.
Then check it in your instance under Integrations → Tracking & links: Open test page proves the snippet runs on your site, and a test payment followed by I've paid, check now proves the click reaches Stripe. Nobody is credited for the test.