# Site analytics.

One script tag counts page views, visitors, referrers and UTM campaigns for your site, with no cookies. The events land in the same dif analytics project as your experiments, so dashboards, funnels and experiment metrics all read one event log.

The script is 3.8 KB (under 2 KB gzipped). It is served from `https://cdn.dif.sh` and sends events straight to the collector at `https://ingest.difdb.com/v1/batch`. Your server is not in the path. Apps that already use `@dif.sh/sdk` can send the same page views [from the SDK](#sdk) instead.

## Set it up with an agent

Ask your coding agent to "set up dif analytics". The [dif-setup-analytics](https://dif.sh/docs/skills/#setup-analytics) skill turns site analytics on, adds the script tag for page views, plans and adds your events, and checks that they arrive. It takes the site key from `dif site setup`, and only asks you to copy it from **Settings → Site** if it can't. It puts the key in the script tag as `data-key`. Page views come from that tag; your SDK keeps its project key and `pageViews` stays off. It uses [`dif site setup`, `dif site check` and `dif events`](https://dif.sh/docs/cli/#site). Existing projects get the skill with [`dif init --agents-only`](https://dif.sh/docs/cli/#init). The rest of this page is the manual setup and the reference.

## Turn it on

Project owners and admins turn site analytics on in dif analytics under **Settings → Site**. Turning it on picks or makes the publishable key (`dif_pk_live_…`) that sends page views, and fills it into the snippet.

| setting | what it does |
| --- | --- |
| Allowed origins | The origins the script sends from, one per line, such as `https://example.com`. At least one is required. The collector refuses a page view from any other origin with a 403. |
| Rate limit | Events a minute for this key. 6,000 by default, at most 60,000. Over the limit is a 429. |
| Time zone | Sets the day for charts and for the daily visitor id. A change splits visitors once, on the day you make it. |
| Collapse ids in paths | On by default. `/orders/839201` is stored as `/orders/:id`, so pages group. |

A **test key** (`dif_pk_test_…`) lets you try the script on your machine. It takes only `localhost`, `127.0.0.1`, `[::1]`, `*.localhost` and `*.test` as origins. Test events are not billed, and a project's test data stops at 100,000 events a month.

> // analytics If Settings → Site cannot show the full key in the snippet, it asks for it: put in the key you copied when it was made.

## The tracking script

Put this tag in the `<head>` of each page. Settings → Site fills in your key.

```
<script defer src="https://cdn.dif.sh/s/v1.js"
        data-key="dif_pk_live_…"></script>
```

On load, and on each route change in a single-page app, it sends one page view with the page URL, the referrer, the screen size and `navigator.language`. The collector cleans the URL before it stores anything:

-   The fragment is dropped.
-   The query is dropped, except `utm_source`, `utm_medium`, `utm_campaign`, `utm_term`, `utm_content` and `ref`.
-   Click ids such as `gclid`, `fbclid` and `msclkid` keep their name only. Their values are never stored.
-   The referrer is stored as a domain, such as `news.ycombinator.com`. Its path and query are dropped.

Country, browser, OS and device type come from the request at the collector. IP addresses and the raw user agent are not stored.

### Versions

| file | cache | changes |
| --- | --- | --- |
| `/s/v1.js` | 1 hour | Moves to each new release of script contract v1: the `data-*` attributes and `window.dif` methods on this page. A breaking change ships as `v2.js`, and `v1.js` stays. |
| `/s/<version>.js` | 1 year, immutable | Never. `/s/0.9.0.js` is the same bytes for good. |

## Pin a version with SRI

To load a script that cannot change under you, pin a version and add its [Subresource Integrity](https://developer.mozilla.org/en-US/docs/Web/Security/Subresource_Integrity) hash. The browser refuses the file if its bytes do not match. Settings → Site shows this tag for the current release, under **Pinned version with SRI**:

```
<script defer src="https://cdn.dif.sh/s/0.9.0.js"
        integrity="sha384-6MrgwPHhCq0eFNXfC1QRFs2HjRSBOKmbgO0OMAcZQF+5VmEioFyomMnN0+X3yYas"
        crossorigin="anonymous"
        data-key="dif_pk_live_…"></script>
```

`crossorigin="anonymous"` is required: without it the browser cannot check the hash of a file from another origin, and does not run it. To check a hash yourself:

```
echo "sha384-$(curl -s https://cdn.dif.sh/s/0.9.0.js | openssl dgst -sha384 -binary | openssl base64 -A)"
```

A pinned tag gets no fixes until you change it. To upgrade, copy the new tag from Settings → Site, or swap the version and the hash together.

## Content Security Policy

If your site sends a `Content-Security-Policy` header, allow the CDN for the script and the collector for its requests:

```
script-src https://cdn.dif.sh;
connect-src https://ingest.difdb.com;
```

Add these to the sources your policy already lists. Both `fetch` and `navigator.sendBeacon` fall under `connect-src`. If you set `data-host`, list that origin instead of `ingest.difdb.com`. Product events that the SDK sends with a user id go to `events.url` (default `https://cloud.dif.sh`), so add that origin to `connect-src` too.

## data-\* attributes

All settings are attributes on the script tag. Only `data-key` is required.

| attribute | default | what it does |
| --- | --- | --- |
| `data-key` | required | The publishable key from Settings → Site. |
| `data-domains` | none | Comma-separated hostnames, such as `example.com,www.example.com`. On any other hostname the script sends nothing, so local and preview deploys are not billed. |
| `data-spa` | `history` | `history` sends a page view on `pushState`, `replaceState` and `popstate`. `hash` also listens to `hashchange` and turns `#/route` into the path. `off` sends the first page view only. |
| `data-auto` | `true` | `false` sends no page views on its own. Call `dif.page()` yourself. |
| `data-user-id` | none | The signed-in user's id, rendered by your server. Same as calling `dif.identify(id)` on load. |
| `data-consent` | none | `required` holds up to 50 events in memory until your consent tool calls `dif.consent(true)`. |
| `data-respect-dnt` | `false` | `true` sends nothing when Do Not Track or Global Privacy Control is on. |
| `data-host` | `https://ingest.difdb.com` | The collector URL, for staging and tests. Leave it unset in production. |

## window.dif

The script adds four methods to `window.dif`:

```
dif.track("signup", { plan: "pro" });   // a custom event with props
dif.page();                            // a page view, when data-auto="false"
dif.identify("u_42", { plan: "pro" }); // later events carry this user id
dif.identify(null);                    // sign out: back to the visitor id
dif.consent(true);                    // send the held events (data-consent="required")
```

-   `identify` keeps the id in memory for this page load only, because the script uses no storage. Call it on each load, or render `data-user-id`. Traits send an identify event. An id alone sends nothing.
-   `consent(false)` drops the held events.
-   The script does not replace a `window.dif` that is already on the page.

For clicks, you do not need JavaScript. A click on an element with `data-dif-event` sends that event, with its `data-dif-prop-*` attributes as props:

```
<button data-dif-event="signup" data-dif-prop-plan="pro">Start free</button>
```

Each event is one request. A network error or a 5xx is tried once more after 2 seconds. A 403 (an origin not in the key's list) stops the script sending for the rest of the page load.

## Privacy and consent

> // analytics No cookies. IP addresses are not stored. Visitor ids are pseudonymous, separate for each site, and rotate every day at your project's midnight. Whether you need consent depends on your jurisdiction and your use.

-   **Visitors.** Without a user id, the collector hashes the IP address and user agent with a salt for that day and that site, then discards the IP. Each salt is deleted after its day, so nobody, dif included, can link a visitor id to an IP afterwards. A visitor who comes back tomorrow counts as a new visitor, so ranges longer than a day show daily unique visitors.
-   **Device reads.** The script reads `navigator.language`, the screen size and `navigator.webdriver`. Under EDPB Guidelines 2/2023 such reads can fall under ePrivacy Art. 5(3), so "no cookies" does not by itself mean "no consent".
-   **Opt-out.** `data-consent="required"` holds events until your consent tool calls `dif.consent(true)`. `data-respect-dnt="true"` honours Do Not Track and Global Privacy Control.
-   **Processors.** Cloudflare sees visitors' IP addresses at its edge and passes them to dif-db, which uses them for the visitor hash and discards them. Data is stored in Cloudflare R2, in the United States (location hint Eastern North America). dif does not offer an EU-only store.
-   **Retention.** Raw requests are kept 30 days and bot traffic 28 days. Stored events are kept until retention limits ship. The backup holds deleted data for up to 3 days longer.

## Page views from the SDK

If your app already runs [`dif.init()`](https://dif.sh/docs/sdk/#init), it can send page views without the script tag. Turn them on with `pageViews: "auto"`:

```
import { dif } from "@dif.sh/sdk";
import { events } from "../dif/generated/events";

dif.init({
  events,
  userId: () => currentUser?.id ?? null,
  pageViews: "auto",   // on load and on each pushState route change
});

dif.page();                                  // or send one yourself
dif.identify(user.id, { plan: user.plan });
```

| option | default | notes |
| --- | --- | --- |
| `pageViews` | `"off"` | `"auto"` sends page views at init and on SPA navigation. It is off by default because every page view is billed. |
| `anonymous` | `false` | When `true`, a `dif.track()` with no user id goes to the collector with a visitor id. Otherwise it is dropped. |
| `anonymousUserId` | `false` | Set `true` when `userId()` returns an id your app minted for a visitor, such as a cookie value. Page views then count a visitor, not a signed-in user. |
| `ingestUrl` | `https://ingest.difdb.com` | Where page views go. |

The adapters take the same option: `config.pageViews` on React's `<DifProvider>`, and `initDif({ pageViews: "auto" })` in `@dif.sh/svelte`. With the script tag on the page, `pageViews: "auto"` stays off, so a page view is never counted twice. The key that sends page views needs at least one allowed origin.

If you also use site analytics, the recommended setup is the script tag for page views, with the site key as `data-key`, and SDK `pageViews` off. The site key only accepts its allowed origins, so it must not replace the SDK's project key in `dif/config.yaml`. Keep the project key for `dif.track()` and experiment exposures.

### From a server

[`DifServer`](https://dif.sh/docs/sdk/#server) sends a page view with `page()`. It needs a `userId` and an absolute http(s) URL:

```
await dif.page({ url: "https://example.com/pricing", userId: user.id });
```

Server page views get the cleaned URL, referrer and UTM fields, but no country, browser or device: those come from the visitor's own request.

## Host the script yourself

The npm package ships the same file as `@dif.sh/sdk/script.js`. To serve it from your own origin, copy it under a versioned name so you can cache it for good:

```
npm install @dif.sh/sdk@0.9.0
cp node_modules/@dif.sh/sdk/dist/script.js public/js/dif-0.9.0.js
```

```
<script defer src="/js/dif-0.9.0.js"
        data-key="dif_pk_live_…"
        data-domains="example.com,www.example.com"></script>
```

Only the file moves. Events still go to `https://ingest.difdb.com`, so keep it in `connect-src`; `script-src 'self'` covers the file. Never change a long-cached file in place: to upgrade, copy the new version under its new name and change the `src`.

> // analytics Do not proxy the collector through your own domain. Every visitor would then arrive from your server's IP address, so distinct visitors merge into one and the per-IP limit flags their events.

## Check the install

Load a page of your site, then select **Check live install** (or **Check test install**) under Settings → Site. The collector answers from memory, so you see a result in seconds:

```
3 events accepted in the last hour, last at 12:04:31, from https://example.com.
3 page views stored from the last hour.
```

From a terminal, [`dif site check --env live`](https://dif.sh/docs/cli/#site-check) runs the same check.

When nothing arrives, the check names what the collector refused in the last hour:

| refused for | what to do |
| --- | --- |
| an origin not in the key's list (403) | Add the exact origin, scheme included, to **Allowed origins**. A test key takes local origins only. |
| site analytics off (403) | Turn site analytics on for the project in Settings → Site. |
| the rate limit or spend cap (429) | Raise **Rate limit**, or the spend cap in billing settings. |
| a bad request (400) | Check that the page URL is http(s) and under 8,192 bytes. |

If nothing was refused either, the request never left the browser. Check that:

-   `data-domains`, if set, lists the hostname of the page;
-   your Content Security Policy allows [both hosts](#csp);
-   a pinned tag has `crossorigin="anonymous"` and the hash of that exact version;
-   `data-respect-dnt` or `data-consent` is not holding the events in your own browser.
