# Set up Little Friend in a product: guide for coding agents

You are a coding agent working in a product's repository. This guide takes you from nothing to a verified Little Friend install: the project, the script, events, goals, funnels, session replay, server events and AI agent visibility. It ends with a report for the person who asked.

Work through the steps in order. Each decision has a default: use it unless the repo or the person who asked says otherwise. When a step does not apply, skip it and say why in the report.

## Contents

0. [Conventions](#0-conventions)
1. [What Little Friend is, and the rules](#1-what-little-friend-is-and-the-rules)
2. [Sign in once per machine](#2-sign-in-once-per-machine)
3. [Read the repo and plan the journeys](#3-read-the-repo-and-plan-the-journeys)
4. [Workspace, project, mode and consent](#4-workspace-project-mode-and-consent)
5. [Install the script](#5-install-the-script)
6. [Content Security Policy](#6-content-security-policy)
7. [Custom events](#7-custom-events)
8. [Goals](#8-goals)
9. [Funnels](#9-funnels)
10. [Identify signed-in people](#10-identify-signed-in-people)
11. [Session replay](#11-session-replay)
12. [Server events](#12-server-events)
13. [Crawlers and AI agents: the door and a log drain](#13-crawlers-and-ai-agents-the-door-and-a-log-drain)
14. [Hybrid and native apps](#14-hybrid-and-native-apps)
15. [Verify](#15-verify)
16. [Launch checklist](#16-launch-checklist)
17. [Report back](#17-report-back)

## 0. Conventions

- **The CLI.** Run it as `npx --yes @littlefriend/cli <command>`. It needs Node 22 or later. This guide writes `littlefriend <command>` for short: type the full `npx` form, unless the CLI is installed globally.
- **Scope flags.** Commands that work on a project take `--project <id>`, and commands that work in a workspace take `--workspace <id or name>`. Agent shells often drop environment variables between calls, so pass the flags on every command. The examples below leave them out to stay short. The CLI also reads `LITTLEFRIEND_PROJECT` and `LITTLEFRIEND_WORKSPACE`.
- **Reading output.** Add `--json` when you need a value from the output, such as an id. Errors go to stderr with a non-zero exit code. With `--json`, they are also printed on stdout as `{ "error": { "code", "message" } }`.
- **Secrets.** Server keys (`lfs_`), edge keys (`lfe_`), read keys (`lfr_`) and drain secrets are shown once. Never put them in your messages, logs, commits or the report. Write keys to an env file with `--write-env` (step 12). The public site key (`lf_`) is fine to commit.
- **Credentials.** `~/.littlefriend/credentials.json` holds the sign-in. Never read it, print it or copy it into a repo.
- **Deletes.** Never delete or revoke a project, key, goal, funnel or drain you did not create in this session.
- **Repo rules win.** Follow the product repo's own rules for branches, commits, dependencies and deploys.
- **The code wins.** `littlefriend <command> --help` shows a command's flags. If this guide and the CLI disagree, trust the CLI and say so in the report.

## 1. What Little Friend is, and the rules

Little Friend is privacy-first web analytics (littlefriend.io). A small script, `lf.js`, counts page views, sources, clicks and named events without cookies. Server events count outcomes your backend confirms. Log drains and `@littlefriend/edge` show crawlers and AI agents, and the door decides which agents get in. Reports live at app.littlefriend.io.

The product must keep these rules. If a task would break one, stop and ask.

1. **No personal data** in event names, property keys or values, routes, ids, or goal and funnel names. Personal data means emails, names, usernames, phone numbers, addresses, account or card numbers, text a person typed, and anything else that points to one person.
2. **`identify` takes an opaque id** from the product's own database, such as `usr_8f3k2`. Never an email, a phone number, a name, or a hash of any of them.
3. **No typed text.** Never send form values, search queries or error messages as properties. Report a failed form with a short category, such as `validation` or `server`.
4. **Secret keys stay on the server.** Never put `lfs_`, `lfe_` or `lfr_` keys in client code, or in a variable a bundler exposes to the browser (`NEXT_PUBLIC_`, `VITE_`, `PUBLIC_`, `NUXT_PUBLIC_`, `EXPO_PUBLIC_`).
5. **No extra tracking.** Do not add cookies, storage or fingerprinting for analytics. Do not work around Global Privacy Control or a visitor's opt-out: the script already honors both.
6. **Unknown stays unknown.** Never combine an IP address with device traits to guess who someone is.

Little Friend also strips query strings and fragments (except allowlisted `utm_*` values), turns id-like and personal-looking path segments into `:id` or `:redacted`, drops property values that look like an email or a long number, and never reads form values or page text. Treat that as a safety net. Rule 1 still applies.

## 2. Sign in once per machine

```sh
littlefriend whoami
```

If it names an account, go to step 3. Otherwise:

```sh
littlefriend login
```

It opens a browser, prints the URL too, and waits up to 5 minutes. The person who owns the Little Friend account approves the login in the browser. Tell them a sign-in page is waiting, then wait. If nobody approves in time, stop and ask. Do not retry in a loop.

- The CLI acts with that person's role in each workspace. Creating projects, keys, goals, funnels and settings needs the editor or owner role.
- In CI, set `LITTLEFRIEND_TOKEN` to an access token instead of signing in.
- `littlefriend logout` revokes the sign-in and deletes the local credentials.

## 3. Read the repo and plan the journeys

Collect these facts before you create anything. They drive every later decision, and most of them go into the report.

| Fact | Where to look |
|---|---|
| Product name and production domain | README, deploy config (`vercel.json`, `fly.toml`, `netlify.toml`, `wrangler.toml`), site URL env vars, canonical tags, sitemap config |
| Every host the product serves pages from | `www.`, `app.`, docs subdomains, redirect config |
| Web framework | `package.json` and config files. The table in step 5 maps them |
| Where the HTML `<head>` is rendered | Root layout, `index.html`, document template |
| Sign-in | Auth libraries (Auth.js, Clerk, Supabase, Lucia, Better Auth, Passport), `/login` and `/signup` routes, a current-user hook |
| Money | Checkout, pricing, plans, trials, payment webhooks |
| Onboarding and activation | First-run screens, "create your first ..." flows, invites |
| Pages with private data | Account, settings, billing, admin, messages, documents, and any health, legal or financial records |
| Consent tool | A cookie banner or consent manager (OneTrust, Cookiebot, Osano, Klaro, a custom one) |
| Content Security Policy | Search code, config and headers files for `Content-Security-Policy` |
| Server runtime and host | API routes, server framework (Express, Celsian, Hono, Next.js route handlers), Workers, Fly or Vercel config |
| Env files | `.env`, `.env.local`, `.env.example`, and what `.gitignore` ignores |
| App shells | `capacitor.config.*`, `ionic.config.json`, Cordova `config.xml`, `src-tauri/`, an Electron main process, React Native or Expo |
| Existing analytics | Google Analytics, Plausible, PostHog, Segment or Vercel Analytics calls |

Existing analytics: leave them in place unless asked to remove them. Their event lists are good candidates for your named events and goals.

### Plan the journeys

Before you add a single event, decide what this product exists to get people to do, and which paths lead there. Steps 7 to 9 build exactly this plan, so every event, goal and funnel has a reason.

1. **Say the product's job in one sentence:** who arrives, and what a good visit ends with. Read the home page, the pricing page, the main call to action, and the signup or checkout code.
2. **List the outcomes, most valuable first.** Usually 1 to 3: money (purchase, upgrade, trial), an account (signup), a lead (contact, demo booked), or activation, the first time someone gets value (created a project, sent an invite, published a page).
3. **Write one journey per top outcome, at most 3.** A journey is the path a person takes from arriving to the outcome, in 3 to 5 steps they would recognize: where it really starts (a landing page, pricing, a docs page), the moment they commit (opened signup, started checkout), and the outcome itself.
4. **Decide how each step is seen.** A page is a route step (`route:/pricing`). An action inside a page, or something the server confirms, is a named event you add in step 7 (`event:signup.start`). The outcome becomes a goal in step 8, and the journey becomes a saved funnel in step 9.
5. **Check the routes.** Read the router for each route step. Ids and personal segments are stored as `:id` or `:redacted`, so `/projects/42/settings` is stored as `/projects/:id/settings`.

Start from the row that fits, then change it to match what the code really does:

| Product | Outcome | Journey |
|---|---|---|
| App or SaaS | Signup, then activation | `route:/` → `route:/pricing` → `event:signup.start` → `goal:<Signup id>` → `goal:<Activated id>` |
| Store | Purchase | `route:/products/:id` → `event:cart.add` → `event:checkout.start` → `goal:<Purchase id>` |
| Services or lead generation | Contact or booking | `route:/` → `route:/services` → `event:contact.open` → `goal:<Contact sent id>` |
| Docs or open source | Adoption | `route:/docs` → `route:/docs/getting-started` → `goal:<Install copied id>`, a goal on `install.copy` |
| Marketing site for an app on another host | A visitor heads to sign up | `route:/` → `route:/pricing` → `goal:<Signup click id>`, a goal on `cta.signup` |

**A journey ends at the edge of its host.** A journey-mode session lives in one tab's session storage, which browsers keep apart for each host. A visit that moves from `example.com` to `app.example.com` becomes two sessions. Give each host its own funnel: end the marketing site's funnel on a goal for a named event fired when the signup link is clicked (`lf('track', 'cta.signup')`), and start the app's funnel at its signup page.

Keep the plan small and useful:

- Pick what someone running the product would ask about on a Monday: "Of the people who saw pricing, how many started a trial?" If nobody would act on a number, do not build it.
- At most 3 funnels and 5 goals per project. Every funnel ends on a goal.
- A step the code cannot see yet (no route, no event) needs an event in step 7. Note it in the plan.
- A server-confirmed outcome joins the journey only when the server event carries the browser's correlation id (step 12). Plan that, or end the funnel on the browser event just before it.
- Aggregate mode has no sessions, so it has no funnels. Plan goals only, and say so in the report.

Write the plan into the report (step 17) as a table before you build anything:

| Journey | Outcome goal | Steps, and how each is seen |
|---|---|---|
| Signup | Signup (server) | `/pricing` route, `signup.start` event on the button, `signup.completed` server event with the browser's correlation id |

## 4. Workspace, project, mode and consent

### Workspace

```sh
littlefriend workspaces list
```

| Situation | Workspace |
|---|---|
| The person who asked named one | That one |
| The list shows one workspace | That one |
| Several, and nobody named one | Stop and ask. Never guess |
| The one you need is missing | Stop and ask. The CLI does not create workspaces |

### Reuse before you create

```sh
littlefriend projects list --workspace <workspace>
```

If a project already has the product's domain, reuse it: note its id and site key, and run `littlefriend projects get` to see its mode and allowed origins. Never create a second project for the same domain.

One product is one project, even when its marketing pages and app live on different hosts of the same domain. List every host in allowed origins.

### Mode

| The product has | Mode |
|---|---|
| Sign-in, signup, onboarding, checkout, or any flow of several steps | `journey` |
| Only marketing or content pages, and no sign-in | `aggregate` |
| It is a site you build for a client | `aggregate`, unless the client asked for journeys |

- Aggregate mode keeps counts only, with no session or visitor key anywhere. It still gives views, sources, pages, devices, countries, events and goals.
- Journey mode adds sessions, timelines, funnels, paths, entry and exit pages, session replay and identify. Its session id lives in the tab's session storage and ends after 30 idle minutes (24 hours at most).

### Consent

| Situation | Do this |
|---|---|
| The product already runs a consent tool | Use `--consent required` in step 5. Call `lf('consent', 'journey')` when the tool grants analytics consent, and `lf('consent', 'aggregate')` when it is withdrawn |
| No consent tool, journey mode | Ask the person who asked whether to ship without a banner. Do not add a consent tool yourself |
| Aggregate mode | Nothing to wire |

Until consent arrives, the script counts in aggregate mode. A browser that sends Global Privacy Control always stays in aggregate mode.

If the product has a privacy page, add this text for journey mode:

> We use Little Friend for privacy-friendly analytics. It sets no cookies and does not store IP addresses. To connect the pages you view in one visit, it keeps a random id in your browser tab's session storage. The visit ends after 30 minutes of inactivity, and the id is gone when you close the tab. If your browser sends Global Privacy Control, your visit is only counted, never connected.

In aggregate mode, use only the first two sentences. With session replay on (step 11), add:

> Some visits are recorded as a masked copy of the pages you view. Text stays hidden unless we chose to show it, form entries are never recorded, and recordings are deleted within 7 days.

If the project shows all text in recordings (`body` in its shown text), use this instead:

> Some visits are recorded as a copy of the pages you view. We chose to show the text on our pages in these recordings. What you type or choose in forms is never recorded, email addresses and phone and card numbers stay masked, and recordings are deleted within 7 days.

If there is no privacy page, say so in the report.

### Create the project

```sh
littlefriend projects create --name "Acme" --domain acme.com --mode journey \
  --origin https://acme.com --origin https://www.acme.com --origin http://localhost:3000 \
  --timezone America/New_York
```

It prints the project id and the public site key. Keep both for the rest of the guide and the report.

- `--domain`: the production host. Little Friend stores it lowercase, without a scheme, path or `www.`.
- `--origin`, once per origin: every production host that serves pages, plus the local dev server's origin so you can verify before deploy (step 15). Add app origins from step 14. Preview deploys and any origin not listed get `403` and count nowhere, which is intended. An empty list accepts every origin.
- `--timezone`: the time zone the business reports in. Without it, reports use UTC.
- To add an origin later, run `littlefriend projects update --add-origin https://app.acme.com`. `--remove-origin` takes one out, and `--origin` replaces the whole list.
- A native iOS or macOS app sends no origin. List its bundle id with `littlefriend apps add com.acme.shop`.

## 5. Install the script

Print the exact code for the stack:

```sh
littlefriend snippet --framework next --mode journey
```

It prints what to add, with the site key filled in, and the CSP lines the site needs. Add `--consent required` when step 4 said so. Add `--replay` only in step 11.

| The repo has | `--framework` | Where the code goes |
|---|---|---|
| `next` | `next` | The root layout: `app/layout.tsx` (App Router) or `pages/_document.tsx` (Pages Router) |
| `nuxt` | `nuxt` | `nuxt.config.ts` |
| `@sveltejs/kit` | `sveltekit` | `src/app.html` |
| `astro` | `astro` | The layout every page shares, often `src/layouts/Layout.astro` |
| `@remix-run/*`, or React Router with `app/root.tsx` | `remix` | `app/root.tsx` |
| `react` with Vite or another bundler, no framework | `react` | `index.html` |
| `vue` with Vite | `vue` | `index.html` |
| `@angular/core` | `angular` | `src/index.html` |
| A WordPress theme or plugin | `wordpress` | Where the snippet says |
| `what-framework`, a Shopify theme, plain HTML, anything else | `html` | The `<head>` every page shares: `index.html`, the document template, `layout/theme.liquid` |
| A bundled app where you want typed functions | `npm` | The client entry, once at startup |

The snippet is the source of truth for the code. The last column is where to look first.

A static HTML site with no build step loads the script straight from the Little Friend CDN. Put this tag in the `<head>` of every page, with the project's site key in place of `lf_YOUR_SITE_KEY`:

```html
<script defer src="https://cdn.littlefriend.io/lf.js" data-site="lf_YOUR_SITE_KEY"></script>
```

`littlefriend snippet --framework html` prints the same tag with the key filled in. A page the tag is missing from is never counted, so add it to every HTML file, or to the shared template or include when the site has one.

Rules:

- **One tracker per page.** Use the tag or the npm package (`@littlefriend/tracker`), never both. Load it on every page, once.
- **Single-page apps need nothing extra.** History API navigations count as page views. If the router does not use the History API, call `lf('page')` after each navigation. Call it for navigations only, never for a screen the load or a History API navigation already recorded.
- **Outside production, mark traffic as test.** Add `data-test` to the tag, or pass `test: true` to `init`, when the build is not production (for example `process.env.NODE_ENV !== 'production'` or `import.meta.env.DEV`). Test traffic shows in the live install check and never in reports.
- **Name dynamic routes.** Id-like segments already become `:id`. For readable groups, such as `/blog/:slug`, add `data-routes='["/blog/:slug"]'` to the tag, pass `routes` to `init`, or call `lf('route', '/blog/:slug')`. Goals and funnel steps match these routes exactly.
- **Calls before the script loads.** If the product's own code calls `lf(...)`, add this stub above the tag, so `lf` exists before the deferred script runs. Calls wait in a queue until it loads.

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

- **Secret scanners.** The site key (`lf_`) is public, but gitleaks and similar scanners may flag it as an API key. Add an allowlist entry for that exact key rather than hiding it. A constant named `LITTLE_FRIEND_SITE` rather than `..._KEY` trips fewer rules.
- **Monorepo build caches.** If the tag only renders in production (for example on `VERCEL_ENV`), declare that variable for the build task in `turbo.json` or the cache's equivalent. Otherwise a preview build and a production build can share one cached output.

With the tag in a TypeScript app, declare the global once, for example in `src/lf.d.ts`:

```ts
declare global {
  function lf(command: string, ...args: unknown[]): void;
}
export {};
```

## 6. Content Security Policy

Skip this step if the product sets no CSP. Otherwise add:

```text
script-src https://cdn.littlefriend.io
connect-src https://in.littlefriend.io
```

- With the npm package, the tracker is part of your bundle, so only `connect-src` is needed.
- The replay script comes from the same host as `lf.js` and sends to the same collector. It needs no other entries.
- A policy with a nonce or `'strict-dynamic'` ignores host entries for scripts. Give the tag the page's nonce, or use the npm package.
- Update every copy of the policy: `Content-Security-Policy-Report-Only`, `<meta http-equiv>` tags, and the test files that assert headers.
- Common places: `next.config.*` `headers()`, `middleware.ts` or `proxy.ts`, `vercel.json`, `netlify.toml`, `_headers`, Helmet options, server header code.

## 7. Custom events

The script sends these on its own: page views, outbound links, downloads, engaged time and, with `data-scroll`, scroll depth. The `$` prefix is reserved for them.

Add the named events your journey plan (step 3) needs, and the few the product's key feature needs. Three ways to add more:

```html
<!-- A named click: sends $click with { "id": "pricing.start_trial", "plan": "pro" } -->
<button data-lf="pricing.start_trial" data-lf-plan="pro">Start free trial</button>

<!-- A tracked form: sends $form_start and $form_submit with { "id": "signup" } -->
<form data-lf-form="signup">...</form>
```

```ts
// A named event, after the thing really happened
lf('track', 'signup.completed', { plan: 'pro' });

// A failed form: a short category, never the message
lf('formError', 'signup', 'validation');
```

With npm, import the same names: `track`, `formError`, `page`, `route`, `consent`, `optout`, `optin`.

**Goals and funnel steps start from an event name or a route.** A goal on an event can also require up to 3 property values, such as `plan` set to `pro` (step 8). A funnel's `event:` step matches the name only, and a `goal:<id>` step uses the goal's conditions. Every `data-lf` click arrives as `$click`, and every tracked form as `$form_submit`. For anything that becomes a goal or a funnel step, fire its own named event with `track`.

### Names

- `area.action`, lowercase: dots between parts, underscores inside a part. `signup.start`, `signup.completed`, `onboarding.project_created`, `checkout.start`, `order.completed`, `plan.upgraded`, `invite.sent`.
- Past tense for outcomes (`completed`, `created`, `sent`). `start` or `open` for intent.
- The pattern is `^[a-z][a-z0-9_.:-]{0,63}$`. `data-lf` ids follow the same convention.
- Fire outcome events after the server call succeeds, never on the button press. Fire intent events on the press.
- Aim for 5 to 15 named events: the steps of signup, onboarding, activation and checkout, and the product's key feature. Do not name every click.

| Good | Bad | Why the bad one fails |
|---|---|---|
| `signup.completed` | `Signup Completed` | Uppercase and spaces are refused |
| `checkout.start` | `click_button_3` | Says nothing about the product |
| `invite.sent` with `{ role: 'editor' }` | `invite.sent.jane@acme.com` | Personal data in the name |
| `order.completed` with `{ plan: 'pro' }` | `order_8812_completed` | An id in the name makes a new event per order |
| `search.submit` with `{ results: 12 }` | `search.submit` with `{ query: 'knee pain' }` | Typed text is personal data |
| `project.created` | `$project_created` | `$` is reserved |

### Properties

- Up to 8 per event. Keys are lowercase snake case, up to 32 characters. Values are strings, numbers or booleans. Strings are cut to 64 characters.
- Use small fixed sets (`plan`, `step`, `method`, `role`, `source`) and counts.
- A value that looks like an email or a long run of digits is dropped, even when sent on purpose.

### Page types (optional)

Flows group pages by type. Little Friend suggests types from your paths, and owners and editors can change the rules in Settings, Page types. When a page's type can't be told from its path, set it on the page:

```html
<meta name="lf:type" content="comparison">
```

The value is a lowercase key: letters, digits, `-` or `_`, starting with a letter, at most 32 characters. A tag beats the URL rules for that page. The tracker reads this one tag and nothing else.

On a client-side navigation the page view is recorded when the URL changes. Its type is read after the next animation frame, or at once when the tab is hidden, so head managers that write the tag on render are read correctly. On page load the tag is read when the script runs, so put it in the HTML the server sends.

## 8. Goals

A goal is a conversion. Create 2 to 5, one for each outcome in your journey plan (step 3), most valuable first.

| Product | Goals to start with |
|---|---|
| App or SaaS with sign-in | Signup (server), activation: the first key action, upgrade or trial started (server) |
| Store | Purchase (server, with value), checkout started |
| Lead generation | Contact form sent, demo booked, the thank-you page |
| Content or docs | Newsletter signup, a named event on the link to the product's signup |

- Prefer server-confirmed goals for money and accounts: `--source server --server-confirmed`. `--source server` counts only events your server sends with a secret key, and `--server-confirmed` also marks the goal that way in reports, so a reader knows a browser cannot fake it. Use browser goals for intent, or when there is no backend.
- A route goal matches the stored route exactly. Check the routes with `littlefriend report pages` first.
- An event goal can also require up to 3 property values: `--prop plan=pro`, once per property. The event counts only when each of those properties equals its value, compared as text. Use it to split one event into outcomes, such as a Pro signup, instead of adding a second event.
- Create goals before launch. A goal counts from the moment it is saved.
- Name goals in plain words: "Signup", "Purchase", "Demo booked".

```sh
littlefriend goals create --name "Signup" --event signup.completed --source server --server-confirmed
littlefriend goals create --name "Purchase" --event order.completed --source server --server-confirmed
littlefriend goals create --name "Pro signup" --event signup.completed --source server --server-confirmed --prop plan=pro
littlefriend goals create --name "Activated" --event project.created
littlefriend goals create --name "Contact sent" --route /contact/thanks
littlefriend goals list
```

Keep the goal ids (`goal_...`) for funnels and the report.

## 9. Funnels

Journey mode only. Save one funnel for each journey in your plan (step 3), 1 to 3 in all, named after the journey.

A funnel has 1 to 8 steps in order. Each step is `route:/path`, `event:<name>` or `goal:<goalId>`. A session reaches a step when it has done the steps before it, in that order.

| Flow | Steps |
|---|---|
| Signup | `route:/pricing` → `event:signup.start` → `goal:<Signup id>` |
| Activation | `goal:<Signup id>` → `event:onboarding.profile_completed` → `goal:<Activated id>` |
| Checkout | `route:/pricing` → `event:checkout.start` → `goal:<Purchase id>` |

- Keep 3 to 5 steps. Start broad and end on a goal.
- A server event joins a session only when it carries that session's correlation id or session id (step 12). Without one, a server-only goal as the last step is never reached. Pass a correlation id, or end on a browser event.

```sh
littlefriend funnels create --name "Signup" \
  --step route:/pricing --step event:signup.start --step goal:goal_XXXXXXXX
littlefriend funnels list
littlefriend funnels report fnl_XXXXXXXX --from 2026-10-01 --to 2026-10-07
```

Dates are `YYYY-MM-DD` in the project's time zone.

## 10. Identify signed-in people

Journey mode only. `lf('identify', ...)` is handled by the replay script, so it needs step 11. Without replay, skip this step.

```ts
// Wherever the app knows the signed-in user: after sign-in and on each page load
lf('identify', user.id); // your own opaque id, such as usr_8f3k2

// On sign-out
lf('identify', null);
```

With npm: `import { identify } from '@littlefriend/replay'`, then `identify(user.id)` and `identify(null)`.

- The ref is 1 to 64 letters, digits, `_`, `.`, `:` and `-`. UUIDs and prefixed ids work.
- Prefix numeric ids, such as `usr_4821937`. A ref of seven or more bare digits is refused.
- Never an email, a phone number, a name, a username, or a hash of any of them. Emails are refused.
- The ref lasts for the journey session in that tab. Call it on each page load while signed in, so the next session carries it too.
- Before consent it waits in memory, and a Global Privacy Control visitor sends nothing.
- With a ref, a workspace owner can find one person's sessions and erase their sessions, events and recordings (Settings, Replay, Forget a person).

## 11. Session replay

Replay records a journey session as a masked copy of the page: layout, scrolling, clicks and page changes. Every word is masked until you choose to show it. Form values, checked boxes, chosen options, images, video, audio, canvas and iframes are never recorded.

### Decide

| Situation | Replay |
|---|---|
| Journey mode, and the person who asked wants replay | On |
| Journey mode, and nobody said | Ask first. Each workspace records up to 10 sessions a month free. More needs a card on file (Settings, Billing). Past the allowance, recording stops until a card is added or the month ends. Your own test recordings count too |
| Pages show health, legal or financial records, or other people's private messages | Off, unless the owner asks |
| Aggregate mode | Not available |

### Defaults

| Setting | Default |
|---|---|
| Sample rate | `100`, unless the site expects more than about 1,000 recorded sessions a day. Then sample down, for example to `25`. Each project stores up to 1 GiB of recordings a day, about 2,000 typical recordings, and refuses more until midnight UTC |
| Text shown | Nav, header, footer, headings, buttons, labels, table headers, legends, tabs, menu items |
| Hidden elements | Support chat, third-party widgets, and any region that lists other people's data |
| Pages never recorded | `/account`, `/settings`, `/billing`, `/checkout`, `/admin`, plus every private-data route from step 3 |
| Minimum active time | 2 seconds, the built-in default. A shorter recording is dropped unless it has at least 3 clicks |

### Turn it on

```sh
littlefriend replay enable --rate 100
littlefriend replay set \
  --unmask nav --unmask header --unmask footer \
  --unmask h1 --unmask h2 --unmask h3 --unmask h4 \
  --unmask button --unmask label --unmask th --unmask legend \
  --unmask "[role=button]" --unmask "[role=tab]" --unmask "[role=menuitem]" \
  --block .support-chat \
  --exclude /account --exclude /settings --exclude /billing --exclude /checkout --exclude /admin
littlefriend snippet --framework next --mode journey --replay
```

- `replay set` replaces each list. Pass every item every time.
- Add the replay code the snippet prints after `lf.js`, with the same site key. With npm, call `startReplay({ site })` from `@littlefriend/replay` after `init`.
- An excluded route covers itself and every path below it: `/account` covers `/account/billing`. `*` stands for one segment: `/projects/*/settings` covers `/projects/acme/settings` and everything below it. Up to 50 routes, each at most 100 characters, with no query or fragment.
- Selectors: tag names, classes, ids and attribute selectors with plain values, joined by spaces, `>` or commas. Pseudo-classes, sibling selectors and `*` are refused. Up to 50 per list, 200 characters each.

### Mark the HTML

Emails, phone numbers and card numbers stay masked even in shown text. Names do not. Search the shown regions (header, nav, account menu, buttons) for places that print the signed-in person's name, company, initials or avatar label, and mask them again:

```html
<header>
  <nav>...</nav>
  <button class="account-menu" data-lf-mask>{user.name}</button>
</header>

<aside class="support-chat" data-lf-block>...</aside>
```

- `data-lf-mask` masks text again inside a shown region.
- `data-lf-block` leaves an element out, drawn as an empty box. Use it for regions whose shape alone says too much, and on sensitive parts of routes that draw their page late after navigation.
- `data-lf-unmask` shows the text of one element, for plain product copy such as plan names and prices. It needs at least one selector in the project's shown text: the preset above, or `--unmask "[data-lf-unmask]"` alone. With that list empty, every word is masked, marks included.

`littlefriend replay get` shows the settings, and says the replay script is installed once the first recording arrives.

## 12. Server events

Send outcomes the backend confirms: account created, payment succeeded, plan changed. Default: yes for every product with sign-in or payments.

### The key

```sh
git check-ignore -q .env.local && echo ignored
littlefriend keys create --kind server --label "acme server" --write-env .env.local --env-name LF_SERVER_KEY
```

- Use the env file the framework loads (`.env.local` for Next.js, often `.env` elsewhere). It must be ignored by git. If `git check-ignore` prints nothing, add the file to `.gitignore` first.
- With `--write-env`, the CLI appends `LF_SERVER_KEY=...` only if the name is not set yet, and never prints the secret.
- Add `LF_SERVER_KEY=` with no value to `.env.example`, if the repo has one.
- Production needs the same variable in the host's secret store. Copy it from the env file without printing it, if you have the host's CLI and the repo's rules allow it. Otherwise list it under "Needs a person". Check each host CLI's `--help` before you run these:

```sh
# Vercel
grep '^LF_SERVER_KEY=' .env.local | cut -d= -f2- | tr -d '\n' | vercel env add LF_SERVER_KEY production

# Fly
grep '^LF_SERVER_KEY=' .env | fly secrets import -a <app>

# Cloudflare Workers (the edge key from step 13)
grep '^LF_EDGE_KEY=' .env | cut -d= -f2- | tr -d '\n' | wrangler secret put LF_EDGE_KEY
```

### Send from Node.js

Install `@littlefriend/node` with the repo's package manager (Node 18.17 or later). Create one client at module scope:

```ts
// lib/little-friend.ts
import { LittleFriend } from '@littlefriend/node';

const key = process.env.LF_SERVER_KEY;
export const lf = key ? new LittleFriend({ key }) : null;
```

Then send each outcome where the backend confirms it: after the account row is written, in the payment webhook, after the plan change commits.

```ts
import { createHash } from 'node:crypto';
import { lf } from './lib/little-friend';

lf?.track({
  // 8 to 32 letters, digits, _ or -. The same id on a retry counts once.
  id: createHash('sha256').update(order.id).digest('base64url').slice(0, 32),
  name: 'order.completed',
  props: { plan: order.plan },
  value: { amount: order.totalCents, currency: 'USD' }, // minor units
  correlationId: order.checkoutRef, // optional, see below
});

await lf?.flush(); // in a serverless function, before it returns
```

- `track` never throws. A bad event goes to `onError`, which logs a warning by default.
- In serverless functions (Vercel, Next.js route handlers and server actions), `await lf.flush()` before returning. In a long-running server, `await lf.shutdown()` when the process exits.
- Derive `id` from the record, as above. Raw UUIDs (36 characters) and short numeric ids fail the id rule.
- Other languages: POST `{ "v": 1, "events": [ ... ] }` to `https://in.littlefriend.io/v1/server` with `Authorization: Bearer $LF_SERVER_KEY`. Retry `429` and `503` after `Retry-After`. Never retry a `400`. Details: https://littlefriend.io/docs/goals#http

### Join server outcomes to journeys

In journey mode, a server event joins the visitor's session when it carries the same correlation id as a browser event:

```ts
// Browser, when checkout starts: a random id for this attempt, sent to the server with the form
const checkoutRef = crypto.randomUUID();
lf('track', 'checkout.start', { plan: 'pro' }, checkoutRef);
```

The server stores `checkoutRef` with the order and passes it as `correlationId`. A correlation id is 16 to 64 letters, digits, `_` or `-`, and never only digits and dashes. Aggregate mode drops it.

## 13. Crawlers and AI agents: the door and a log drain

`lf.js` sees only browsers. Crawlers and AI agents rarely run JavaScript, so Little Friend needs the requests themselves.

| Where the product runs | See agents with | Door |
|---|---|---|
| Vercel, any framework, static too | A Vercel log drain | Next.js: `nextProxy` in `proxy.ts` (Next.js 16) or `middleware.ts` (Next.js 15). Other frameworks: skip it and say so |
| Next.js on another host | `wrapFetch(edge, handler, { waitUntil })` in route handlers, or `nodeMiddleware(edge)` in a custom Node server | `nextProxy`, as on Vercel |
| Cloudflare Workers | `withLittleFriend` from `@littlefriend/edge` | Add `door: createDoor` |
| Node with Express, Connect or `node:http` | `nodeMiddleware(edge)` | `nodeDoor(createDoor(lf), createEdge(lf))` in its place |
| Bun, Deno, Hono or another fetch handler | `wrapFetch(edge, handler)` | `wrapFetch(edge, handler, { door })` |
| Celsian | `observeCelsian(app, edge)` | None built in. Skip it and say so |
| Static hosting without functions, not on Vercel | Only with a Worker in front | Only with a Worker in front |

A request both a drain and the edge package report is counted once.

Requests to the project's ignored routes are counted and not kept. Every project starts with `/api`, because an app calling its own API (session checks, polling, presence) is not a crawler or an agent. Add the product's other API paths, such as `/trpc` or `/graphql`:

```sh
littlefriend projects update --add-ignored-route /trpc
```

Remove `/api` only when the owner wants to watch who calls the API, and say so in the report.

### A Vercel log drain

```sh
littlefriend drains list
littlefriend drains create --provider vercel
```

- Check `drains list` first. Reuse an active drain.
- `drains create` prints the endpoint, the header and the signing secret, once. Create it only when you can paste them into Vercel in the same sitting: in the team's settings, add a log drain for this project only, all sources, production, and 100% sampling. Drains need a Vercel Pro or Enterprise team.
- If you cannot reach Vercel's settings, do not create the drain. List it under "Needs a person": they can do both halves on the dashboard's Agents page, with Add a Vercel log drain.
- A lost secret: `littlefriend drains rotate <id>` issues a new pair and keeps the old one working for 24 hours.
- Within minutes of traffic, the Coverage card on the Agents page shows the drain as Live.

### `@littlefriend/edge` and the door

Use this when the product has code that runs on every request. Install `@littlefriend/edge` 0.3.0 or later. The door came in 0.2.0, and 0.3.0 stops sending requests to ignored routes. If the repo already depends on `^0.2.0`, change it to `^0.3.0`: that range never picks up 0.3.0 on its own.

1. Create an edge key into the env file, as in step 12:

```sh
littlefriend keys create --kind edge --label "acme edge" --write-env .env.local --env-name LF_EDGE_KEY
```

2. Install `@littlefriend/edge` and wire it for the runtime in the table above. The exact code for each runtime is on https://littlefriend.io/docs/agents (sections Any host and The door). For Next.js 16:

```ts
// proxy.ts
import { createDoor, createEdge, nextProxy } from '@littlefriend/edge';
import { NextResponse } from 'next/server';

const lf = { key: process.env.LF_EDGE_KEY!, ipHeader: 'x-forwarded-for' };
export const proxy = nextProxy(createDoor(lf), NextResponse, createEdge(lf));
export const config = { matcher: ['/((?!_next/static|_next/image|favicon.ico).*)'] };
```

3. Set `ipHeader` to the header the host sets to the client address: `x-forwarded-for` on Vercel, `cf-connecting-ip` on Cloudflare, `fly-client-ip` on Fly. Without it, no address is sent and operator address checks cannot run.

4. Pick a preset and keep dry run:

```sh
littlefriend door set --preset verified_only --mode dry_run
littlefriend door simulate --ua "Mozilla/5.0 AppleWebKit/537.36 (KHTML, like Gecko; compatible; GPTBot/1.2; +https://openai.com/gptbot)" --path /blog
```

| Product | Preset |
|---|---|
| A store with `/checkout`, `/cart` or `/account` | `commerce` |
| An app or API with sign-in | `verified_only` |
| Content, docs or marketing | `no_training` |
| Unsure | `open` |

- Dry run decides every request and records what it would have done. It never changes a response.
- **Never switch the door to live.** The owner does that after reading 7 days of the door's report on the Agents page.
- A browser always gets in, whatever the rules say.
- `commerce` matches `/checkout`, `/cart` and `/account`. If the store uses other paths, say so in the report.

## 14. Hybrid and native apps

**Hybrid apps** (Capacitor, Ionic, Cordova, Tauri, Electron, React Native WebView, or the app's own WKWebView or Android WebView) show web pages. Install the script in the app's web code as in step 5, then add the origin the web view sends to the project's allowed origins:

```sh
littlefriend projects update --add-origin capacitor://localhost --add-origin https://localhost
```

| App shell | Origin to add |
|---|---|
| Capacitor on iOS | `capacitor://localhost` |
| Capacitor on Android | `https://localhost` |
| Ionic with its Cordova web view | `ionic://localhost` on iOS, `http://localhost` on Android |
| Cordova | `app://localhost` on iOS (scheme preference set to `app`), `https://localhost` on Android |
| Tauri | `tauri://localhost` on macOS, iOS and Linux. `http://tauri.localhost` on Windows and Android, or `https://tauri.localhost` with `useHttpsScheme` |
| Electron | The scheme and host the app serves from, such as `app://myapp` |
| React Native WebView | The origin of the site it loads |
| WKWebView with a custom scheme handler | The scheme and host you register, such as `app://localhost` |
| WKWebView loading a file URL | No origin, see below |
| Android WebView with WebViewAssetLoader | `https://appassets.androidplatform.net`, or `https://localhost` with `setDomain("localhost")` |
| Android WebView loading `file:///android_asset` | No origin, see below |

- If the shell's config changes the scheme or host, add the ones it sets.
- A page loaded from a file has no origin: an Android WebView on `file:///android_asset` sends `Origin: null`, a WKWebView that opened it with `loadFileURL` sends `Origin: null` from `fetch` and `Origin: file://` from `sendBeacon`, and an Electron app that loads its pages from files sends no `Origin` header at all. No list can name any of those, so leave the list empty, or serve the app from a scheme (a `WKURLSchemeHandler`, or `electron-serve`, which serves `app://-`) or from the asset loader. The script sends only the page's file name as the route, such as `/index.html`, so the folders above it, which can hold the user's name, never leave the device; the collector keeps the same rule for scripts older than 0.1.2, and keeps a route a current script names, such as `/settings/profile`, whole.
- A file page cannot `pushState` to a new path: engines allow only a new query or fragment there. A hash-routed app names its routes itself. Name the starting route before the script loads, in the inline queue stub, as the template your router matches, such as `lf('route', '/orders/:id')`, or as the route part of the hash alone, `lf('route', '/' + location.hash.replace(/^#\/?/, '').split(/[?&=]/)[0])`, so the load's own page view carries it. Never pass the whole fragment, since a fragment can carry a query or a sign-in token. The script cuts a named route at the first `?` or `#`, redacts a segment that holds `=` and replaces id-like segments, but a route should hold no values to begin with. After each later navigation, once the hash has changed, call `lf('route', '/settings')`, then `lf('page')`. Call `lf('page')` for navigations only: a router hook that also fires for the starting screen must skip that first call, or the screen counts twice. An app that routes with `pushState` gets its page views on its own and never calls `lf('page')`.
- Apps on iOS send no referrer. A link opened from an Android app in Chrome arrives as `android-app://<package>/`, and a known app is stored under its web host, such as `mail.google.com` for Gmail, in that app's channel. The package table is under Webmail and email apps in `docs/METRICS.md`, published at https://littlefriend.io/docs/metrics#channels.
- Events queued when the app goes to the background are sent as the page is hidden. An app killed while on screen (a crash, a force stop) loses what was queued in its last 5 seconds, and a kill and relaunch starts a new session.
- UTM tags on a deep link are read like any landing: pass the link's query on to the page URL (`index.html?utm_source=newsletter&utm_medium=email`) and the visit lands in that channel with those values.
- For local testing, an https asset-loader or Capacitor page cannot reach an http collector except at `localhost`: on the Android emulator, run `adb reverse tcp:<port> tcp:<port>` and point `data-api` at `http://localhost:<port>`. The real collector is https and needs neither.
- If the repo deliberately skips analytics inside the shell, keep that and say so in the report.

### Native apps

Screens drawn natively with SwiftUI, UIKit or AppKit send their own screens and events through the Swift SDK. The full guide is https://littlefriend.io/docs/ios.

1. **Install the SDK.** Add the Swift package that https://littlefriend.io/docs/ios#install names, from `0.1.0`, and link its `LittleFriend` product.
2. **Start it with the project's site key**, the public `lf_` key the script uses, once as the app launches, in the mode chosen in step 4. Leave the options out for aggregate mode.

   ```swift
   // The SwiftUI App's init, or application(_:didFinishLaunchingWithOptions:)
   var options = LittleFriend.Options()
   options.mode = .journey
   LittleFriend.start(key: "<site key>", options: options)
   ```

   With consent required, set the consent option to `.required`, and call `LittleFriend.consent(.journey)` when the person agrees, as step 4 describes for the script.
3. **Add the app id to Allowed apps**: the app's bundle id. A project admits only the apps it lists. Until the app is listed, its batches are refused with `403 app_not_allowed`, and the dashboard's data health strip names it.

   ```sh
   littlefriend apps add com.acme.shop
   ```

4. **Name the screens** with route templates, never values, as on the web. SwiftUI: `.lfScreen("/products/:id", type: "product")` on each screen's view. Anywhere else: `LittleFriend.screen("/orders/:id", type: "order")`. A UIKit app can set `autoScreens` and give each view controller a route with `LFScreen` and `lfRoute`.
5. **Track the events the plan names**, with the same names and properties as the web, so the goals and funnels of steps 8 and 9 count both: `LittleFriend.track("signup", props: ["plan": .string("pro")])`.
6. **Call `LittleFriend.flush()` after a correlated event.** In journey mode, give the app's event the correlation id the server sends with the confirmed outcome (step 12), `correlationId: hash`, and call `LittleFriend.flush()` right after it, so it goes out at once. When the app's event arrives first, the server's outcome counts under the app's platform.
7. **Verify.** Open a screen in the app, then run `littlefriend verify --source browser --since 10 --wait 120`: app batches count under the browser source. The iOS Simulator sends test traffic, which verify shows as test traffic and reports never store. A release build on a device sends real traffic.

Native Android screens, and Flutter and React Native views, send the outcomes they lead to from the backend with `@littlefriend/node` (step 12). The server key never goes inside the app.

## 15. Verify

1. Run the product: the local dev server (its origin is on the list from step 4), or the deployed site.
2. Load the site in a real browser (Playwright, agent-browser, or a person). `curl` does not run the script. Headless Chrome says so in its user agent and is counted as automation, so its visits stay out of page views and funnels, which count people. For the journey walks in item 9, run the browser headed or give it a desktop Chrome user agent. Then run `littlefriend verify --source browser --since 10 --wait 120`. It exits 0 once an accepted event from the browser in the last 10 minutes shows up, and prints its time, route and source. `--source browser` matters on a project with a log drain or the edge SDK, whose events would otherwise pass for the tag's. It exits 1 when none arrives in time. On a project that already has traffic, keep `--since` short, so an older event cannot pass for yours.
3. In the browser's network panel, `POST https://in.littlefriend.io/v1/e` answers `202` with `{"accepted": n, "dropped": 0}`. The console shows no CSP errors.
4. Click through each flow with a named event and confirm each name in the request bodies. Any `dropped` above 0 means a name or property broke a rule. The live install check (Settings, Install) shows every field kept, every property dropped, and why.
5. Replay: in the browser's network panel, `GET https://in.littlefriend.io/v1/r/config?k=<site key>` returns `"on": true`, and `POST /v1/r` answers `202`. From `curl`, send the page's origin with `-H 'Origin: https://<domain>'`: without an allowed origin the answer is `"on": false`. Then `littlefriend replay get` reads installed.
6. Server events: run the flow that sends one. `verify` shows source `server`, or `await lf.flush()` resolves with `accepted: 1`.
7. Agents: `littlefriend door get` shows the policy and its mode. On the dashboard's Agents page, the Coverage card shows the drain as Live, and the door page shows that the door has read its rules.
8. A few minutes later: `littlefriend report overview` and `littlefriend report goals` for a sanity check.
9. Walk each journey in your plan once, in one tab, step by step, on a page without `data-test` (test events stay out of reports). A few minutes later, `littlefriend funnels report fnl_XXXXXXXX` shows that session at every step. A step at 0 means its route or event name does not match what arrives: compare it with `littlefriend report pages` and the request bodies.

Verify on production after the deploy too, without `data-test`.

| Symptom | Cause |
|---|---|
| No request to `in.littlefriend.io` | CSP blocks the script, or the tag never rendered |
| `403` `origin_not_allowed` | The page's origin is not in allowed origins |
| `400` | Wrong or malformed site key, or a malformed batch |
| Sessions unavailable, funnels empty | The project or the snippet is not in journey mode. Both must be |
| Replay `403` `replay_off`, `session_in_aggregate_mode` or `route_excluded` | Replay is off, the project is in aggregate mode, or the page is excluded |
| Replay `402` `replay_card_required` | The workspace used its free recordings this month and has no card on file |
| Replay `429` `quota_exceeded` | The project stored its 1 GiB of recordings for the day, or one address used its share of that. It clears at midnight UTC. If it happens often, lower the sample rate |
| Server events `rejected` in `onError` | Wrong kind of key, or a revoked one |

## 16. Launch checklist

- [ ] One project for the domain, in the right workspace, in the right mode.
- [ ] Allowed origins list every production host, every app origin and the dev origin.
- [ ] The script is on every page, once, with `data-test` outside production.
- [ ] CSP updated, including report-only copies and header tests.
- [ ] Every goal and funnel step has its own named event. No personal data in names, properties or routes.
- [ ] The journey plan is written down, with one goal per outcome.
- [ ] 2 to 5 goals and, in journey mode, 1 to 3 funnels saved, one per journey in the plan.
- [ ] Each journey was walked once and shows at every step of its funnel report.
- [ ] `identify` sends an opaque id, and `null` on sign-out (replay only).
- [ ] Replay: shown regions checked for names, private routes excluded, widgets blocked.
- [ ] Server key in an ignored env file and in the host's secrets. Serverless code flushes.
- [ ] Door in dry run where the runtime allows it. Drain connected on Vercel.
- [ ] Ignored routes cover the product's own API paths.
- [ ] Privacy page text added.
- [ ] `littlefriend verify --source browser` exits 0 on production, and batches show `"dropped": 0`.
- [ ] No secret in your changes: `git diff <base branch> | grep -E 'lf[ser]_[A-Za-z0-9]'` prints nothing.
- [ ] Report sent.

## 17. Report back

End with this report, filled in. Use "skipped" with a reason where a step did not apply. Never include a secret.

```markdown
## Little Friend setup: <product>

- Repo and branch:
- Domain and hosts:
- Workspace:
- Project id and site key (lf_):
- Mode and consent:
- Allowed origins:
- Snippet: --framework <name>, in <file>
- CSP: <files changed, or none needed>
- Journey plan: <the table from step 3: journey, outcome goal, steps and how each is seen>
- Named events: <name, where it fires>
- Goals: <id, name, match>
- Funnels: <id, name, steps>
- Identify: <where it is called, what id it sends, or skipped>
- Replay: <on or off, rate, shown, hidden, excluded routes>
- Server events: <events, files, env var names, host secrets set or not>
- Agents: <drain id and status, door runtime, preset and mode, or skipped>
- Ignored routes: <the list, and any change from /api>
- Hybrid or native: <origins added, apps listed and SDKs started, backend events, or none>
- Privacy page: <updated, or no privacy page>
- Verify: <time, route and source that verify printed, local and production>
- Skipped, and why:
- Needs a person: <drains to connect, secrets to set, questions>
- Guide or CLI problems found:
```
