# Install Tracely on a website

Audience: an AI coding agent working in the website's repository. Follow the steps in order.
Analytics server: `https://tracely-opal-three.vercel.app`

## 0. What you need from the user

| Value | Where the user finds it | Required |
|---|---|---|
| Site ID (12 lowercase letters/digits) | Dashboard → site → Settings → Install | Yes |
| API key (starts with `tr_`) | Dashboard → site → Settings → API keys | Only for step 6 (verify) |

Ask for the site ID if you don't have it. Never invent one.

Rules:
- The site ID is public. It is safe in client code and in the repository.
- The API key is a secret. Use it only in your terminal for step 6. Never write it into source files, `.env` files that are committed, client code, or logs.
- The website's hostname must match the site's domain or one of its "Other hostnames" (Settings → General). Subdomains of a listed domain are accepted. If events are rejected with HTTP 403, ask the user to add the hostname.

## 1. Add the script

Add the snippet **once**, so it loads on every page. Replace `SITE_ID`.

### Plain HTML, or any server-rendered site (WordPress theme, Rails, Django, Laravel, Hugo, Jekyll, Astro)

Put this in the shared `<head>` template:

```html
<script defer data-site="SITE_ID" src="https://tracely-opal-three.vercel.app/a.js"></script>
```

### Next.js App Router

In `app/layout.tsx`:

```tsx
import Script from "next/script";

export default function RootLayout({ children }: { children: React.ReactNode }) {
  return (
    <html lang="en">
      <body>
        {children}
        <Script src="https://tracely-opal-three.vercel.app/a.js" data-site="SITE_ID" strategy="afterInteractive" />
      </body>
    </html>
  );
}
```

### Next.js Pages Router

In `pages/_app.tsx`, render the same `<Script>` next to `<Component {...pageProps} />`.

### React / Vue / Svelte single-page apps (Vite, CRA)

Put the HTML snippet in `index.html` inside `<head>`. Client-side navigation is tracked automatically (`history.pushState` and back/forward), so no router code is needed.

### Other frameworks

Any setup that puts the HTML snippet in the `<head>` of every page works. Do not bundle or self-host a copy of `a.js`; always load it from `https://tracely-opal-three.vercel.app/a.js` (or through the proxy in step 3) so it stays up to date.

### Script options (data attributes on the script tag)

| Attribute | Effect |
|---|---|
| `data-site="SITE_ID"` | Required. |
| `data-api="/path"` | Send events to this URL instead of `https://tracely-opal-three.vercel.app/api/event`. Used with the proxy in step 3. |
| `data-mode="cookieless"` | Never store an ID in the browser. |
| `data-consent` | Store no ID until `tracely.consent()` is called (see step 4). |
| `data-outbound="false"` | Don't send the `outbound` event for clicks on links to other sites. It is sent by default, without query strings. |
| `data-download="false"` | Don't send the `download` event (prop `url`) for clicks on file links such as .pdf or .zip. |
| `data-form="false"` | Don't send the `form` event (prop `form`: the form's id, name or action path; never field values) on form submits. |
| `data-hash` | Count hash routes (`#/path`) as separate pages, for hash-based routers. |
| `data-dnt="false"` | Ignore the browser's Do Not Track setting. Don't add this unless the user asks. |
| `data-allow-local` | Track on localhost. For local testing only; never ship it to production. |

When a page is left, the script also sends an `engage` event with the seconds the tab was visible and the scroll depth. It is not a custom event and doesn't count toward the monthly quota.

The script sends nothing on `localhost`, `127.0.0.1` or `file:` pages unless `data-allow-local` is set, and nothing from browsers with Do Not Track on.

## 2. Custom events and goals

Page views are automatic. For actions (signups, purchases, button clicks), send custom events.

Without JavaScript, add `data-track` to any clickable element. Extra `data-track-*` attributes become properties:

```html
<button data-track="signup" data-track-plan="pro">Sign up</button>
```

With JavaScript:

```js
window.track("signup", { plan: "pro" });
window.identify("user-123"); // optional: your own user ID, never an email or other personal data
```

If code may call `track` before the script loads, add this inline stub **before** the snippet. Calls made early are queued and sent once the script loads:

```html
<script>window.track=window.track||function(){(window.track.q=window.track.q||[]).push(arguments)}</script>
```

TypeScript declaration (e.g. `types/tracely.d.ts`):

```ts
type PulseProps = Record<string, string | number | boolean>;
declare global {
  interface Window {
    track?: (name: string, props?: PulseProps) => void;
    identify?: (id: string) => void;
    tracely?: { track: Window["track"]; identify: Window["identify"]; optOut(): void; optIn(): void; consent(): void };
  }
}
export {};
```

Call it as `window.track?.("signup")` so code still works when the script is blocked.

Limits (events outside them are dropped):
- Event name: 1–64 characters, only letters, digits, `_`, `:`, `.`, `-` and spaces. Use short, stable, lowercase names like `signup` or `checkout:start`.
- Properties: at most 20; keys up to 64 characters; values are strings (up to 256 characters), numbers or booleans.
- Never put personal data (emails, names, phone numbers, addresses) in event names or properties.

