# Install on Express

> Add Reveata to pages an Express app serves, proxy the script and events through two routes, and credit payments to their visits.

An Express app serves its pages from templates, static files or a front-end build. The snippet goes once in the file that renders `<head>` for every page.

Copy the snippet from your Reveata dashboard (it contains your website’s tracking id):

```html
<script
  defer
  data-website-id="ws_your_tracking_id"
  src="https://reveata.com/js/script.js"
></script>
```

## Add it to your site

Paste the snippet before `</head>` in the right place for how your app renders pages:

- **A view engine** (EJS, Pug, Handlebars): the layout or partial that renders `<head>`, for example `views/partials/head.ejs` or the `layout.pug` other views extend.
- **Static files** with `express.static('public')`: each HTML file in `public`, or the one `index.html` of a single-page app.
- **A front-end build** (React, Vue, Svelte with Vite) served by Express: the `index.html` of that front end. Its guide says where: [React](https://reveata.com/docs/react), [Vue](https://reveata.com/docs/vue).

For a Pug layout, the tag is written like this:

```pug
head
  script(defer data-website-id="ws_your_tracking_id" src="https://reveata.com/js/script.js")
```

Deploy, and that’s it: page changes in a single-page app go through the browser’s History API, which the script follows.

## Check it works

Open your deployed site in a normal browser window with ad blockers turned off for it, then open **Realtime** in Reveata: your visit appears within a few seconds. If it doesn’t, follow [Verify your installation](https://reveata.com/docs/verify-your-installation). The script ignores `localhost` unless you add `data-allow-localhost="true"`.

## Proxy through Express

Two routes can serve the Reveata script from your own domain and pass events on, so fewer visits are lost to ad blockers.

1. **Create a proxy secret.** In Reveata, open your website’s **Settings → General**, find **Proxy secret** in **Tracking code**, and choose **Create proxy secret**. Store it on the server as the environment variable `REVEATA_PROXY_SECRET`. Never send it to the browser.
2. **Add the routes** (Node.js 18 or later, for the built-in `fetch`), before your other routes:

```js
const express = require('express');

const UPSTREAM = 'https://reveata.com';
const PASS = ['user-agent', 'accept-language', 'origin', 'referer', 'sec-fetch-dest', 'sec-fetch-mode', 'sec-fetch-site'];

const app = express();
// Behind one load balancer or CDN (Heroku, Render, Railway, Fly.io…), so req.ip is the visitor:
app.set('trust proxy', 1);

app.get('/dt/script.js', async (req, res) => {
  const r = await fetch(`${UPSTREAM}/js/script.js`);
  res.status(r.status);
  res.set('content-type', r.headers.get('content-type') ?? 'text/javascript');
  res.set('cache-control', r.headers.get('cache-control') ?? 'public, max-age=86400');
  res.send(Buffer.from(await r.arrayBuffer()));
});

app.post('/dt/event', express.text({ type: '*/*', limit: '16kb' }), async (req, res) => {
  const headers = {
    'content-type': 'text/plain',
    'x-reveata-proxy-secret': process.env.REVEATA_PROXY_SECRET ?? '',
    'x-reveata-client-ip': req.ip,
  };
  for (const name of PASS) if (req.get(name)) headers[name] = req.get(name);
  const r = await fetch(`${UPSTREAM}/api/collect`, { method: 'POST', headers, body: req.body });
  res.set('x-reveata-proxy', r.headers.get('x-reveata-proxy') ?? '');
  res.status(r.status).end();
});
```

3. **Point the snippet at them:**

```html
<script defer data-website-id="ws_your_tracking_id" data-api="/dt/event" src="/dt/script.js"></script>
```

Set `trust proxy` to the number of proxies in front of your app: `1` for one load balancer, more if there are several. Without any proxy in front, remove the line, or `req.ip` could be set by anyone with an `X-Forwarded-For` header.

To check it: open `/dt/script.js` on your site, then find the request to `/dt/event` in the browser’s **Network** tab. Its `x-reveata-proxy` response header says `trusted` when the secret was accepted, and **Realtime** shows your own city. Other answers are explained in [Proxy through your own server](https://reveata.com/docs/self-hosted-proxy#check-that-it-works). Or skip the code and use the [managed proxy](https://reveata.com/docs/managed-proxy): one DNS record.

## Revenue

First connect your payment provider in Reveata: see [Connect a payment provider](https://reveata.com/docs/connect-a-payment-provider). Then pass the Reveata visitor id with each checkout, so the payment is credited to the visit that brought the buyer.

In the browser, send the ids with the request that starts the checkout:

```js
const res = await fetch('/checkout', {
  method: 'POST',
  headers: { 'content-type': 'application/json' },
  body: JSON.stringify({ priceId: 'price_123', ...(window.reveata?.metadata?.() ?? {}) }),
});
window.location.href = (await res.json()).url;
```

On the server, put them in the Stripe Checkout Session’s metadata:

```js
const Stripe = require('stripe');
const stripe = new Stripe(process.env.STRIPE_SECRET_KEY);

app.post('/checkout', express.json(), async (req, res) => {
  const metadata = {};
  for (const key of ['reveata_visitor_id', 'reveata_session_id']) {
    if (typeof req.body[key] === 'string' && req.body[key]) metadata[key] = req.body[key];
  }
  const session = await stripe.checkout.sessions.create({
    mode: 'payment',
    line_items: [{ price: req.body.priceId, quantity: 1 }],
    success_url: `${req.protocol}://${req.get('host')}/thanks?session_id={CHECKOUT_SESSION_ID}`,
    metadata,
  });
  res.json({ url: session.url });
});
```

In a real app, check `priceId` against the prices you sell.

For other providers, the same two ids go in their custom data: see the provider’s page under [Connect a payment provider](https://reveata.com/docs/connect-a-payment-provider).

**Payments from your own billing.** If Reveata doesn’t connect to your provider, send each payment with the [Payments API](https://reveata.com/docs/payments-api):

```js
await fetch('https://reveata.com/api/v1/payments', {
  method: 'POST',
  headers: {
    Authorization: `Bearer ${process.env.REVEATA_SITE_KEY}`,
    'Content-Type': 'application/json',
  },
  body: JSON.stringify({
    transactionId: `order_${order.id}`, // unique: retries are then safe
    amount: order.totalWithoutTax, // major units, e.g. 49.00
    currency: 'USD',
    email: order.email,
    visitorId: order.reveataVisitorId, // saved from the checkout request
  }),
});
```

## Goals

Add `data-reveata-goal="signup"` to a button or link in your views, or call `window.reveata?.('goal', 'signup')` from your front-end code. See [Custom goals](https://reveata.com/docs/custom-goals).

## Common pitfalls

- **`trust proxy` set wrong.** Too low and every visit gets your load balancer’s address; on with no proxy in front and visitors can choose their own address.
- **Helmet’s Content Security Policy.** With `helmet()`, allow the Reveata script, or use the proxy so `'self'` covers it: see [Content Security Policy](https://reveata.com/docs/content-security-policy).
- **Counting payments twice.** With your payment provider connected in Reveata, don’t also send the same payments with the Payments API.
