# Proxy through your own server

> Serve the Reveata script and send events through your own domain with Next.js, Vercel, Netlify, Cloudflare Workers, Nginx, Caddy, Apache, Express, Laravel, WordPress and more.

If you would rather not add a DNS record for the [managed proxy](https://reveata.com/docs/managed-proxy), you can pass Reveata's two addresses through a server or platform you already run. The browser then only talks to your own domain.

Two addresses need to go through:

| On your site (example) | Goes to                     | Method | Notes                                                     |
| ---------------------- | --------------------------- | ------ | --------------------------------------------------------- |
| `/dt/script.js`        | `https://reveata.com/js/script.js` | GET    | Use `/js/script.cookieless.js` for the cookieless build.  |
| `/dt/event`            | `https://reveata.com/api/collect`  | POST   | Body is JSON sent as `text/plain`, at most 16 KB.         |

The paths on your site can be anything. Avoid words like `analytics` or `tracking`, which some blockers look for. Then point the snippet at them, with `data-api` set to your event path:

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

## 1. Create a proxy secret

Your proxy tells Reveata the visitor's IP address. Reveata only believes it when the request also carries your website's proxy secret, so nobody else can pretend to be your proxy.

1. Open your website in Reveata, then **Settings → General**. You need to be an **admin** or the **owner**.
2. In **Tracking code**, find **Proxy secret** and choose **Create proxy secret**.
3. Copy the secret (it starts with `dt_proxy_`). It is shown only once.
4. Store it as an environment variable named `REVEATA_PROXY_SECRET` on the server or platform that runs your proxy.

Keep the secret on your server. Never put it in the snippet, in client-side JavaScript or in a file the browser can download. If it leaks, choose **Rotate**: the old secret stops working right away, so update the environment variable straight after.

## 2. What the proxy must send

On `/dt/event`, your proxy adds two headers:

- **`X-Reveata-Proxy-Secret`**: the secret from `REVEATA_PROXY_SECRET`.
- **`X-Reveata-Client-IP`**: the visitor's IP address, as your server sees it. If you leave it out, Reveata uses the `X-Forwarded-For` entry your proxy added.

With a valid secret, Reveata uses that address to locate visitors, apply the IP exclusions in **Settings → General**, tell cookieless visitors apart and apply the per-visitor limit of events per minute. With a wrong or missing secret, both headers are ignored: visits still count, but they are located and limited by your proxy's own address.

It also passes on:

- **The browser's headers**: `User-Agent`, `Accept-Language`, `Origin`, `Referer` and the `Sec-Fetch-*` headers. Reveata uses them to tell browsers from bots; events whose headers look scripted are dropped as bot traffic, with or without a secret.
- **The request body** of `/dt/event`, unchanged.
- **Not your cookies.** The script sends its ids in the body, so Reveata needs no cookies from your domain. Drop the `Cookie` header so your own session cookies never leave your server.

Reveata answers events with `202` and no body. The script is served with `Cache-Control: public, max-age=86400, stale-while-revalidate=604800` and an `ETag`; pass those on so browsers and CDNs cache it. Never cache `/dt/event`.

The configs below forward the visitor's IP from what your server sees. If your server itself sits behind a load balancer or CDN, make sure that address is the visitor's and not the load balancer's (each section says how).

## Next.js

Proxy the script with a rewrite in `next.config.ts` (or `next.config.js`):

```ts
import type { NextConfig } from 'next';

const nextConfig: NextConfig = {
  async rewrites() {
    return [{ source: '/dt/script.js', destination: 'https://reveata.com/js/script.js' }];
  },
};

export default nextConfig;
```

Rewrites can't add headers, so events go through a route handler. With the App Router, create `app/dt/event/route.ts`:

```ts
const PASS = [
  'user-agent',
  'accept-language',
  'origin',
  'referer',
  'sec-fetch-dest',
  'sec-fetch-mode',
  'sec-fetch-site',
];

export async function POST(request: Request) {
  const headers = new Headers({ 'content-type': 'text/plain' });
  for (const name of PASS) {
    const value = request.headers.get(name);
    if (value) headers.set(name, value);
  }
  headers.set('x-reveata-proxy-secret', process.env.REVEATA_PROXY_SECRET ?? '');
  const ip = request.headers.get('x-forwarded-for')?.split(',')[0]?.trim();
  if (ip) headers.set('x-reveata-client-ip', ip);

  const upstream = await fetch('https://reveata.com/api/collect', {
    method: 'POST',
    headers,
    body: await request.text(),
    cache: 'no-store',
  });
  return new Response(null, { status: upstream.status });
}
```

Add `REVEATA_PROXY_SECRET` to `.env.local` (and to your host's environment variables) without the `NEXT_PUBLIC_` prefix, so it never reaches the browser. On Vercel, `X-Forwarded-For` holds the visitor's address. On your own server, put Next.js behind a proxy that sets it (Nginx, Caddy or your load balancer). Then add the snippet above to your root layout.

## Vercel

For other frameworks on Vercel, add a function at `api/dt-event.js`:

```js
const PASS = [
  'user-agent',
  'accept-language',
  'origin',
  'referer',
  'sec-fetch-dest',
  'sec-fetch-mode',
  'sec-fetch-site',
];

export async function POST(request) {
  const headers = new Headers({ 'content-type': 'text/plain' });
  for (const name of PASS) {
    const value = request.headers.get(name);
    if (value) headers.set(name, value);
  }
  headers.set('x-reveata-proxy-secret', process.env.REVEATA_PROXY_SECRET ?? '');
  const ip = request.headers.get('x-forwarded-for')?.split(',')[0]?.trim();
  if (ip) headers.set('x-reveata-client-ip', ip);

  const upstream = await fetch('https://reveata.com/api/collect', {
    method: 'POST',
    headers,
    body: await request.text(),
  });
  return new Response(null, { status: upstream.status });
}
```

Then route both paths in `vercel.json`:

```json
{
  "rewrites": [
    { "source": "/dt/script.js", "destination": "https://reveata.com/js/script.js" },
    { "source": "/dt/event", "destination": "/api/dt-event" }
  ]
}
```

Add `REVEATA_PROXY_SECRET` under **Project Settings → Environment Variables** and redeploy. Vercel sets `X-Forwarded-For` to the visitor's address itself.

## Netlify

Proxy the script in `_redirects` in your publish folder. The `200` status makes it a proxy, not a redirect:

```
/dt/script.js  https://reveata.com/js/script.js  200
```

Send events through an edge function at `netlify/edge-functions/dt-event.js`:

```js
const PASS = [
  'user-agent',
  'accept-language',
  'origin',
  'referer',
  'sec-fetch-dest',
  'sec-fetch-mode',
  'sec-fetch-site',
];

export default async (request, context) => {
  if (request.method !== 'POST') return new Response(null, { status: 405 });
  const headers = new Headers({ 'content-type': 'text/plain' });
  for (const name of PASS) {
    const value = request.headers.get(name);
    if (value) headers.set(name, value);
  }
  headers.set('x-reveata-proxy-secret', Netlify.env.get('REVEATA_PROXY_SECRET') ?? '');
  headers.set('x-reveata-client-ip', context.ip);

  const upstream = await fetch('https://reveata.com/api/collect', {
    method: 'POST',
    headers,
    body: await request.text(),
  });
  return new Response(null, { status: upstream.status });
};

export const config = { path: '/dt/event' };
```

Add `REVEATA_PROXY_SECRET` under **Site configuration → Environment variables**, with a scope that includes functions, and redeploy.

## Cloudflare Workers

Add a Worker on a route that covers the two paths, for example `example.com/dt/*`:

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

export default {
  async fetch(request, env) {
    const { pathname } = new URL(request.url);
    if (pathname === '/dt/script.js' && request.method === 'GET') {
      return fetch(`${UPSTREAM}/js/script.js`);
    }
    if (pathname === '/dt/event' && request.method === 'POST') {
      const headers = new Headers({ 'content-type': 'text/plain' });
      for (const name of PASS) {
        const value = request.headers.get(name);
        if (value) headers.set(name, value);
      }
      headers.set('x-reveata-proxy-secret', env.REVEATA_PROXY_SECRET ?? '');
      headers.set('x-reveata-client-ip', request.headers.get('cf-connecting-ip') ?? '');
      const upstream = await fetch(`${UPSTREAM}/api/collect`, {
        method: 'POST',
        headers,
        body: request.body,
      });
      return new Response(null, { status: upstream.status });
    }
    return new Response('Not found', { status: 404 });
  },
};
```

Store the secret with `npx wrangler secret put REVEATA_PROXY_SECRET`, or under **Settings → Variables and Secrets** of the Worker in the Cloudflare dashboard (type **Secret**).

## Nginx

Nginx doesn't read environment variables in its config. Put the secret in a small file at the `http` level, for example `/etc/nginx/conf.d/reveata.conf`, readable only by root (`chmod 600`):

```nginx
map $host $reveata_proxy_secret {
    default "dt_proxy_your_secret";
}
```

With the official Docker image you can keep it in an environment variable instead: save the same block as `/etc/nginx/templates/reveata.conf.template` with `default "${REVEATA_PROXY_SECRET}";`, and the image writes `/etc/nginx/conf.d/reveata.conf` from it at startup.

Then, inside the `server` block of your site:

```nginx
location = /dt/script.js {
    proxy_pass https://reveata.com/js/script.js;
    proxy_ssl_server_name on;
    proxy_set_header Cookie "";
}

location = /dt/event {
    proxy_pass https://reveata.com/api/collect;
    proxy_ssl_server_name on;
    proxy_set_header X-Reveata-Proxy-Secret $reveata_proxy_secret;
    proxy_set_header X-Reveata-Client-IP $remote_addr;
    proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
    proxy_set_header Cookie "";
}
```

Nginx passes the other request headers on by default and sends the upstream's host name as `Host`. If Nginx runs behind a load balancer or CDN, set `set_real_ip_from` and `real_ip_header` (the `realip` module) so `$remote_addr` is the visitor's address.

## Caddy

In your site's block of the Caddyfile:

```
handle /dt/script.js {
	rewrite * /js/script.js
	reverse_proxy https://reveata.com {
		header_up Host {upstream_hostport}
		header_up -Cookie
	}
}

handle /dt/event {
	rewrite * /api/collect
	reverse_proxy https://reveata.com {
		header_up Host {upstream_hostport}
		header_up X-Reveata-Proxy-Secret {env.REVEATA_PROXY_SECRET}
		header_up X-Reveata-Client-IP {client_ip}
		header_up -Cookie
	}
}
```

Set `REVEATA_PROXY_SECRET` in the environment Caddy runs with (for example `Environment=` in a systemd override, or `environment:` in Docker Compose). Caddy sets `X-Forwarded-For` itself. If Caddy runs behind a load balancer or CDN, add it under `trusted_proxies` in the global `servers` options so `{client_ip}` is the visitor's address.

## Apache

With `mod_proxy`, `mod_proxy_http`, `mod_ssl` and `mod_headers` enabled, in your `VirtualHost`:

```apache
SSLProxyEngine on