Goals are created by the user in the dashboard (Settings → Goals), either from an event name or a page path such as `/thank-you`. After adding events, tell the user which event names you added so they can create goals from them.

## 3. Ad-blocker proxy (optional)

Some ad blockers block third-party analytics. Serving the script and endpoint from the website's own domain avoids that.

Next.js (`next.config.ts` of the tracked website):

```ts
async rewrites() {
  return [
    { source: "/stats/a.js", destination: "https://tracely-opal-three.vercel.app/a.js" },
    { source: "/stats/event", destination: "https://tracely-opal-three.vercel.app/api/event" },
  ];
}
```

Then load the script with `src="/stats/a.js"` and `data-api="/stats/event"`.

Important limits of the proxy:
- Events then come from the proxy server, not the visitor's browser, so the analytics server may see the proxy's IP address and location instead of the visitor's.
- Use it only with **cookie mode**: don't set `data-mode="cookieless"`, and the site's tracking mode in Settings must be "cookie". In cookieless mode every visitor could be counted as one.
- Country and city reports may show the proxy's location.
- Tell the user about these limits before adding the proxy, and use the plain snippet unless they want it.

## 4. Consent and privacy

- IP addresses are kept only in a separate security log, used to investigate attacks, for the site's retention period (24 months by default). They never appear in reports. Cookie mode stores a random visitor ID (`_pt_vid` cookie and localStorage). Cookieless mode stores nothing in the browser.
- If the website shows a cookie banner, add `data-consent` to the script and call `window.tracely?.consent()` when the visitor accepts. Until then, events are sent without a visitor ID.
- Opt-out link, e.g. on the privacy page: `window.tracely?.optOut()` (and `optIn()` to undo). It is remembered in localStorage.
- Query parameters that look like secrets (`token`, `email`, `password`, `code`, `key` and similar) are removed from URLs before sending.
- Suggested privacy-notice text for the website (the user should review it; this is not legal advice):

> We use Tracely, a hosted analytics tool, to count visits. It keeps your IP address in a separate security log, used only to investigate attacks and deleted after the site's retention period (24 months by default). It does not track you across websites and does not share data with third parties. You can opt out on this page.

## 5. Test locally (optional)

1. Ask the user to add `localhost` to the site's "Other hostnames" (Settings → General).
2. Add `data-allow-local` only in development, for example `{...(process.env.NODE_ENV !== "production" && { "data-allow-local": "" })}` in JSX.
3. Make sure your browser doesn't send Do Not Track, then open a page.

## 6. Verify the install

After the change is deployed (or running locally with step 5), open a page of the website, then call:

```bash
curl -s -H "Authorization: Bearer $PT_API_KEY" https://tracely-opal-three.vercel.app/api/v1/sites/SITE_ID/status
```

Set `PT_API_KEY` in your shell session only. Example response:

```json
{
  "site": "SITE_ID",
  "domain": "example.com",
  "allowedHostnames": ["example.com"],
  "trackingMode": "cookie",
  "receiving": true,
  "firstEventAt": "2026-11-03T10:00:00.000Z",
  "lastEventAt": "2026-11-03T10:04:12.000Z",
  "eventsLast10Minutes": 3
}
```

- `receiving: true` means events arrived in the last 10 minutes. Done.
- `receiving: false`: check the browser's Network tab for the request to `/api/event` (or the proxy path). No request means the page is on localhost without `data-allow-local`, Do Not Track is on, or the visitor opted out. HTTP 403 means the hostname isn't listed in the site's settings. HTTP 400 means the event name or properties break the limits in step 2.
- HTTP 401 from the status call: the key is wrong or revoked. HTTP 404: the key belongs to a different site.

Without an API key, ask the user to open the dashboard's Real-time page and confirm they see the visit.

## Read stats (optional)

The same key reads aggregate stats (never visitor-level data):

```bash
curl -s -H "Authorization: Bearer $PT_API_KEY" "https://tracely-opal-three.vercel.app/api/v1/sites/SITE_ID/stats?period=7d&dim=page&limit=5&series=1"
```

| Param | Values |
|---|---|
| `period` | `today`, `yesterday`, `7d`, `30d` (default), `90d`, `12mo`, `mtd`, `ytd` |
| `from` + `to` | Custom range instead of `period`, `YYYY-MM-DD` in the site's timezone |
| `f` | Filter `key:op:value`, repeatable; `op` is `is`, `is_not` or `contains`, e.g. `f=country:is:US` |
| `dim` | Breakdown dimension, e.g. `page`, `source`, `channel`, `country`, `device`, `browser` |
| `limit` | Breakdown rows, 1–1000 (default 10) |
| `series=1` | Add visitors and pageviews per hour, day or week |

The response has `range`, `summary` (visitors, pageviews, sessions, bounceRate, avgDuration), `breakdown` when `dim` is set, and `timeseries` when `series=1`. Invalid params return HTTP 400 with an `error` message.

## 7. Report back to the user

Tell the user: which files you changed, which custom event names you added (so they can create goals), whether you used the proxy or consent mode, and the verify result.
