Skip to content

πŸ“ˆ Open source, privacy-first web analytics β€” a cookie-less Google Analytics alternative with built-in error tracking and performance monitoring. Self-host it or use our cloud. Get started for free!

Use X-Forwarded-For in favour of X-Client-IP-Address

Blue Mouse766fb08780a5
diff --git a/backend/apps/cloud/src/common/utils.ts b/backend/apps/cloud/src/common/utils.ts
index 2da201d66..fd199ab84 100644
--- a/backend/apps/cloud/src/common/utils.ts
+++ b/backend/apps/cloud/src/common/utils.ts
@@ -425,6 +425,8 @@ export const TRUSTED_PROXY_IPS: ReadonlySet<string> = new Set(
)
export const getIPFromHeaders = (headers: unknown) => {
+ // Legacy header; must keep precedence over X-Forwarded-For so pre-2026
+ // server-side tracking setups keep working.
const customHeader = process.env.CLIENT_IP_HEADER
if (customHeader) {
@@ -434,23 +436,20 @@ export const getIPFromHeaders = (headers: unknown) => {
}
}
+ const forwardedFor = String(getHeader(headers, 'x-forwarded-for') ?? '')
const realIp = normalise(getHeader(headers, 'x-real-ip'))
- // Without X-Real-IP nothing identifies the connection peer, so
- // X-Forwarded-For is entirely client-supplied and cannot be trusted.
- // Callers fall back to the socket address instead.
if (!realIp) {
- return null
+ return normalise(forwardedFor)
}
if (!TRUSTED_PROXY_IPS.has(realIp)) {
- return realIp
+ return normalise(forwardedFor) ?? realIp
}
// The connection is one of our own relays. Recover the visitor from
// X-Forwarded-For, walking from the right past our own hops so a
// client-supplied prefix never wins.
- const forwardedFor = String(getHeader(headers, 'x-forwarded-for') ?? '')
const hops = forwardedFor.split(',')
for (let i = hops.length - 1; i >= 0; --i) {
diff --git a/docs/content/docs/adblockers/guides/netlify.mdx b/docs/content/docs/adblockers/guides/netlify.mdx
index e9930223d..4d2682b6b 100644
--- a/docs/content/docs/adblockers/guides/netlify.mdx
+++ b/docs/content/docs/adblockers/guides/netlify.mdx
@@ -5,6 +5,12 @@ slug: /adblockers/guides/netlify
You can use [Netlify redirects](https://docs.netlify.com/routing/redirects/) to proxy Swetrix analytics traffic via your domain.
+<Callout type="info">
+ Swetrix reads the visitor's IP address from the `X-Forwarded-For` header, which Netlify sets
+ automatically when proxying requests β€” so geolocation, unique visitor counting and [bot
+ protection](/bot-protection) keep working as normal.
+</Callout>
+
## Setup Netlify rewrites rules
First, you need to add the following rules to the `_redirects` file. If you don't already have it, you will need to [create it](https://docs.netlify.com/routing/redirects/rewrites-proxies/) first.
diff --git a/docs/content/docs/adblockers/guides/nextjs.mdx b/docs/content/docs/adblockers/guides/nextjs.mdx
index 23a23b004..2679f87f7 100644
--- a/docs/content/docs/adblockers/guides/nextjs.mdx
+++ b/docs/content/docs/adblockers/guides/nextjs.mdx
@@ -5,6 +5,14 @@ slug: /adblockers/guides/nextjs
You can use [Next.js](https://nextjs.org/) to proxy Swetrix analytics traffic via your domain.
+<Callout type="info">
+ Swetrix reads the visitor's IP address from the `X-Forwarded-For` header, which Vercel and other
+ Next.js hosting platforms set automatically when proxying requests β€” so geolocation, unique
+ visitor counting and [bot protection](/bot-protection) keep working as normal. If you self-host
+ Next.js behind your own web server, make sure it forwards `X-Forwarded-For` (see the [Nginx
+ guide](/adblockers/guides/nginx)).
+</Callout>
+
## Setup Next.js rewrites rules
First, you need to add the following rules to the `next.config.js` file. If you don't already have it, you will need to [create it](https://nextjs.org/docs/pages/api-reference/next-config-js/rewrites) in your project's root directory first.
diff --git a/docs/content/docs/adblockers/guides/nginx.mdx b/docs/content/docs/adblockers/guides/nginx.mdx
index a13ac2bd0..b1041b781 100644
--- a/docs/content/docs/adblockers/guides/nginx.mdx
+++ b/docs/content/docs/adblockers/guides/nginx.mdx
@@ -5,6 +5,14 @@ slug: /adblockers/guides/nginx
If you are already using Nginx on your website, you can add Swetrix to your configuration to proxy it.
+<Callout type="warn">
+ The `proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;` line in the configuration below
+ is **essential β€” do not remove it**. It forwards your visitor's real IP address to Swetrix.
+ Without it, all events arrive from your server's datacenter IP: geolocation data will show your
+ server's location instead of your visitors', and if your project's [bot protection
+ level](/bot-protection) is set to **Strict**, your traffic will be dropped as datacenter traffic.
+</Callout>
+
## Update your Nginx configuration
```
@@ -41,9 +49,9 @@ server {
}
location /log {
- proxy_set_header Host $swetrix_api_host;
- proxy_set_header X-Client-IP-Address $proxy_add_x_forwarded_for;
- proxy_set_header X-Forwarded-Proto $scheme;
+ proxy_set_header Host $swetrix_api_host;
+ proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
+ proxy_set_header X-Forwarded-Proto $scheme;
proxy_ssl_server_name on;
proxy_buffering on;
diff --git a/docs/content/docs/adblockers/how-to-deal-with-adblockers.mdx b/docs/content/docs/adblockers/how-to-deal-with-adblockers.mdx
index 81a58adb2..73537440d 100644
--- a/docs/content/docs/adblockers/how-to-deal-with-adblockers.mdx
+++ b/docs/content/docs/adblockers/how-to-deal-with-adblockers.mdx
@@ -19,13 +19,14 @@ The advantage of this approach is that your site will only make first-party requ
You have two options, summarised below. Pick the one that matches how much DevOps work you're willing to do:
-| | Managed reverse proxy | Self-hosted proxy |
-| -------------------------------- | ------------------------------------------------------------------ | ----------------------------------------------------------------------------------------- |
-| **Setup effort** | A few minutes β€” add a CNAME record in your DNS, paste a snippet | Configure your own web server (Nginx, Netlify, Next.js, etc.) |
-| **Technical knowledge required** | Minimal | Moderate to high |
-| **SSL certificate** | Provisioned automatically by Swetrix | You provide it (or your platform does) |
-| **How it looks to ad blockers** | A request to a subdomain of your site to a Swetrix-controlled edge | A request to your own server, fully indistinguishable from any other request to your site |
-| **Detectability** | Low | **Lowest** β€” the most effective option |
+| | Managed reverse proxy | Self-hosted proxy |
+| -------------------------------- | ------------------------------------------------------------------ | ------------------------------------------------------------------------------------------------------------------------------------- |
+| **Setup effort** | A few minutes β€” add a CNAME record in your DNS, paste a snippet | Configure your own web server (Nginx, Netlify, Next.js, etc.) |
+| **Technical knowledge required** | Minimal | Moderate to high |
+| **SSL certificate** | Provisioned automatically by Swetrix | You provide it (or your platform does) |
+| **How it looks to ad blockers** | A request to a subdomain of your site to a Swetrix-controlled edge | A request to your own server, fully indistinguishable from any other request to your site |
+| **Detectability** | Low | **Lowest** β€” the most effective option |
+| **Visitor IP & geolocation** | Preserved automatically | Preserved via the `X-Forwarded-For` header (set automatically by Vercel/Netlify; on your own Nginx, forward it as shown in the guide) |
### Best: Self-hosted proxy (least detectable)
@@ -37,6 +38,14 @@ The trade-off is that you have to set it up yourself. If you already run Nginx,
- [Netlify](/adblockers/guides/netlify)
- [Next.js](/adblockers/guides/nextjs)
+<Callout type="info">
+ Swetrix reads the visitor's real IP address from the `X-Forwarded-For` header. Hosting platforms
+ like Vercel and Netlify set it automatically when proxying; if you run your own web server, make
+ sure it forwards the header (the Nginx guide shows how) β€” otherwise geolocation will reflect your
+ server's location and [bot protection](/bot-protection) set to **Strict** will drop the traffic as
+ datacenter traffic.
+</Callout>
+
### Easiest: Managed reverse proxy (zero-config)
If you don't want to maintain proxy configuration yourself, Swetrix Cloud can run a reverse proxy on your behalf. You add a CNAME record on a subdomain you control, and we handle the SSL certificate and proxying automatically.
diff --git a/docs/content/docs/api/events.mdx b/docs/content/docs/api/events.mdx
index 93272b79e..3a952e165 100644
--- a/docs/content/docs/api/events.mdx
+++ b/docs/content/docs/api/events.mdx
@@ -12,7 +12,7 @@ We already provide several [integrations](/integrations) and a [script](/swetrix
### Unique visitors tracking
<Callout type="warn">
-For the unique (and live) visitor functionality to work properly, each request must have the `User-Agent` and `X-Client-IP-Address` HTTP headers set. If you don't set these headers, the API will still work, but the unique visitor count will be incorrect.
+For the unique (and live) visitor functionality to work properly, each request must have the `User-Agent` header set, and β€” when sent from a backend server or proxy β€” the `X-Forwarded-For` header with the visitor's IP address. If you don't set these headers, the API will still work, but the unique visitor count will be incorrect.
</Callout>
@@ -25,9 +25,29 @@ The API relies on the client's IP address and user agent to create a temporary s
This header is used to determine the visitor's browser, operating system and device type. It's also used to determine whether or not the visitor is a bot.
We also use this header to create a temporary session for the visitor.
-#### X-Client-IP-Address
+#### X-Forwarded-For
-This header is used to determine the visitor's IP address. You must pass the visitor's IP address using this header, otherwise the API will use the IP address of the server making the request (i.e. your server's IP address), resulting in incorrect unique and live visitor data.
+Used to explicitly set the IP address of the visitor. If not set, the remote IP of the sender is used automatically. Depending on your use-case:
+
+1. If sending the event directly from your visitor's device, this header does not need to be set.
+2. If sending the event from a backend server or a proxy, make sure to set this header to the visitor's real IP address.
+
+<Callout type="warn">
+ If you forward a server, hosting provider or CDN IP address instead of the actual visitor IP,
+ unique and live visitor counts will be incorrect and geolocation will reflect your server's
+ location. On projects with [bot protection](/bot-protection) set to **Strict**, such events are
+ dropped entirely as datacenter traffic β€” the API still responds with a success status, but the
+ event is not recorded. You can confirm drops in the **Blocked traffic** report under Project
+ settings β†’ Shields.
+</Callout>
+
+The IP address is never stored in raw form β€” it's used to calculate the temporary visitor session described above and to fill the geolocation reports (country, region, city).
+
+If the header contains a comma-separated list (as it does when the request passed through a chain of proxies), the first valid IP address from the list is used. Both IPv4 and IPv6 addresses are supported. More information about the header format can be found on [MDN](https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/X-Forwarded-For).
+
+#### X-Client-IP-Address (legacy)
+
+Older Swetrix integrations used the custom `X-Client-IP-Address` header for the same purpose. It's still honoured and takes precedence over `X-Forwarded-For`, so existing setups keep working β€” but it's not recommended for new integrations; use the standard `X-Forwarded-For` header instead.
#### Content-Type
@@ -136,7 +156,7 @@ This endpoint records pageview events.
```bash title="Request"
curl -i -X POST https://api.swetrix.com/log \
-H "User-Agent: Mozilla/5.0 (Windows NT 10.0; rv:109.0) Gecko/20100101 Firefox/116.0" \
- -H "X-Client-IP-Address: 192.0.2.1" \
+ -H "X-Forwarded-For: 192.0.2.1" \
-H "Content-Type: application/json" \
-d '{"pid":"YOUR_PROJECT_ID","lc":"en-US","pg":"/"}'
```
@@ -152,7 +172,7 @@ This endpoint records custom events.
```bash title="Request"
curl -i -X POST https://api.swetrix.com/log/custom \
-H "User-Agent: Mozilla/5.0 (Windows NT 10.0; rv:109.0) Gecko/20100101 Firefox/116.0" \
- -H "X-Client-IP-Address: 192.0.2.1" \
+ -H "X-Forwarded-For: 192.0.2.1" \
-H "Content-Type: application/json" \
-d '{"pid":"YOUR_PROJECT_ID","lc":"en-US","pg":"/"}'
```
@@ -169,7 +189,7 @@ It's recommended to send heartbeat events every 30 seconds. We also extend the s
```bash title="Request"
curl -i -X POST https://api.swetrix.com/log/hb \
-H "User-Agent: Mozilla/5.0 (Windows NT 10.0; rv:109.0) Gecko/20100101 Firefox/116.0" \
- -H "X-Client-IP-Address: 192.0.2.1" \
+ -H "X-Forwarded-For: 192.0.2.1" \
-H "Content-Type: application/json" \
-d '{"pid":"YOUR_PROJECT_ID"}'
```
@@ -225,7 +245,7 @@ This endpoint records error events. These error events are later aggregated in t
```bash title="Request"
curl -i -X POST https://api.swetrix.com/log/error \
-H "User-Agent: Mozilla/5.0 (Windows NT 10.0; rv:109.0) Gecko/20100101 Firefox/116.0" \
- -H "X-Client-IP-Address: 192.0.2.1" \
+ -H "X-Forwarded-For: 192.0.2.1" \
-H "Content-Type: application/json" \
-d '{"pid":"YOUR_PROJECT_ID","lc":"en-US","pg":"/","name":"ParseError","message":"Malformed input","lineno":12,"colno":510,"filename":"https://example.com/assets/convert.js"}'
```
@@ -312,7 +332,7 @@ fetch("https://api.swetrix.com/log", {
method: "POST",
headers: {
"User-Agent": "FORWARD_CLIENT_USER_AGENT_HERE",
- "X-Client-IP-Address": "FORWARD_CLIENT_IP_ADDRESS_HERE",
+ "X-Forwarded-For": "FORWARD_CLIENT_IP_ADDRESS_HERE",
"Content-Type": "application/json",
},
body: JSON.stringify({
@@ -352,7 +372,7 @@ func main() {
}
req.Header.Set("User-Agent", "FORWARD_CLIENT_USER_AGENT_HERE")
- req.Header.Set("X-Client-IP-Address", "FORWARD_CLIENT_IP_ADDRESS_HERE")
+ req.Header.Set("X-Forwarded-For", "FORWARD_CLIENT_IP_ADDRESS_HERE")
req.Header.Set("Content-Type", "application/json")
client := &http.Client{}
@@ -378,7 +398,7 @@ curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode([
$headers = [
'User-Agent: FORWARD_CLIENT_USER_AGENT_HERE',
- 'X-Client-IP-Address: FORWARD_CLIENT_IP_ADDRESS_HERE',
+ 'X-Forwarded-For: FORWARD_CLIENT_IP_ADDRESS_HERE',
'Content-Type: application/json',
];
diff --git a/docs/content/docs/integrations/aspnet.mdx b/docs/content/docs/integrations/aspnet.mdx
index b930a6094..a6d89b25e 100644
--- a/docs/content/docs/integrations/aspnet.mdx
+++ b/docs/content/docs/integrations/aspnet.mdx
@@ -415,7 +415,7 @@ public class SwetrixService
Content = JsonContent.Create(payload),
};
request.Headers.Add("User-Agent", userAgent);
- request.Headers.Add("X-Client-IP-Address", ip);
+ request.Headers.Add("X-Forwarded-For", ip);
await _httpClient.SendAsync(request);
}
@@ -435,7 +435,7 @@ public class SwetrixService
Content = JsonContent.Create(payload),
};
request.Headers.Add("User-Agent", userAgent);
- request.Headers.Add("X-Client-IP-Address", ip);
+ request.Headers.Add("X-Forwarded-For", ip);
await _httpClient.SendAsync(request);
}
@@ -456,7 +456,7 @@ public class SwetrixService
Content = JsonContent.Create(payload),
};
request.Headers.Add("User-Agent", userAgent);
- request.Headers.Add("X-Client-IP-Address", ip);
+ request.Headers.Add("X-Forwarded-For", ip);
await _httpClient.SendAsync(request);
}
diff --git a/docs/content/docs/integrations/fastapi.mdx b/docs/content/docs/integrations/fastapi.mdx
index 27c1f11af..076f87f71 100644
--- a/docs/content/docs/integrations/fastapi.mdx
+++ b/docs/content/docs/integrations/fastapi.mdx
@@ -73,7 +73,7 @@ class SwetrixClient:
json=payload,
headers={
"User-Agent": user_agent or "",
- "X-Client-IP-Address": ip,
+ "X-Forwarded-For": ip,
"Content-Type": "application/json",
},
)
@@ -104,7 +104,7 @@ class SwetrixClient:
json=payload,
headers={
"User-Agent": user_agent or "",
- "X-Client-IP-Address": ip,
+ "X-Forwarded-For": ip,
"Content-Type": "application/json",
},
)
@@ -141,7 +141,7 @@ class SwetrixClient:
json=payload,
headers={
"User-Agent": user_agent or "",
- "X-Client-IP-Address": ip,
+ "X-Forwarded-For": ip,
"Content-Type": "application/json",
},
)
@@ -155,7 +155,7 @@ class SwetrixClient:
json={"pid": self.project_id},
headers={
"User-Agent": user_agent or "",
- "X-Client-IP-Address": ip,
+ "X-Forwarded-For": ip,
"Content-Type": "application/json",
},
)
@@ -535,7 +535,7 @@ class SwetrixClient:
await self._client.post(
self.api_url,
json=payload,
- headers={"User-Agent": user_agent or "", "X-Client-IP-Address": ip, "Content-Type": "application/json"},
+ headers={"User-Agent": user_agent or "", "X-Forwarded-For": ip, "Content-Type": "application/json"},
)
async def track_event(self, ip: str, user_agent: str, *, ev: str, **kwargs):
@@ -545,7 +545,7 @@ class SwetrixClient:
await self._client.post(
f"{self.api_url}/custom",
json=payload,
- headers={"User-Agent": user_agent or "", "X-Client-IP-Address": ip, "Content-Type": "application/json"},
+ headers={"User-Agent": user_agent or "", "X-Forwarded-For": ip, "Content-Type": "application/json"},
)
async def track_error(self, ip: str, user_agent: str, *, name: str, **kwargs):
@@ -558,7 +558,7 @@ class SwetrixClient:
await self._client.post(
f"{self.api_url}/error",
json=payload,
- headers={"User-Agent": user_agent or "", "X-Client-IP-Address": ip, "Content-Type": "application/json"},
+ headers={"User-Agent": user_agent or "", "X-Forwarded-For": ip, "Content-Type": "application/json"},
)
async def close(self):