
# Web SDK

`@kerdly/web` gives each visitor a first-party id, records page visits and clicks on your app links,
and passes the visitor on to the app store or your web checkout. Kerdly then connects the ad click
that brought the visitor to the install, sign-up or purchase that follows.

- Package: [`@kerdly/web`](https://www.npmjs.com/package/@kerdly/web) on npm, or the snippet at
  `https://cdn.kerdly.com/v1/kerdly.js`.
- No runtime dependencies. The snippet is about 4 KB gzipped.
- Source and changelog: [github.com/Kerdly/kerdly-sdk/tree/main/web](https://github.com/Kerdly/kerdly-sdk/tree/main/web).

## Before you start

You need the project's **web key** (`wk_live_…`). It is made with the website: open the Web app's
**Settings → SDK** in the dashboard, which shows the snippet with the key filled in. It is public and
safe to put in a page. If the site also sells
something, its Web app needs a **server key** (`sk_live_…`) for your server; see
[Report purchases from your server](#report-purchases-from-your-server).

## Install

Pick one. Both behave the same.

### Option A: the snippet

Put this in the `<head>` of every page:

```html
<script src="https://cdn.kerdly.com/v1/kerdly.js" data-key="wk_live_…" async></script>
```

It records a visit for the page, handles clicks on your app links, and exposes the instance as
`window.kerdly`. It loads `async`, so check that `window.kerdly` exists before calling it.

`/v1/kerdly.js` is always the newest release, so your site gets fixes without a change on your
side. Every release behind that address stays compatible with the one before it; a breaking change
would get a new address (`/v2/`).

To review each update yourself, pin a release instead. Its file never changes, and the `integrity`
attribute makes the browser refuse anything else:

```html
<script src="https://cdn.kerdly.com/0.1.0/kerdly.js"
        integrity="sha384-…" crossorigin="anonymous"
        data-key="wk_live_…" async></script>
```

Each release's `integrity` value is in its
[GitHub release notes](https://github.com/Kerdly/kerdly-sdk/releases) and in
[cdn.kerdly.com/versions.json](https://cdn.kerdly.com/versions.json).

TypeScript types for `window.kerdly`:

```ts
import type { Kerdly } from "@kerdly/web";
declare global { interface Window { kerdly?: Kerdly } }
```

### Option B: npm

```sh
npm install @kerdly/web
```

```ts
import { createKerdly } from "@kerdly/web";

const kerdly = createKerdly({ key: "wk_live_…" });
```

Create one instance per page load, once, in the browser. Importing the package is safe in
server-rendered code; on the server `createKerdly` returns an instance that does nothing.

### Next.js (App Router)

A small client component, rendered once in the root layout:

```tsx
// app/kerdly.tsx
"use client";

import { useEffect } from "react";
import { usePathname } from "next/navigation";
import { createKerdly, type Kerdly } from "@kerdly/web";

let kerdly: Kerdly | null = null;

export function getKerdly(): Kerdly {
  kerdly ??= createKerdly({ key: process.env.NEXT_PUBLIC_KERDLY_WEB_KEY! });
  return kerdly;
}

export function KerdlyTracker() {
  const pathname = usePathname();
  useEffect(() => {
    getKerdly().visit(); // the first call records the landing page; later calls each new route
  }, [pathname]);
  return null;
}
```

```tsx
// app/layout.tsx
import { KerdlyTracker } from "./kerdly";

export default function RootLayout({ children }: { children: React.ReactNode }) {
  return (
    <html lang="en">
      <body>
        {children}
        <KerdlyTracker />
      </body>
    </html>
  );
}
```

`createKerdly` records the first visit itself, and `visit()` ignores a repeat for the same URL, so
the effect's first run does no harm.

### Single-page apps

The SDK records the landing page once. In a single-page app, call `kerdly.visit()` after each route
change. A repeat for the same URL is ignored unless you pass `{ force: true }`.

## Mark your app links

Add `data-kerdly-link` to every link that leads to your app: your Kerdly links or store links.

```html
<a href="https://apps.apple.com/app/id1234567890" data-kerdly-link>Get Tallybird for iPhone</a>
<a href="https://play.google.com/store/apps/details?id=com.example.tallybird" data-kerdly-link>Get it on Google Play</a>
```

When one is clicked, the SDK records the click and adds the visitor id to the link, then lets the
browser navigate as usual. New-tab and middle clicks work, and links added to the page later are
covered. For navigation in your own code:

```ts
location.href = kerdly.click("https://apps.apple.com/app/id1234567890");
```

## Identify signed-in users

If your site has accounts, tell Kerdly who the visitor is after sign-in, so events your server
reports for that user are credited to the visitor's ad click:

```ts
onAuthStateChanged(auth, (user) => {
  if (user) kerdly.identify(user.uid);
});
```

`userId` is a string of 1 to 128 characters: the same id your server uses when it reports events.
Repeating the call is free; it is sent once.

If Kerdly reads your charges from Paddle or Stripe, your checkout puts this same id in Paddle's
custom data or Stripe's metadata, under the field set as the Web app's **User id field**
(`kerdly_user_id` unless you change it). That is how a charge finds the visit and the ad behind it;
see [Sell on your website](https://kerdly.com/docs/guides/web-checkout.md#4-paddle-or-stripe-connect-it-no-server-code).

## Ad pixels

If the page also runs the Meta or TikTok pixel, give pixel events an id from `eventId`. Kerdly
sends its own copy of the event under the same id, so the network counts it once:

```js
fbq("track", "Lead", {}, { eventID: kerdly.eventId("Lead") });
ttq.track("ViewContent", {}, { event_id: kerdly.eventId("ViewContent") });
```

For a purchase, use your order id as the pixel's `eventID` instead, and send the same id as the
server event's `event_id` (see [deduplication](https://kerdly.com/docs/guides/events-and-dedupe.md)).

## Report purchases from your server

Which payment event maps to which Kerdly event, with a Stripe example, is in
[Track the whole funnel](https://kerdly.com/docs/sdks/funnel.md#setup-2-a-website-that-sells-on-the-web), and the
full Stripe walkthrough with webhooks and refunds is in [Sell on your website](https://kerdly.com/docs/guides/web-checkout.md).

On the web, trials and purchases come from your server, which knows they really happened, or
straight from Paddle or Stripe when you
[connect them](https://kerdly.com/docs/guides/web-checkout.md#4-paddle-or-stripe-connect-it-no-server-code) (then skip
this section for that provider). Your server sends them with the Web app's **server key** to `POST /v1/s2s/events`. Kerdly joins each
one to the visitor you identified and, if you turned on postbacks, forwards it to your ad networks.

Get the key from the Web app's **Settings → SDK → Server keys and key rotation**. It is shown once; keep it in your
server's secrets.

```sh
curl https://app.kerdly.com/api/v1/s2s/events \
  -H "Authorization: Bearer $KERDLY_SERVER_KEY" \
  -H "Content-Type: application/json" \
  -d '{
    "events": [{
      "event_id": "ch_3Q9tallybird0001",
      "name": "subscribe",
      "ts": 1793900000000,
      "user_id": "user_8f2k1",
      "props": {
        "product_id": "tallybird_pro_annual",
        "transaction_id": "ch_3Q9tallybird0001",
        "value": 39.99,
        "net_value": 36.12,
        "currency": "USD",
        "store": "stripe",
        "product_kind": "subscription",
        "subscription_id": "sub_1Q9tallybird"
      }
    }]
  }'
```

| Field | Required | |
|---|---|---|
| `event_id` | yes | Your id for the event, 1 to 64 characters. A repeat is answered as a duplicate, so retries are safe. |
| `name` | yes | `start_trial`, `subscribe`, `trial_conversion`, `renewal`, `purchase`, `refund`, or a custom name. |
| `ts` | yes | When it happened, in milliseconds since the epoch. |
| `user_id`, `visitor_id` | one of them | The id you passed to `identify`, or `kerdly.visitorId()` from the page. |
| `props` | no | `value` (what the customer paid), `net_value` (what you keep after fees and taxes, same currency), `currency`, `product_id`, `transaction_id`, `store` (`stripe`, `paddle`, … or `web`), `product_kind`, `subscription_id`. A `refund` needs the `transaction_id` of the charge it refunds. |
| `environment` | no | `production` (default) or `sandbox`. |

Up to 100 events per request. The answer lists each event as accepted, duplicate or rejected:

```json
{ "accepted": ["ch_3Q9tallybird0001"], "duplicates": [], "rejected": [] }
```

A rejected event carries its `index` and a `reason`: `invalid_event`, `invalid_name`,
`reserved_name`, `invalid_props`, `invalid_ts`, `missing_user` or `invalid_overrides`.

## Options

| Option | Snippet attribute | Default | |
|---|---|---|---|
| `key` | `data-key` | required | The project's web key (`wk_live_…`). The SDK refuses a secret `sk_` key. |
| `endpoint` | `data-endpoint` | `https://app.kerdly.com/api` | Where data is sent. |
| `cookieDomain` | `data-cookie-domain` | your site's main domain | Set it if the site is on a shared hosting domain (`*.vercel.app`, `*.github.io`) or an unusual country domain. |
| `visitorCookie` | `data-visitor-cookie` | `kerdly_vid` | Name an existing first-party id cookie to reuse it. It must be readable by JavaScript (not `HttpOnly`). |
| `autoVisit` | | `true` | Record a visit when the SDK starts. |
| `autoDecorate` | `data-auto-decorate` | `a[data-kerdly-link]` | Which links are app links: a CSS selector, or `false` to turn it off. |
| `ipv6EchoUrl` | `data-ipv6-echo-url` | on | Looks up the visitor's public IPv6 address once per tab. `null` (or an empty attribute) turns it off. |

## API

No method throws.

| Method | Returns | |
|---|---|---|
| `kerdly.visit(options?)` | `boolean` | Records a visit to the current page. A repeat for the same URL is ignored unless `{ force: true }`. |
| `kerdly.click(url)` | `string` | Records a click on an app link and returns the URL to navigate to. |
| `kerdly.decorate(url)` | `string` | Returns the URL with the visitor id added, without recording a click. |
| `kerdly.identify(userId)` | `boolean` | Links this visitor to your own user id. |
| `kerdly.eventId(name)` | `string` | An event id to share between a browser pixel event and the same event from your server. |
| `kerdly.visitorId()` | `string` | The visitor id. |

## Content-Security-Policy

If your site sends a CSP, allow `https://cdn.kerdly.com` in `script-src` (snippet only), and
`https://app.kerdly.com` and `https://api6.ipify.org` (the IPv6 lookup) in `connect-src`.

## Cookies and storage

| Name | Where | Lifetime | Purpose |
|---|---|---|---|
| `kerdly_vid` (or your `visitorCookie`) | first-party cookie | 400 days (7 days in Safari for script-set cookies) | The visitor id |
| `_fbc` | first-party cookie | 90 days | Meta's click cookie, written when the URL has an `fbclid`, the same way Meta's pixel does |
| `kerdly_uid` | `localStorage` | until cleared | Remembers the last `identify`, so it isn't sent twice |
| `kerdly_ip6` | `sessionStorage` | the tab session | The result of the IPv6 lookup |

The SDK reads Meta's `_fbp` and TikTok's `_ttp` cookies but never writes them. Cookies are
`SameSite=Lax`, and `Secure` on https pages.

## Consent

Nothing is stored or sent before `createKerdly` runs or the snippet loads. On a page that waits for
consent, load the snippet or call `createKerdly` after the visitor agrees.

To start fully passive and decide yourself when to send:

```ts
const kerdly = createKerdly({ key: "wk_live_…", autoVisit: false, autoDecorate: false, ipv6EchoUrl: null });
```

Each visit or click sends the page URL and title, the referrer, the visitor id, the Meta and TikTok
cookies above, the browser's user agent (from 0.1.1), and the visitor's public IPv6 address when
available.

## Check it's working

1. Open your page with a test campaign tag, for example `?utm_source=test&utm_campaign=docs_check`.
2. In the browser's network tab, look for a `POST` to `app.kerdly.com/api/v1/web/touch` answered
   with a success status.
3. In the dashboard, the Web app's **Onboarding** page shows the tag step with the time of the last
   visit.

## Troubleshooting

- Warnings in the browser console start with `[Kerdly]`.
- The visitor id changes on every page load: the cookie named in `visitorCookie` is `HttpOnly`, or
  the browser refused `cookieDomain`. Use the default cookie or fix the domain.
- Questions or problems: [open an issue](https://github.com/Kerdly/kerdly-sdk/issues) or contact
  Kerdly support. Never post your keys.

---

Source: https://kerdly.com/docs/sdks/web. Index of all docs: https://kerdly.com/llms.txt