<Location "/dt/script.js">
    ProxyPass "https://reveata.com/js/script.js"
    RequestHeader unset Cookie
</Location>

<Location "/dt/event">
    ProxyPass "https://reveata.com/api/collect"
    RequestHeader unset Cookie
    RequestHeader set X-Reveata-Proxy-Secret "${REVEATA_PROXY_SECRET}"
    RequestHeader set X-Reveata-Client-IP "expr=%{REMOTE_ADDR}"
</Location>
```

Apache reads `${REVEATA_PROXY_SECRET}` from its environment when it starts. On Debian and Ubuntu, add `export REVEATA_PROXY_SECRET=dt_proxy_…` to `/etc/apache2/envvars` (readable only by root), then restart Apache. Apache adds `X-Forwarded-For` itself. If Apache runs behind a load balancer or CDN, enable `mod_remoteip` so `REMOTE_ADDR` is the visitor's address.

## Express

With Node.js 18 or later (built-in `fetch`):

```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, uncomment so req.ip is the visitor and not the load balancer:
// 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.status(r.status).end();
});
```

## Laravel

Add the secret to `config/services.php`, and `REVEATA_PROXY_SECRET=dt_proxy_…` to your `.env`:

```php
'reveata' => [
    'proxy_secret' => env('REVEATA_PROXY_SECRET'),
],
```

Then in `routes/web.php`:

```php
use Illuminate\Foundation\Http\Middleware\ValidateCsrfToken;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Http;
use Illuminate\Support\Facades\Route;

