DocsStorefront integrationTrack share links
Coming soon Kwik's public API and MCP server are coming soon. These docs are an early preview, in the beginning stages: endpoints, fields and examples are samples and will change before launch. Brands on Kwik today can ask their account manager about integrations.
Read every docs page as one Markdown file, ready to paste into ChatGPT, Claude or any AI assistant.
Storefront integration · Guide 1 of 4Track Kwik Share Links Through Checkout.
Keep the referral code from the shopper's first visit all the way to the finished order, so Kwik credits the right rep. Works on a Shopify theme, a Hydrogen or other headless storefront, or any website with its own checkout.
Before you start
- Pick your path below: a Shopify theme, Hydrogen (or any headless Shopify build), or any other website.
- Kwik set up for the store, and one working share code to test with (we use
ABC123). - Hydrogen: your cart query fragment includes
attributes { key value }. - Shopify themes: the Kwik 2.0 app installed, with its Referral Attribution app embed turned on.
- Other websites: you control what is saved on each order. See what to send on every order.
How attribution travels
A shopper opens a rep's link: /products/hoodie?waveLink=ABC123. The code has to survive every page they visit after that, then land on the order.
- Read the
waveLinkparameter. The name is case-sensitive, and so is the code. KeepABC123exactly as it came in. - Store it in a first-party cookie,
_kwik_waveLink, for 30 days. Links on later pages won't carry the parameter. - Write it to the Shopify cart as the
waveLinkattribute, keeping any attributes already on the cart. - Check the finished order for
waveLink = ABC123, then confirm Kwik credited the right rep.
A newer link replaces an older one: the cookie and the cart attribute always hold the last code the shopper followed.
| Your site | How the code reaches the order | Jump to |
|---|---|---|
| Shopify theme (Liquid) | The Referral Attribution app embed does it. No code. | [Liquid themes](#liquid) |
| Hydrogen or headless Shopify | Your code: cookie, cart attribute, every checkout path | [Hydrogen 1 to 3](#read) |
| Any other website | A copy-paste snippet, then save the code on your order | [Any other website](#any-site) |
Needs confirmationWhich field a store's Kwik integration reads can differ by setup: the cart attribute waveLink, a hidden line attribute _kwik_waveLink (Kwik 2.0 app stores), or the order tag waveLink=ABC123. The samples below set the cart and line attributes together, which is safe. Ask your Kwik contact which one your store uses before launch.
Hydrogen 1: Read the code and set the cookie
Read the code on the server, in the root loader, so it works on the very first request, even before JavaScript runs. Only accept 1 to 64 letters and digits.
// app/lib/kwik-attribution.server.ts
// Reads a Kwik share code from the URL or the attribution cookie.
const PARAM = 'waveLink'; // exact case: ?waveLink=ABC123
const COOKIE = '_kwik_waveLink';
const MAX_AGE = 60 * 60 * 24 * 30; // 30 days
const VALID = /^[A-Za-z0-9]{1,64}$/; // keep the code's case as-is
export function readWaveLink(request: Request) {
const fromUrl = new URL(request.url).searchParams.get(PARAM);
if (fromUrl && VALID.test(fromUrl)) return {code: fromUrl, fromUrl: true};
const cookies = request.headers.get('Cookie') ?? '';
const match = cookies.match(/(?:^|;\s*)_kwik_waveLink=([A-Za-z0-9]{1,64})(?:;|$)/);
return {code: match ? match[1] : null, fromUrl: false};
}
export function waveLinkCookie(code: string) {
return `${COOKIE}=${code}; Max-Age=${MAX_AGE}; Path=/; SameSite=Lax; Secure`;
}
// app/root.tsx (loader only). Uses React Router 7 / current Hydrogen imports.
import {data, type LoaderFunctionArgs} from 'react-router';
import {readWaveLink, waveLinkCookie} from '~/lib/kwik-attribution.server';
import {syncCartWaveLink} from '~/lib/kwik-cart.server';
export async function loader({request, context}: LoaderFunctionArgs) {
const {code, fromUrl} = readWaveLink(request);
const headers = new Headers();
if (code && fromUrl) {
headers.append('Set-Cookie', waveLinkCookie(code)); // 30-day first-party cookie
await syncCartWaveLink(context.cart, code); // updates a cart that already exists
}
// ...your existing root data
return data({waveLink: code}, {headers});
}
Hydrogen 2: Write it to the cart
Shopify's cartAttributesUpdate replaces the whole attribute list. Read the cart first and merge, or you will wipe attributes other apps set, like gift notes or delivery dates.
// app/lib/kwik-cart.server.ts
// Writes the code to the cart as the `waveLink` attribute and keeps every other attribute.
// cartAttributesUpdate replaces the whole list, so merge before you write.
// Your cart query fragment must include: attributes { key value }
import type {HydrogenCart} from '@shopify/hydrogen';
export async function syncCartWaveLink(cart: HydrogenCart, code: string | null) {
if (!code) return null;
const current = await cart.get();
if (!current) return null; // no cart yet: the cart action adds it on the first add
const attrs = current.attributes ?? [];
if (attrs.some((a) => a.key === 'waveLink' && a.value === code)) return null; // already set
const kept = attrs
.filter((a) => a.key !== 'waveLink')
.map(({key, value}) => ({key, value: value ?? ''}));
return cart.updateAttributes([...kept, {key: 'waveLink', value: code}]);
}
Hydrogen 3: Cover every path to checkout
Every add to cart must end with the attribute set. Route them all through one cart action and set it there.
| Path | What to do |
|---|---|
| Product page add to cart | Goes through the cart action. Covered. |
| Quick-add on product cards | Use the same CartForm and cart action, not a separate client-side Storefront API call. |
| Cart drawer and upsells | Same cart action. The attribute is checked again after every change. |
| First add (no cart yet) | The first add creates the cart, so the action sets the attribute after the add, not before. |
| "Buy now" or direct checkout | Skips the cart. Create the cart with the attribute already on it, then send the shopper to checkoutUrl. |
// app/routes/cart.tsx (action). Every add to cart goes through here:
// the product page, quick-add on cards, the cart drawer and upsells.
import {CartForm} from '@shopify/hydrogen';
import {data, type ActionFunctionArgs} from 'react-router';
import {readWaveLink} from '~/lib/kwik-attribution.server';
import {syncCartWaveLink} from '~/lib/kwik-cart.server';
export async function action({request, context}: ActionFunctionArgs) {
const {cart} = context;
const formData = await request.formData();
const {action, inputs} = CartForm.getFormInput(formData);
const {code} = readWaveLink(request); // from the 30-day cookie
let result;
switch (action) {
case CartForm.ACTIONS.LinesAdd: {
// Kwik 2.0 app stores: also tag each new line (hidden from shoppers because of the "_").
const lines = code
? inputs.lines.map((l) => ({...l, attributes: [...(l.attributes ?? []), {key: '_kwik_waveLink', value: code}]}))
: inputs.lines;
result = await cart.addLines(lines);
break;
}
// ...your other cart actions (LinesUpdate, LinesRemove, DiscountCodesUpdate)
default:
result = await cart.get();
}
// The first add creates the cart, so set the cart attribute after every action.
const synced = await syncCartWaveLink(cart, code);
const finalCart = synced?.cart ?? result?.cart;
const headers = finalCart?.id ? cart.setCartId(finalCart.id) : new Headers();
return data({cart: finalCart, errors: result?.errors}, {headers});
}
// app/routes/buy-now.tsx (action). A "Buy now" button that skips the cart
// still needs the code, so create the cart with the attribute already on it.
import {redirect, type ActionFunctionArgs} from 'react-router';
import {readWaveLink} from '~/lib/kwik-attribution.server';
export async function action({request, context}: ActionFunctionArgs) {
const form = await request.formData();
const merchandiseId = String(form.get('merchandiseId'));
const {code} = readWaveLink(request);
const {cart} = await context.cart.create({
lines: [{
merchandiseId,
quantity: 1,
attributes: code ? [{key: '_kwik_waveLink', value: code}] : [],
}],
attributes: code ? [{key: 'waveLink', value: code}] : [],
});
return redirect(cart.checkoutUrl);
}
Find it on the Shopify order
In Shopify admin, open the order. Cart attributes show in the Additional details card: you should see waveLink with the value ABC123. In the Admin API it is in customAttributes (GraphQL) or note_attributes (REST webhooks).
Line attributes that start with an underscore, like _kwik_waveLink, are hidden from shoppers at checkout.
When you also need the order tag
Some setups also want the literal tag waveLink=ABC123 on the order. Add it when:
- Your Kwik contact says your store's integration reads order tags.
- The merchant wants to filter or export referred orders in Shopify admin. Tags are searchable there. Attributes are not.
Add the tag on the server after the order exists, never from the browser. Two ways: a Shopify Flow workflow (Order created → check the waveLink attribute → Add order tags), or an orders/create webhook in your own app:
// Server only: a webhook handler in your own Shopify app (needs the write_orders scope).
// Topic: orders/create. Verify the X-Shopify-Hmac-Sha256 header before trusting the body.
export async function handleOrderCreated(order: any, adminGraphql: (q: string, v: object) => Promise<any>) {
const attr = (order.note_attributes ?? []).find((a: any) => a.name === 'waveLink');
const code = attr?.value;
if (!code || !/^[A-Za-z0-9]{1,64}$/.test(code)) return;
await adminGraphql(
`mutation AddTag($id: ID!, $tags: [String!]!) {
tagsAdd(id: $id, tags: $tags) { userErrors { field message } }
}`,
{id: order.admin_graphql_api_id, tags: [`waveLink=${code}`]},
);
}
Shopify themes: what changes
- Turn on the Kwik 2.0 Referral Attribution app embed (Online Store → Themes → Customize → App embeds). It reads
waveLink,wavelinkorkwiklinkfrom the URL and sets the 30-day_kwik_waveLinkcookie for you. - App embeds don't run on Hydrogen. That is why the code above exists.
- If your theme needs the
waveLinkcart attribute too,/cart/update.jsonly changes the attributes you send, so other attributes stay put. - Test custom quick-add buttons and drawer carts the same way. A theme that builds its own checkout links can skip the cart.
<!-- Liquid theme: only for custom cart code. With the Kwik 2.0 "Referral Attribution"
app embed turned on, the cookie is already handled for you. -->
<script>
(function () {
var VALID = /^[A-Za-z0-9]{1,64}$/;
var code = new URLSearchParams(location.search).get('waveLink');
if (!code || !VALID.test(code)) {
var m = document.cookie.match(/(?:^|;\s*)_kwik_waveLink=([A-Za-z0-9]{1,64})/);
code = m ? m[1] : null;
} else {
document.cookie = '_kwik_waveLink=' + code + '; Max-Age=2592000; Path=/; SameSite=Lax; Secure';
}
if (!code) return;
// /cart/update.js changes only the attributes you send, so other attributes stay.
fetch('/cart/update.js', {
method: 'POST',
headers: {'Content-Type': 'application/json'},
body: JSON.stringify({attributes: {waveLink: code}})
});
})();
</script>
Any other website
Not on Shopify, or building your own checkout? The idea is the same on any site: remember the code for 30 days, save it on the order, and send it to Kwik with the order. Paste this snippet before </body> on every page:
<!-- Kwik share-link snippet for any website. Paste before </body> on every page.
It keeps the code for 30 days and puts it wherever your checkout can pick it up. -->
<script>
(function () {
var VALID = /^[A-Za-z0-9]{1,64}$/; // letters and digits, case kept as-is
var COOKIE = '_kwik_waveLink';
var DAYS = 30;
function readCookie() {
var m = document.cookie.match(/(?:^|;\s*)_kwik_waveLink=([A-Za-z0-9]{1,64})(?:;|$)/);
return m ? m[1] : null;
}
// 1. Read ?waveLink=ABC123 (exact case) and remember it. A newer link replaces an older one.
var fromUrl = new URLSearchParams(location.search).get('waveLink');
if (fromUrl && VALID.test(fromUrl)) {
document.cookie = COOKIE + '=' + fromUrl + '; Max-Age=' + (DAYS * 86400) + '; Path=/; SameSite=Lax; Secure';
try {
localStorage.setItem('kwik_landing', JSON.stringify({ url: location.href, at: new Date().toISOString() }));
} catch (e) {}
}
// 2. Give your checkout code one function to call.
window.KwikAttribution = {
code: function () { return readCookie(); },
landing: function () {
try { return JSON.parse(localStorage.getItem('kwik_landing') || 'null'); } catch (e) { return null; }
},
// The "attribution" object for the order body
forOrder: function () {
var l = this.landing();
return this.code() ? { wave_link: this.code(), landing_url: l && l.url, first_seen_at: l && l.at } : null;
}
};
// 3. Server-rendered checkout forms: add a hidden field to any form marked data-kwik-checkout.
function fillForms() {
var code = readCookie();
if (!code) return;
document.querySelectorAll('form[data-kwik-checkout]').forEach(function (form) {
var input = form.querySelector('input[name="wave_link"]');
if (!input) {
input = document.createElement('input');
input.type = 'hidden';
input.name = 'wave_link';
form.appendChild(input);
}
input.value = code;
});
}
document.addEventListener('DOMContentLoaded', fillForms);
document.addEventListener('submit', fillForms, true);
})();
</script>
Then get the code onto the order, whichever way your checkout works:
- Server-rendered checkout form: add
data-kwik-checkoutto the form. The snippet adds a hiddenwave_linkfield, and your server saves it on the order. - JavaScript checkout: call
KwikAttribution.forOrder()and include it when you create the order. - A platform with order custom fields (like WooCommerce, BigCommerce or Squarespace): copy the
_kwik_waveLinkcookie into an order field at checkout.
// A JavaScript checkout: include the attribution when you create the order.
const res = await fetch('/api/checkout', {
method: 'POST',
headers: {'Content-Type': 'application/json'},
body: JSON.stringify({
cart, // your own cart
attribution: window.KwikAttribution?.forOrder(), // {wave_link, landing_url, first_seen_at} or null
}),
});
// Save attribution.wave_link on your order record. It goes to Kwik with the order.
<?php
// Example for a WooCommerce store (functions.php or a small plugin).
// Copies the share code from the 30-day cookie onto the order when it is created.
add_action('woocommerce_checkout_create_order', function ($order) {
$code = $_COOKIE['_kwik_waveLink'] ?? '';
if (preg_match('/^[A-Za-z0-9]{1,64}$/', $code)) {
$order->update_meta_data('waveLink', $code);
}
});
// The code is then on the order as the "waveLink" custom field.
// Send it as attribution.wave_link with the rest of the order body.
However it is saved, the code goes to Kwik as attribution.wave_link in the order body. See what to send on every order for every field.
NoteKwik's built-in store connection is for Shopify. On other platforms, the snippet and order body on these pages are how you connect today, with the details set up with your Kwik contact.
End-to-end test
- Open a private window and go to
/products/hoodie?waveLink=ABC123. - Check the browser cookies:
_kwik_waveLink=ABC123, about 30 days to expire. - Click to another page, like a collection. The URL no longer has the code.
- Quick-add a different product (a cap) from a product card. Open the cart drawer.
- Check the cart: attributes include
waveLink=ABC123, and the cap line has_kwik_waveLink. - Check out with a test payment.
- In Shopify admin, the order shows
waveLink=ABC123under Additional details (and the tagwaveLink=ABC123, if you add tags). - In Kwik, confirm the order is credited to the rep behind
ABC123. - Repeat with "Buy now", and once with a second link (
?waveLink=XYZ789) to confirm the newer code wins.