# Proxy The Snippet Through Your Own Server

> Forward the tracking snippet through your own server, worker or edge function, with the visitor's IP address, so ad blockers miss it and locations stay right.

Source: https://behavly.io/help-center/user-activity/proxy-through-your-own-server · Behavly Help Center · Heatmaps & Tracking

Ad blockers stop the snippet when it loads from `behavly.io`. The [managed proxy](https://behavly.io/help-center/user-activity/proxy-through-your-subdomain) is the way we recommend around that: one DNS record, no code, and Behavly runs it. This page is for when you would rather send the snippet through a server, worker or edge function you already run.

The usual way of doing that loses one thing: the visitor's address. Behavly works out where a visit comes from by the address the request arrives from, and through your server that is your server, so every visitor shows up in your data centre's city. Each setup below passes the visitor's address on, so locations stay right.

#### How It Works

Your server answers three kinds of address under a path of your choosing, `/bv/` on this page, and forwards each to Behavly:

| On your site | Forwarded to |
| --- | --- |
| `/bv/t.js` | `https://behavly.io/t.js`, the snippet |
| `/bv/bv-overlay.js` | `https://behavly.io/bv-overlay.js`, the heatmap overlay |
| `/bv/api/track/…` | `https://behavly.io/api/track/…`, where the snippet sends what it records |

Then change the `src` of your script tag and deploy. The rest of the tag stays as it is. The snippet sends everything to wherever it was loaded from, so nothing else changes:

```html
<script async src="/bv/t.js" data-pid="YOUR_WRITE_KEY"></script>
```

> Note: Pick a path that says nothing, such as `/bv/` or `/x/`. Ad blockers also block by name, and a path with `analytics`, `tracking` or `behavly` in it is the kind they list. If you choose another path, change `/bv` everywhere in the code below.

#### Pass On The Visitor's Address

Your proxy adds one header to every request it forwards, holding the address the visitor connected from:

```http
X-Behavly-Client-IP: 81.2.69.142
```

- Behavly uses it to look up where the visitor is, and for nothing else: not to identify anyone, not to count requests and not to tell bots apart. The address is not stored.
- The lookup runs on Behavly's own servers, in a copy of DB-IP's database, so the address is not sent anywhere else.
- Only a public address counts. A private or reserved one, such as `10.0.0.5`, `192.168.1.20` or `::1`, or anything that is not an IP address, is ignored, and the location then comes from the address that connected, as it would without the header.

Why not `X-Forwarded-For`, which proxies already send? Behavly runs on Vercel, which replaces `X-Forwarded-For` with the address that connected to it, so that it cannot be faked. The visitor's address has to travel in a header of its own.

> Note: Anyone who sends requests to Behavly directly can put any address in this header. All it can do is move where their own visits appear on the map, which is why Behavly trusts it for location and for nothing else.

#### What Every Proxy Must Do

Each setup below does these five things. Keep them if you adapt one, or follow them to write your own for another platform:

- **Forward only** `/bv/t.js`, `/bv/bv-overlay.js` and `/bv/api/track/…`, and answer `404` for anything else under `/bv/`.
- **Send the visitor's address** in `X-Behavly-Client-IP`.
- **Pass the request on unchanged:** the method, the body exactly as it arrived, and the `Content-Type`, `User-Agent`, `Origin`, `Sec-GPC` and `DNT` headers. Don't parse the body: as a page closes, the snippet sends its last batch as `text/plain`. `Sec-GPC` and `DNT` carry the visitor's privacy signals, which Behavly honours when your site asks it to.
- **Never forward cookies or the `Authorization` header.** Behavly needs neither, and your visitors' sessions must not leave your site.
- **Return Behavly's answer:** its status code and body, with its `Content-Type`, `Cache-Control` and `X-Behavly-Client-IP-Status` headers.

#### Next.js

Add a route handler. A rewrite in `next.config` is not enough: it cannot add a header, so Behavly sees the address of whatever made the request rather than the visitor's, and places visits wherever that is.

Where: `app/bv/[...path]/route.ts`, or `src/app/bv/[...path]/route.ts` if your app is in `src`.

```ts
// app/bv/[...path]/route.ts
// Forwards /bv/t.js, /bv/bv-overlay.js and /bv/api/track/* to Behavly,
// with the visitor's IP address so their location is right.
const BEHAVLY = "https://behavly.io";
const ALLOWED = /^\/bv\/(t\.js|bv-overlay\.js|api\/track\/[\w-]+)$/;
const FORWARD = ["content-type", "user-agent", "origin", "sec-gpc", "dnt"];
const RETURN = ["content-type", "cache-control", "x-behavly-client-ip-status"];

async function proxy(request: Request): Promise<Response> {
  const url = new URL(request.url);
  const match = ALLOWED.exec(url.pathname);
  if (!match) return new Response("Not found", { status: 404 });

  const headers = new Headers();
  for (const name of FORWARD) {
    const value = request.headers.get(name);
    if (value) headers.set(name, value);
  }
  // On Vercel, x-real-ip is the visitor: Vercel sets it, so it can't be faked.
  // Behind your own load balancer, the first x-forwarded-for entry is.
  const ip = request.headers.get("x-real-ip") ?? request.headers.get("x-forwarded-for")?.split(",")[0]?.trim();
  if (ip) headers.set("x-behavly-client-ip", ip);

  let upstream: Response;
  try {
    upstream = await fetch(BEHAVLY + "/" + match[1] + url.search, {
      method: request.method,
      headers,
      body: request.method === "GET" ? undefined : await request.arrayBuffer(),
      cache: "no-store",
    });
  } catch {
    return new Response("Bad gateway", { status: 502 });
  }

  const out = new Headers();
  for (const name of RETURN) {
    const value = upstream.headers.get(name);
    if (value) out.set(name, value);
  }
  return new Response(upstream.body, { status: upstream.status, headers: out });
}

export const GET = proxy;
export const POST = proxy;
```

- On Vercel, `x-real-ip` is the visitor's address. Hosted elsewhere behind your own load balancer, the first `x-forwarded-for` entry is, or whichever header that load balancer sets.
- If your `proxy.ts` or `middleware.ts` sends signed-out visitors to a login page, leave `/bv` out of its `matcher`.
- With `next/script`: `<Script src="/bv/t.js" data-pid="YOUR_WRITE_KEY" strategy="afterInteractive" />`.

#### Express

Where: a new file, `behavly-proxy.js`, mounted in your app.

```js
// behavly-proxy.js: forwards /bv/* to Behavly with the visitor's IP address.
// Needs Node 18 or later (built-in fetch) and Express 4 or 5.
const express = require("express");

const BEHAVLY = "https://behavly.io";
const ALLOWED = /^\/(t\.js|bv-overlay\.js|api\/track\/[\w-]+)$/;
const FORWARD = ["content-type", "user-agent", "origin", "sec-gpc", "dnt"];
const RETURN = ["content-type", "cache-control", "x-behavly-client-ip-status"];

const router = express.Router();

// The body exactly as it was sent: JSON, or text/plain from the snippet's
// last batch as the page closes.
router.use(express.raw({ type: () => true, limit: "1mb" }));

router.use(async (req, res) => {
  if (!ALLOWED.test(req.path)) return res.sendStatus(404);

  const headers = {};
  for (const name of FORWARD) {
    const value = req.get(name);
    if (value) headers[name] = value;
  }
  // req.ip is the visitor once "trust proxy" matches your setup (see below).
  if (req.ip) headers["x-behavly-client-ip"] = req.ip;

  try {
    const upstream = await fetch(BEHAVLY + req.url, {
      method: req.method,
      headers,
      body: Buffer.isBuffer(req.body) && req.body.length > 0 ? req.body : undefined,
    });
    for (const name of RETURN) {
      const value = upstream.headers.get(name);
      if (value) res.set(name, value);
    }
    res.status(upstream.status).send(Buffer.from(await upstream.arrayBuffer()));
  } catch {
    res.sendStatus(502);
  }
});

module.exports = router;
```

```js
// app.js
const express = require("express");
const app = express();

// Only with a load balancer or proxy in front of Express (Heroku, Render,
// nginx…), so req.ip is the visitor rather than that proxy. Leave it out
// when Express faces the internet itself.
app.set("trust proxy", 1);

// Before express.json() or any other body parser, so the body reaches
// Behavly untouched.
app.use("/bv", require("./behavly-proxy"));
```

`req.ip` is the visitor only when `trust proxy` matches what sits in front of Express: leave it unset when Express faces the internet itself, and use `1` behind one load balancer. Behind Cloudflare, use `req.get("cf-connecting-ip")` instead of `req.ip`.

#### PHP

Where: `bv.php` in your site's root, plus one rewrite rule for Apache or Nginx.

```php
<?php
// bv.php: forwards /bv/* to Behavly with the visitor's IP address.
// Needs PHP 7.4 or later with the curl extension.
$behavly = 'https://behavly.io';
$path = '/' . ltrim((string) ($_GET['bv_path'] ?? ''), '/');
$method = $_SERVER['REQUEST_METHOD'];
if (!preg_match('#^/(t\.js|bv-overlay\.js|api/track/[\w-]+)$#', $path) || !in_array($method, ['GET', 'POST'], true)) {
    http_response_code(404);
    exit;
}

$headers = ['Expect:']; // no 100-continue round trip
$forward = [
    'CONTENT_TYPE' => 'Content-Type',
    'HTTP_USER_AGENT' => 'User-Agent',
    'HTTP_ORIGIN' => 'Origin',
    'HTTP_SEC_GPC' => 'Sec-GPC',
    'HTTP_DNT' => 'DNT',
];
foreach ($forward as $key => $name) {
    if (!empty($_SERVER[$key])) {
        $headers[] = $name . ': ' . $_SERVER[$key];
    }
}
// The visitor. Behind Cloudflare, use $_SERVER['HTTP_CF_CONNECTING_IP'].
$headers[] = 'X-Behavly-Client-IP: ' . $_SERVER['REMOTE_ADDR'];

$query = $_GET;
unset($query['bv_path']);
$returned = [];
$ch = curl_init($behavly . $path . ($query ? '?' . http_build_query($query) : ''));
curl_setopt_array($ch, [
    CURLOPT_CUSTOMREQUEST => $method,
    CURLOPT_HTTPHEADER => $headers,
    CURLOPT_RETURNTRANSFER => true,
    CURLOPT_ENCODING => '',
    CURLOPT_TIMEOUT => 10,
    CURLOPT_HEADERFUNCTION => function ($ch, $line) use (&$returned) {
        if (preg_match('/^(content-type|cache-control|x-behavly-client-ip-status):/i', $line)) {
            $returned[] = trim($line);
        }
        return strlen($line);
    },
]);
if ($method === 'POST') {
    curl_setopt($ch, CURLOPT_POSTFIELDS, file_get_contents('php://input'));
}
$body = curl_exec($ch);
if ($body === false) {
    http_response_code(502);
    exit;
}
http_response_code(curl_getinfo($ch, CURLINFO_RESPONSE_CODE));
foreach ($returned as $line) {
    header($line);
}
echo $body;
```

##### Apache

```apache
# .htaccess, next to bv.php
RewriteEngine On
RewriteRule ^bv/(.*)$ bv.php?bv_path=$1 [QSA,L]
```

##### Nginx With PHP-FPM

```nginx
# Inside your site's server { } block, with PHP-FPM already set up
location /bv/ {
    rewrite ^/bv/(.*)$ /bv.php?bv_path=$1 last;
}
```

`REMOTE_ADDR` is the visitor unless a load balancer or CDN sits in front of PHP. Behind Cloudflare, use `HTTP_CF_CONNECTING_IP`; behind your own load balancer, the first entry of `HTTP_X_FORWARDED_FOR`.

#### Nginx

No code: Nginx forwards the requests itself.

```nginx
# Inside your site's server { } block
location /bv/ {
    proxy_http_version 1.1;
    proxy_ssl_server_name on;
    proxy_set_header Host behavly.io;
    proxy_set_header X-Behavly-Client-IP $remote_addr;
    proxy_set_header Cookie "";
    proxy_set_header Authorization "";

    location = /bv/t.js          { proxy_pass https://behavly.io/t.js; }
    location = /bv/bv-overlay.js { proxy_pass https://behavly.io/bv-overlay.js; }
    location /bv/api/track/      { proxy_pass https://behavly.io/api/track/; }

    return 404;
}
```

- Keep `proxy_ssl_server_name on`. Without it Nginx connects to Behavly without naming the site it wants, and gets an error back.
- Test with `sudo nginx -t`, then load it with `sudo systemctl reload nginx`.
- `$remote_addr` is the visitor unless something sits in front of Nginx. If something does, tell Nginx which addresses to trust:

```nginx
# Behind a load balancer or Cloudflare: make $remote_addr the visitor
set_real_ip_from 10.0.0.0/8;          # your load balancer's addresses
real_ip_header   X-Forwarded-For;     # CF-Connecting-IP behind Cloudflare
```

#### Caddy

```caddy
example.com {
	handle_path /bv/* {
		@other not path /t.js /bv-overlay.js /api/track/*
		respond @other 404

		reverse_proxy https://behavly.io {
			header_up Host behavly.io
			header_up X-Behavly-Client-IP {client_ip}
			header_up -Cookie
			header_up -Authorization
		}
	}

	# ... the rest of your site
}
```

`{client_ip}` needs Caddy 2.7 or later. It is the visitor's address once the `trusted_proxies` server option lists any load balancer in front of Caddy; on older versions use `{remote_host}`. Check with `caddy validate`, then `caddy reload`.

#### Laravel

```php
<?php
// routes/web.php
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Http;
use Illuminate\Support\Facades\Route;

Route::match(['GET', 'POST'], '/bv/{path}', function (Request $request, string $path) {
    $pending = Http::withHeaders(array_filter([
        'User-Agent' => $request->userAgent(),
        'Origin' => $request->header('Origin'),
        'Sec-GPC' => $request->header('Sec-GPC'),
        'DNT' => $request->header('DNT'),
        // The visitor, once TrustProxies matches your setup (see below).
        'X-Behavly-Client-IP' => $request->ip(),
    ]))->timeout(10);

    if ($request->isMethod('POST')) {
        $pending = $pending->withBody($request->getContent(), $request->header('Content-Type', 'text/plain'));
    }

    $upstream = $pending->send($request->method(), 'https://behavly.io/' . $path, [
        'query' => $request->query(),
    ]);

    return response($upstream->body(), $upstream->status())->withHeaders(array_filter([
        'Content-Type' => $upstream->header('Content-Type'),
        'Cache-Control' => $upstream->header('Cache-Control'),
        'X-Behavly-Client-IP-Status' => $upstream->header('X-Behavly-Client-IP-Status'),
    ]));
})->where('path', 't\.js|bv-overlay\.js|api/track/[\w-]+');
```

Laravel checks a CSRF token on every `POST` to a web route and the snippet has none, so leave the path out. In Laravel 11 and later that is in `bootstrap/app.php`:

```php
<?php
// bootstrap/app.php (Laravel 11 and later): the two middleware lines
use Illuminate\Foundation\Application;
use Illuminate\Foundation\Configuration\Exceptions;
use Illuminate\Foundation\Configuration\Middleware;

return Application::configure(basePath: dirname(__DIR__))
    ->withRouting(
        web: __DIR__.'/../routes/web.php',
        commands: __DIR__.'/../routes/console.php',
        health: '/up',
    )
    ->withMiddleware(function (Middleware $middleware) {
        // The snippet posts without a CSRF token.
        $middleware->validateCsrfTokens(except: ['bv/*']);
        // Only with a load balancer in front, so $request->ip() is the visitor:
        // $middleware->trustProxies(at: '10.0.0.0/8');
    })
    ->withExceptions(function (Exceptions $exceptions) {
        //
    })->create();
```

In Laravel 10, add `'bv/*'` to `$except` in `app/Http/Middleware/VerifyCsrfToken.php`. `$request->ip()` is the visitor once the trusted proxies list your load balancer; without one in front, leave them as they are.

#### Flask

```python
# Forwards /bv/* to Behavly with the visitor's IP address.
# pip install flask requests
import re

import requests
from flask import Flask, Response, abort, request

app = Flask(__name__)

BEHAVLY = "https://behavly.io"
ALLOWED = re.compile(r"t\.js|bv-overlay\.js|api/track/[\w-]+")
FORWARD = ("Content-Type", "User-Agent", "Origin", "Sec-GPC", "DNT")
RETURN = ("Content-Type", "Cache-Control", "X-Behavly-Client-IP-Status")


@app.route("/bv/<path:path>", methods=["GET", "POST"])
def behavly_proxy(path):
    if not ALLOWED.fullmatch(path):
        abort(404)
    headers = {name: request.headers[name] for name in FORWARD if name in request.headers}
    # The visitor. Behind a load balancer, wrap the app in ProxyFix (see below).
    if request.remote_addr:
        headers["X-Behavly-Client-IP"] = request.remote_addr
    try:
        upstream = requests.request(
            request.method,
            f"{BEHAVLY}/{path}",
            params=request.args,
            data=request.get_data() or None,
            headers=headers,
            timeout=10,
        )
    except requests.RequestException:
        abort(502)
    return Response(
        upstream.content,
        status=upstream.status_code,
        headers={name: upstream.headers[name] for name in RETURN if name in upstream.headers},
    )
```

```python
# Behind one load balancer or proxy: make request.remote_addr the visitor
from werkzeug.middleware.proxy_fix import ProxyFix

app.wsgi_app = ProxyFix(app.wsgi_app, x_for=1)
```

#### FastAPI

```python
# Forwards /bv/* to Behavly with the visitor's IP address.
# pip install fastapi httpx
import re

import httpx
from fastapi import FastAPI, Request, Response

app = FastAPI()

BEHAVLY = "https://behavly.io"
ALLOWED = re.compile(r"t\.js|bv-overlay\.js|api/track/[\w-]+")
FORWARD = ("content-type", "user-agent", "origin", "sec-gpc", "dnt")
RETURN = ("content-type", "cache-control", "x-behavly-client-ip-status")
client = httpx.AsyncClient(base_url=BEHAVLY, timeout=10)


@app.api_route("/bv/{path:path}", methods=["GET", "POST"], include_in_schema=False)
async def behavly_proxy(path: str, request: Request) -> Response:
    if not ALLOWED.fullmatch(path):
        return Response(status_code=404)
    headers = {name: request.headers[name] for name in FORWARD if name in request.headers}
    # The visitor. Behind a load balancer, start Uvicorn with --proxy-headers.
    if request.client:
        headers["x-behavly-client-ip"] = request.client.host
    try:
        upstream = await client.request(
            request.method,
            f"/{path}",
            params=request.query_params,
            content=await request.body(),
            headers=headers,
        )
    except httpx.HTTPError:
        return Response(status_code=502)
    return Response(
        upstream.content,
        status_code=upstream.status_code,
        headers={name: upstream.headers[name] for name in RETURN if name in upstream.headers},
    )
```

Behind a load balancer, start Uvicorn with `--proxy-headers` and `--forwarded-allow-ips` set to the balancer's address, so `request.client.host` is the visitor.

#### Cloudflare Workers

Create a Worker with this code, then add the route `example.com/bv/*`, with your own domain, in the Worker's settings under **Domains & Routes**.

```js
// A Worker on the route example.com/bv/*: forwards to Behavly with the
// visitor's IP address.
const BEHAVLY = "https://behavly.io";
const ALLOWED = /^\/bv\/(t\.js|bv-overlay\.js|api\/track\/[\w-]+)$/;
const FORWARD = ["content-type", "user-agent", "origin", "sec-gpc", "dnt"];
const RETURN = ["content-type", "cache-control", "x-behavly-client-ip-status"];

export default {
  async fetch(request) {
    const url = new URL(request.url);
    const match = ALLOWED.exec(url.pathname);
    if (!match) return new Response("Not found", { status: 404 });

    const headers = new Headers();
    for (const name of FORWARD) {
      const value = request.headers.get(name);
      if (value) headers.set(name, value);
    }
    // Cloudflare sets CF-Connecting-IP to the visitor, so it can't be faked.
    const ip = request.headers.get("cf-connecting-ip");
    if (ip) headers.set("x-behavly-client-ip", ip);

    const upstream = await fetch(BEHAVLY + "/" + match[1] + url.search, {
      method: request.method,
      headers,
      body: request.method === "GET" ? null : await request.arrayBuffer(),
    });

    const out = new Headers();
    for (const name of RETURN) {
      const value = upstream.headers.get(name);
      if (value) out.set(name, value);
    }
    return new Response(upstream.body, { status: upstream.status, headers: out });
  },
};
```

#### Netlify

Use an Edge Function. A proxy redirect in `netlify.toml` can send a header, but only one with a fixed value, never the visitor's address.

Where: `netlify/edge-functions/behavly.ts`. It serves `/bv/*` once deployed; `netlify.toml` needs no change.

```ts
// netlify/edge-functions/behavly.ts: forwards /bv/* to Behavly with the
// visitor's IP address.
import type { Config, Context } from "@netlify/edge-functions";

const BEHAVLY = "https://behavly.io";
const ALLOWED = /^\/bv\/(t\.js|bv-overlay\.js|api\/track\/[\w-]+)$/;
const FORWARD = ["content-type", "user-agent", "origin", "sec-gpc", "dnt"];
const RETURN = ["content-type", "cache-control", "x-behavly-client-ip-status"];

export default async (request: Request, context: Context) => {
  const url = new URL(request.url);
  const match = ALLOWED.exec(url.pathname);
  if (!match) return new Response("Not found", { status: 404 });

  const headers = new Headers();
  for (const name of FORWARD) {
    const value = request.headers.get(name);
    if (value) headers.set(name, value);
  }
  // Netlify gives the visitor's address as context.ip.
  if (context.ip) headers.set("x-behavly-client-ip", context.ip);

  const upstream = await fetch(BEHAVLY + "/" + match[1] + url.search, {
    method: request.method,
    headers,
    body: request.method === "GET" ? null : await request.arrayBuffer(),
  });

  const out = new Headers();
  for (const name of RETURN) {
    const value = upstream.headers.get(name);
    if (value) out.set(name, value);
  }
  return new Response(upstream.body, { status: upstream.status, headers: out });
};

export const config: Config = { path: "/bv/*" };
```

#### Check It Works

1. Deploy, open your live site, and open the browser's developer tools on the **Network** tab.
2. Check that the snippet loads from `/bv/t.js` on your own domain.
3. Find a request to `ingest`, which the snippet sends a few seconds after a page view and when you leave the page, and look at its response headers for `X-Behavly-Client-IP-Status`.

| X-Behavly-Client-IP-Status | What it means |
| --- | --- |
| `used` | The address arrived and is a public one. Locations come from it. |
| `ignored: not a public IP address` | Your proxy passed on a private or reserved address, usually a load balancer's or your own network's rather than the visitor's. See the notes for your platform. |
| `ignored: not an IP address` | The header holds something other than an address. Check what your proxy puts in it. |
| Missing | The header did not arrive, or your proxy does not return Behavly's headers. Visits will show your server's location. |

> Note: Testing on your own computer against a local server sends a local address, which is always ignored. Check on your live site.

Locations for visits through your own proxy come from [IP Geolocation by DB-IP](https://db-ip.com), used under the [CC BY 4.0](https://creativecommons.org/licenses/by/4.0/) licence.

See also: https://behavly.io/help-center/user-activity/proxy-through-your-subdomain, https://behavly.io/help-center/user-activity/install-the-snippet, https://behavly.io/help-center/privacy/what-the-snippet-collects
