# Gatsby

Add ProductLense to every page of a Gatsby site from gatsby-ssr.js with setHeadComponents, then identify signed-in users.

Gatsby renders each page's HTML at build time from `gatsby-ssr.js`, so the script is added there once with `setHeadComponents`. Gatsby's client-side navigation uses the history API, which ProductLense records as pageviews.

## Add the script

Create or edit `gatsby-ssr.js` in the project root. Replace `SITE_ID` with the id from Settings → Sites in the ProductLense dashboard.

```jsx title="gatsby-ssr.js" {4-12}
import React from 'react';

export const onRenderBody = ({ setHeadComponents }) => {
  setHeadComponents([
    <script
      key="productlense-stub"
      dangerouslySetInnerHTML={{
        __html: 'window.productlense=window.productlense||function(){(window.productlense.q=window.productlense.q||[]).push(arguments)}',
      }}
    />,
    <script key="productlense" defer data-site="SITE_ID" src="https://api.productlense.app/a.js" />,
  ]);
};
```

Restart `gatsby develop` or rebuild after changing `gatsby-ssr.js`; Gatsby reads it only at startup.

## Identify users

Gatsby sites with sign-in usually know the user in the browser. Call `identify` once the user is loaded:

```jsx title="src/components/ProductLenseIdentify.jsx" {5}
import { useEffect } from 'react';

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

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

## Custom events

```jsx
<button onClick={() => window.productlense?.('event', 'Newsletter signup', { form: 'footer' })}>Subscribe</button>
```

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

## Verify your installation

1. Run `gatsby 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`. Click an internal link: a second pageview follows.

`gatsby develop` 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).
