# Netlify

Serve the ProductLense script from your Netlify domain with a _redirects rule, and forward events through a Netlify Function on the Scale plan.

Netlify proxies a path to another host when a redirect rule has status `200`. That is enough to serve the script; forwarding events needs a function, because the visitor's IP address has to be added to each event.

## Serve the script

```text tab="_redirects" title="_redirects"
/js/a.js  https://api.productlense.app/a.js  200
```

```toml tab="netlify.toml" title="netlify.toml"
[[redirects]]
  from = "/js/a.js"
  to = "https://api.productlense.app/a.js"
  status = 200
```

```html
<script defer data-site="SITE_ID" data-api="https://api.productlense.app" src="/js/a.js"></script>
```

## Forward events (Scale plan)

Store an API key with the `events` scope as the `PL_API_KEY` environment variable, then add this function. Its `path` makes it answer at `/m/api/e` with no redirect rule.

```ts title="netlify/functions/productlense-events.mts"
import type { Config, Context } from '@netlify/functions';

type Event = Record<string, unknown>;

export default async (req: Request, context: Context) => {
  if (req.method !== 'POST') return new Response(null, { status: 405 });
  const text = await req.text();
  if (text.length > 8192) return new Response(null, { status: 413 });
  let body: { b?: Event[] } & Event;
  try {
    body = JSON.parse(text);
  } catch {
    return new Response(null, { status: 400 });
  }
  const extra = { ip: context.ip, ua: req.headers.get('user-agent') ?? '' };
  const out = body.b ? { ...body, b: body.b.map((e) => ({ ...e, ...extra })) } : { ...body, ...extra };
  const r = await fetch('https://api.productlense.app/api/v1/events', {
    method: 'POST',
    headers: { Authorization: `Bearer ${Netlify.env.get('PL_API_KEY')}`, 'Content-Type': 'application/json' },
    body: JSON.stringify(out),
  });
  return new Response(null, { status: r.status });
};

export const config: Config = { path: '/m/api/e' };
```

Then set `data-api="https://example.com/m"` on the tag.

## Check it works

1. Open `https://example.com/js/a.js`: it returns JavaScript.
2. Load a page with the developer tools open. The Network tab shows `a.js` from your domain and a `POST` to `api/e` with status `204`.
3. Open the Live page in the ProductLense dashboard. Your visit appears within a few seconds.