Route::get('/dt/script.js', function () {
    $r = Http::get('https://reveata.com/js/script.js');

    return response($r->body(), $r->status())
        ->header('Content-Type', 'text/javascript; charset=utf-8')
        ->header('Cache-Control', $r->header('Cache-Control') ?: 'public, max-age=86400');
});

Route::post('/dt/event', function (Request $request) {
    $headers = [
        'X-Reveata-Proxy-Secret' => (string) config('services.reveata.proxy_secret'),
        'X-Reveata-Client-IP' => $request->ip(),
    ];
    foreach (['User-Agent', 'Accept-Language', 'Origin', 'Referer', 'Sec-Fetch-Dest', 'Sec-Fetch-Mode', 'Sec-Fetch-Site'] as $h) {
        if ($request->hasHeader($h)) {
            $headers[$h] = $request->header($h);
        }
    }
    $r = Http::withHeaders($headers)
        ->withBody($request->getContent(), 'text/plain')
        ->post('https://reveata.com/api/collect');

    return response('', $r->status());
})->withoutMiddleware([ValidateCsrfToken::class]);
```

The event route has no CSRF token, so it skips CSRF checks. On Laravel 10 and earlier, add `dt/event` to `$except` in `app/Http/Middleware/VerifyCsrfToken.php` instead of `withoutMiddleware`. Reading the secret through `config()` keeps it working after `php artisan config:cache`. If Laravel runs behind a load balancer or CDN, configure trusted proxies so `$request->ip()` is the visitor's address.

## WordPress, without a plugin

Add the secret to `wp-config.php`, which WordPress never serves to browsers, above the line that says to stop editing:

```php
define( 'REVEATA_PROXY_SECRET', getenv( 'REVEATA_PROXY_SECRET' ) ?: '' );
```

If your host has no environment variables, put the secret itself between the quotes instead of the `getenv()` call. Then add to your child theme's `functions.php`. The two addresses are WordPress REST routes:

```php
add_action('rest_api_init', function () {
    register_rest_route('dt/v1', '/script.js', [
        'methods' => 'GET',
        'permission_callback' => '__return_true',
        'callback' => function () {
            $r = wp_remote_get('https://reveata.com/js/script.js');
            header('Content-Type: text/javascript; charset=utf-8');
            header('Cache-Control: public, max-age=86400');
            echo wp_remote_retrieve_body($r);
            exit;
        },
    ]);
    register_rest_route('dt/v1', '/event', [
        'methods' => 'POST',
        'permission_callback' => '__return_true',
        'callback' => function (WP_REST_Request $request) {
            $headers = [
                'Content-Type' => 'text/plain',
                'X-Reveata-Proxy-Secret' => defined('REVEATA_PROXY_SECRET') ? REVEATA_PROXY_SECRET : '',
                'X-Reveata-Client-IP' => $_SERVER['REMOTE_ADDR'] ?? '',
            ];
            foreach (['User-Agent', 'Accept-Language', 'Origin', 'Referer', 'Sec-Fetch-Dest', 'Sec-Fetch-Mode', 'Sec-Fetch-Site'] as $h) {
                $v = $request->get_header($h);
                if ($v) {
                    $headers[$h] = $v;
                }
            }
            $r = wp_remote_post('https://reveata.com/api/collect', ['headers' => $headers, 'body' => $request->get_body()]);
            return new WP_REST_Response(null, wp_remote_retrieve_response_code($r) ?: 502);
        },
    ]);
});
```

Then use these paths in the snippet:

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

If your site runs behind a CDN or load balancer, `REMOTE_ADDR` is its address unless your host or a plugin sets it to the visitor's.

## Check that it works

1. Open `https://your-site/dt/script.js` (or your own path): you should see the script.
2. Visit your site in a normal browser window, then open the **Realtime** view of your website in Reveata. Your visit should appear within a few seconds, located in your own city rather than where your proxy runs. See [Verify your installation](https://reveata.com/docs/verify-your-installation) for more checks.

If your visits count but show your proxy's location, Reveata is ignoring the forwarded address. Its answer to `/dt/event` carries an `x-reveata-proxy` header that says why (Nginx, Caddy and Apache pass it back to the browser, where you can see it in the network tab of the developer tools):

| `x-reveata-proxy`        | Meaning                                                                                        |
| ------------------------- | ---------------------------------------------------------------------------------------------- |
| `trusted`                 | Secret accepted; the forwarded address is used.                                                |
| `proxy_secret_invalid`    | The secret is missing, mistyped, rotated or deleted. Copy a new one into the environment variable. |
| `proxy_client_ip_invalid` | The secret is right, but `X-Reveata-Client-IP` is empty or not an IP address.                 |

No header at all means the proxy didn't send `X-Reveata-Proxy-Secret`.

## More platforms

Step-by-step pages for other stacks, with the same two paths and headers:

- [NGINX](https://reveata.com/docs/nginx#proxy-through-nginx), [Caddy](https://reveata.com/docs/caddy#proxy-through-caddy) and [Express](https://reveata.com/docs/express#proxy-through-express), step by step with checks
- [Plain PHP](https://reveata.com/docs/proxy-php), without a framework
- [Flask](https://reveata.com/docs/proxy-flask) and [FastAPI](https://reveata.com/docs/proxy-fastapi)
- [Astro](https://reveata.com/docs/proxy-astro), with a server adapter
- [Firebase Hosting](https://reveata.com/docs/proxy-firebase), through a Cloud Function
- [DigitalOcean](https://reveata.com/docs/proxy-digitalocean) App Platform and Droplets
- [The Vite dev server](https://reveata.com/docs/proxy-vite), to try it locally

On other hosts, use the guide for your framework and forward the visitor's address your host reports. Fly.io, for example, puts it in the `Fly-Client-IP` header.
