# React (Vite)

Add ProductLense to a React single-page app built with Vite by pasting the script into index.html.

A React app built with Vite has one `index.html`, so the script goes there once. React Router and other history-based routers are recorded without extra code, because the script listens to `pushState`, `replaceState` and `popstate`.

## Add the script

Replace `SITE_ID` with the id from Settings → Sites in the ProductLense dashboard.

```html title="index.html" {5-6}
<!doctype html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <script>window.productlense=window.productlense||function(){(window.productlense.q=window.productlense.q||[]).push(arguments)}</script>
    <script defer data-site="SITE_ID" src="https://api.productlense.app/a.js"></script>
  </head>
  <body>
    <div id="root"></div>
    <script type="module" src="/src/main.tsx"></script>
  </body>
</html>
```

Keep the ProductLense tag as written. Vite leaves an external classic script in `index.html` untouched; do not import it from `main.tsx`.

## Identify users

Call `identify` once the signed-in user is known, for example from a hook used in your app shell.

```tsx title="src/useProductLenseIdentify.ts" {11}
import { useEffect } from 'react';

declare global {
  interface Window {
    productlense?: (...args: unknown[]) => void;
  }
}

export function useProductLenseIdentify(user: { id: string } | null) {
  useEffect(() => {
    if (user) window.productlense?.('identify', user.id);
  }, [user]);
}
```

Use the same id you store on the customer in your billing provider; see [how payments are attributed](/docs/revenue/attribution).

## Custom events

```tsx
<button onClick={() => window.productlense?.('event', 'Upgrade clicked', { plan: 'growth' })}>
  Upgrade
</button>
```

See [custom events](/docs/track/custom-events) for naming rules.

## Verify your installation

1. Build and deploy, then open your site in a normal browser window.
2. Open the Live page in the ProductLense dashboard. Your visit appears within a few seconds.
3. In the browser's developer tools, the Network tab shows a `POST` to `https://api.productlense.app/api/e` with status `204`. Navigate to another route: a second pageview follows.

The Vite dev server runs on `localhost`, where nothing is sent unless you add `data-dev="true"` to the tag. Ad blockers in your own browser may block the request. If the visit does not appear, follow [Verify your installation](/docs/install/verify).
