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!

feature: configurable proxy header variable (#458)

Long Le8e9bac94e202
diff --git a/backend/.env.example b/backend/.env.example
index d5f6c9fb3..099aaadb2 100644
--- a/backend/.env.example
+++ b/backend/.env.example
@@ -78,8 +78,9 @@ PADDLE_API_KEY=
SENTRY_ENABLED=false
SENTRY_DSN=''
-# Cloudflare Proxy
-CLOUDFLARE_PROXY_ENABLED=false
+# What header should be used to get IP address (e.g. cf-connecting-ip, x-real-ip, etc.)
+# Default: x-forwarded-for
+CLIENT_IP_HEADER=cf-connecting-ip
# Load balancing
IS_PRIMARY_NODE=true
diff --git a/backend/apps/cloud/src/analytics/heartbeat.gateway.ts b/backend/apps/cloud/src/analytics/heartbeat.gateway.ts
index 8e5f8ecbb..97674a250 100644
--- a/backend/apps/cloud/src/analytics/heartbeat.gateway.ts
+++ b/backend/apps/cloud/src/analytics/heartbeat.gateway.ts
@@ -9,7 +9,7 @@ import _split from 'lodash/split'
import { AnalyticsService } from './analytics.service'
import { AppLoggerService } from '../logger/logger.service'
-import { isProxiedByCloudflare } from '../common/constants'
+import { getIPFromHeaders } from '../common/utils'
// Heartbeat interval: update session every 60 seconds
const HEARTBEAT_INTERVAL_MS = 60_000
@@ -179,18 +179,12 @@ export class HeartbeatGateway
private getIPFromSocket(client: Socket): string {
const headers = client.handshake.headers
- if (isProxiedByCloudflare && headers['cf-connecting-ip']) {
- const cfIP = headers['cf-connecting-ip']
- return Array.isArray(cfIP) ? cfIP[0] : cfIP
- }
-
- const ip = headers['x-forwarded-for'] || null
+ const ip = getIPFromHeaders(headers)
if (!ip) {
return client.handshake.address || ''
}
- const ipStr = Array.isArray(ip) ? ip[0] : ip
- return _split(ipStr, ',')[0]
+ return ip
}
}
diff --git a/backend/apps/cloud/src/common/constants.ts b/backend/apps/cloud/src/common/constants.ts
index 045c4ff22..4cc0146b9 100644
--- a/backend/apps/cloud/src/common/constants.ts
+++ b/backend/apps/cloud/src/common/constants.ts
@@ -26,7 +26,6 @@ const {
JWT_ACCESS_TOKEN_LIFETIME = 60 * 30,
} = process.env
const isDevelopment = process.env.NODE_ENV === 'development'
-const isProxiedByCloudflare = process.env.CLOUDFLARE_PROXY_ENABLED === 'true'
const PRODUCTION_ORIGIN = process.env.CLIENT_URL || 'https://swetrix.com'
const { TWO_FACTOR_AUTHENTICATION_APP_NAME } = process.env
@@ -203,7 +202,6 @@ export {
ERROR_COLUMNS,
PERFORMANCE_COLUMNS,
sentryIgnoreErrors,
- isProxiedByCloudflare,
BLOG_POSTS_PATH,
MIN_PAGES_IN_FUNNEL,
MAX_PAGES_IN_FUNNEL,
diff --git a/backend/apps/cloud/src/common/utils.ts b/backend/apps/cloud/src/common/utils.ts
index 7e18b42c3..024bac7d7 100644
--- a/backend/apps/cloud/src/common/utils.ts
+++ b/backend/apps/cloud/src/common/utils.ts
@@ -14,7 +14,7 @@ import _size from 'lodash/size'
import _round from 'lodash/round'
import _split from 'lodash/split'
-import { redis, isDevelopment, isProxiedByCloudflare } from './constants'
+import { redis, isDevelopment } from './constants'
/*
Returns a 32-character hash of the provided string using Node.js crypto module.
@@ -313,49 +313,52 @@ export const getGeoDetails = (ip: string, tz?: string): IPGeoDetails => {
}
}
-export const getIPFromHeaders = (
- headers: any,
- tryXClientIPAddress?: boolean,
-) => {
- const normalise = (raw: unknown): string | null => {
- if (!raw) return null
- const str = String(raw)
- const first = str.split(',')[0]?.trim()
- if (!first) return null
+const normalise = (raw: unknown): string | null => {
+ if (!raw) return null
+ const str = String(raw)
+ const first = str.split(',')[0]?.trim()
+ if (!first) return null
- // Handle bracketed IPv6 like: [::1]:1234
- const unbracketed = first.replace(/^\[([^\]]+)\](?::\d+)?$/, '$1')
+ // Handle bracketed IPv6 like: [::1]:1234
+ const unbracketed = first.replace(/^\[([^\]]+)\](?::\d+)?$/, '$1')
- if (net.isIP(unbracketed)) return unbracketed
+ if (net.isIP(unbracketed)) return unbracketed
- // Handle IPv4 with port like: 203.0.113.1:1234
- const ipv4PortMatch = unbracketed.match(/^(\d{1,3}(?:\.\d{1,3}){3}):\d+$/)
- if (ipv4PortMatch?.[1] && net.isIP(ipv4PortMatch[1])) {
- return ipv4PortMatch[1]
- }
-
- return null
+ // Handle IPv4 with port like: 203.0.113.1:1234
+ const ipv4PortMatch = unbracketed.match(/^(\d{1,3}(?:\.\d{1,3}){3}):\d+$/)
+ if (ipv4PortMatch?.[1] && net.isIP(ipv4PortMatch[1])) {
+ return ipv4PortMatch[1]
}
- if (tryXClientIPAddress) {
- const ip = normalise(headers?.['x-client-ip-address'])
- if (ip) return ip
+ return null
+}
+
+const getHeader = (headers: any, name: string): string | null | undefined => {
+ if (typeof headers?.get === 'function') {
+ return headers.get(name)
}
+ return headers?.[name] ?? headers?.[name.toLowerCase()]
+}
- if (isProxiedByCloudflare) {
- const ip = normalise(headers?.['cf-connecting-ip'])
+export const getIPFromHeaders = (
+ headers: any,
+ tryXClientIPAddress?: boolean,
+) => {
+ if (tryXClientIPAddress) {
+ const ip = normalise(getHeader(headers, 'x-client-ip-address'))
if (ip) return ip
}
- // Get IP based on the NGINX configuration
- // No need to do this if API is behind a load balancer
- // let ip = headers['x-real-ip']
+ const customHeader = process.env.CLIENT_IP_HEADER
- // if (ip) {
- // return ip
- // }
+ if (customHeader) {
+ const headerValue = getHeader(headers, customHeader)
+ if (headerValue) {
+ return normalise(headerValue)
+ }
+ }
- return normalise(headers?.['x-forwarded-for'])
+ return normalise(getHeader(headers, 'x-forwarded-for'))
}
export const sumArrays = (source: number[], target: number[]) => {
diff --git a/backend/apps/community/src/analytics/heartbeat.gateway.ts b/backend/apps/community/src/analytics/heartbeat.gateway.ts
index 775e67876..a39d2a9b5 100644
--- a/backend/apps/community/src/analytics/heartbeat.gateway.ts
+++ b/backend/apps/community/src/analytics/heartbeat.gateway.ts
@@ -9,7 +9,7 @@ import _split from 'lodash/split'
import { AnalyticsService } from './analytics.service'
import { AppLoggerService } from '../logger/logger.service'
-import { isProxiedByCloudflare } from '../common/constants'
+import { getIPFromHeaders } from '../common/utils'
// Heartbeat interval: update session every 60 seconds
const HEARTBEAT_INTERVAL_MS = 60_000
@@ -179,25 +179,12 @@ export class HeartbeatGateway
private getIPFromSocket(client: Socket): string {
const headers = client.handshake.headers
- if (isProxiedByCloudflare && headers['cf-connecting-ip']) {
- const cfIP = headers['cf-connecting-ip']
- return Array.isArray(cfIP) ? cfIP[0] : cfIP
- }
-
- // Get IP based on the NGINX configuration
- let ip = headers['x-real-ip']
-
- if (ip) {
- return Array.isArray(ip) ? ip[0] : ip
- }
-
- ip = headers['x-forwarded-for'] || null
+ const ip = getIPFromHeaders(headers)
if (!ip) {
return client.handshake.address || ''
}
- const ipStr = Array.isArray(ip) ? ip[0] : ip
- return _split(ipStr, ',')[0]
+ return ip
}
}
diff --git a/backend/apps/community/src/common/constants.ts b/backend/apps/community/src/common/constants.ts
index 6bd927ff2..e1f4ed70c 100644
--- a/backend/apps/community/src/common/constants.ts
+++ b/backend/apps/community/src/common/constants.ts
@@ -41,7 +41,6 @@ const {
// 30 minutes
JWT_ACCESS_TOKEN_LIFETIME = 60 * 30,
} = process.env
-const isProxiedByCloudflare = process.env.CLOUDFLARE_PROXY_ENABLED === 'true'
const isDevelopment = process.env.NODE_ENV === 'development'
export const IS_REGISTRATION_DISABLED =
@@ -133,7 +132,6 @@ export {
NUMBER_JWT_ACCESS_TOKEN_LIFETIME as JWT_ACCESS_TOKEN_LIFETIME,
TRAFFIC_COLUMNS,
PERFORMANCE_COLUMNS,
- isProxiedByCloudflare,
MIN_PAGES_IN_FUNNEL,
MAX_PAGES_IN_FUNNEL,
ERROR_COLUMNS,
diff --git a/backend/apps/community/src/common/utils.ts b/backend/apps/community/src/common/utils.ts
index 31d376416..386f8c723 100644
--- a/backend/apps/community/src/common/utils.ts
+++ b/backend/apps/community/src/common/utils.ts
@@ -2,6 +2,7 @@ import { NotFoundException, HttpException } from '@nestjs/common'
import path from 'path'
import fs from 'fs'
import crypto from 'crypto'
+import net from 'net'
import randomstring from 'randomstring'
import { CityResponse, Reader } from 'maxmind'
import timezones from 'countries-and-timezones'
@@ -21,12 +22,7 @@ import dayjs from 'dayjs'
import utc from 'dayjs/plugin/utc'
import _map from 'lodash/map'
-import {
- redis,
- isDevelopment,
- isProxiedByCloudflare,
- SELFHOSTED_GEOIP_DB_PATH,
-} from './constants'
+import { redis, isDevelopment, SELFHOSTED_GEOIP_DB_PATH } from './constants'
import { clickhouse } from './integrations/clickhouse'
import { BotsProtectionLevel, Project } from '../project/entity/project.entity'
import { ProjectViewEntity } from '../project/entity/project-view.entity'
@@ -1157,25 +1153,44 @@ const getGeoDetails = (ip: string, tz?: string): IPGeoDetails => {
}
}
-const getIPFromHeaders = (headers: any) => {
- if (isProxiedByCloudflare && headers['cf-connecting-ip']) {
- return headers['cf-connecting-ip']
+const normalise = (raw: unknown): string | null => {
+ if (!raw) return null
+ const str = String(raw)
+ const first = str.split(',')[0]?.trim()
+ if (!first) return null
+
+ // Handle bracketed IPv6 like: [::1]:1234
+ const unbracketed = first.replace(/^\[([^\]]+)\](?::\d+)?$/, '$1')
+
+ if (net.isIP(unbracketed)) return unbracketed
+
+ // Handle IPv4 with port like: 203.0.113.1:1234
+ const ipv4PortMatch = unbracketed.match(/^(\d{1,3}(?:\.\d{1,3}){3}):\d+$/)
+ if (ipv4PortMatch?.[1] && net.isIP(ipv4PortMatch[1])) {
+ return ipv4PortMatch[1]
}
- // Get IP based on the NGINX configuration
- let ip = headers['x-real-ip']
+ return null
+}
- if (ip) {
- return ip
+const getHeader = (headers: any, name: string): string | null | undefined => {
+ if (typeof headers?.get === 'function') {
+ return headers.get(name)
}
+ return headers?.[name] ?? headers?.[name.toLowerCase()]
+}
- ip = headers['x-forwarded-for'] || null
+const getIPFromHeaders = (headers: any) => {
+ const customHeader = process.env.CLIENT_IP_HEADER
- if (!ip) {
- return null
+ if (customHeader) {
+ const headerValue = getHeader(headers, customHeader)
+ if (headerValue) {
+ return normalise(headerValue)
+ }
}
- return _split(ip, ',')[0]
+ return normalise(getHeader(headers, 'x-forwarded-for'))
}
const sumArrays = (source: number[], target: number[]) => {
diff --git a/docs/docs/selfhosting/configuring.md b/docs/docs/selfhosting/configuring.md
index 48a6532f0..59312168b 100644
--- a/docs/docs/selfhosting/configuring.md
+++ b/docs/docs/selfhosting/configuring.md
@@ -34,7 +34,7 @@ The `API_URL` must be publicly reachable from your users' browsers. Do not set i
| Variable | Default | Description |
| -------------------------- | ---------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ |
| `SECRET_KEY_BASE` | _auto-generated by `configure.sh`_ | Secret used for auth keys and login sessions. Must be set. |
-| `CLOUDFLARE_PROXY_ENABLED` | `false` | If set to `true` - Swetrix will get IP address information from `cf-connecting-ip` header provided by Cloudflare. |
+| `CLIENT_IP_HEADER` | `null` | Defines what header should be used to get IP address (e.g. cf-connecting-ip, x-real-ip, etc.). If not set, Swetrix will use `x-forwarded-for` header. |
| `DISABLE_REGISTRATION` | `true` | When set to `true` - Swetrix will disable user registration, except for the initial user. |
| `IP_GEOLOCATION_DB_PATH` | `` | Path to the `.mmdb` file for IP geolocation database. By default Swetrix uses IP to City Lite database by DB-IP. |
| `IS_PRIMARY_NODE` | `true` | You should not touch this variable unless you know what you are doing. It's used to spin off multiple API instances in a cluster, where only one of them will be primary. If changed to `false`, things like cron task manager will be disabled for this instance. |
diff --git a/docs/docs/selfhosting/how-to.md b/docs/docs/selfhosting/how-to.md
index e009cde3d..b9ae725ab 100644
--- a/docs/docs/selfhosting/how-to.md
+++ b/docs/docs/selfhosting/how-to.md
@@ -74,7 +74,7 @@ To update Swetrix to the latest version, please refer to the changelog on our [G
If you use reverse proxy like Nginx, please set it up to pass the request IP address as the `x-real-ip` header, otherwise it may cause the problems related to API route rate limiting and analytics sessions. If the `x-real-ip` header is undefined, Swetrix will use `x-forwarded-for` or the request IP address as a backup.
-If you are using Cloudflare as a proxy for your self-hosted Swetrix instance, you can set the `CLOUDFLARE_PROXY_ENABLED` environment variable to `true`. This will force Swetrix to check the `cf-connecting-ip` header for the IP address.
+If you are using proxy for your self-hosted Swetrix instance, you should set the `CLIENT_IP_HEADER` environment variable. For example, if your proxy is Cloudflare, then you should set `CLIENT_IP_HEADER` to `cf-connecting-ip`.
:::caution
If you use Cloudflare Tunnel, avoid nested subdomains such as `api.swetrix.example.com` which may not be supported in some Tunnel setups. Prefer a single-label subdomain like `swetrixapi.example.com`, and set `API_URL` to that public URL.