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!

Add country blacklist

Blue Mouse3facfe58b91d
diff --git a/backend/apps/cloud/src/analytics/analytics.controller.ts b/backend/apps/cloud/src/analytics/analytics.controller.ts
index c4ce6c9a2..435f40b26 100644
--- a/backend/apps/cloud/src/analytics/analytics.controller.ts
+++ b/backend/apps/cloud/src/analytics/analytics.controller.ts
@@ -1148,7 +1148,7 @@ export class AnalyticsController {
return BOT_RESPONSE
}
- await this.analyticsService.validate(errorDTO, origin, ip)
+ const project = await this.analyticsService.validate(errorDTO, origin, ip)
const [, psid] = await this.analyticsService.generateAndStoreSessionId(
errorDTO.pid,
@@ -1160,6 +1160,8 @@ export class AnalyticsController {
const { city, region, regionCode, country } = getGeoDetails(ip, errorDTO.tz)
+ this.analyticsService.checkCountryBlacklist(project, country)
+
const { deviceType, browserName, browserVersion, osName, osVersion } =
await this.analyticsService.getRequestInformation(headers)
@@ -1249,7 +1251,7 @@ export class AnalyticsController {
return BOT_RESPONSE
}
- await this.analyticsService.validate(eventsDTO, origin, ip)
+ const project = await this.analyticsService.validate(eventsDTO, origin, ip)
if (eventsDTO.unique) {
const [unique] = await this.analyticsService.generateAndStoreSessionId(
@@ -1270,6 +1272,8 @@ export class AnalyticsController {
eventsDTO.tz,
)
+ this.analyticsService.checkCountryBlacklist(project, country)
+
const { deviceType, browserName, browserVersion, osName, osVersion } =
await this.analyticsService.getRequestInformation(headers)
@@ -1370,7 +1374,7 @@ export class AnalyticsController {
return BOT_RESPONSE
}
- await this.analyticsService.validate(logDTO, origin, ip)
+ const project = await this.analyticsService.validate(logDTO, origin, ip)
const [unique, psid] =
await this.analyticsService.generateAndStoreSessionId(
@@ -1389,6 +1393,8 @@ export class AnalyticsController {
const { city, region, regionCode, country } = getGeoDetails(ip, logDTO.tz)
+ this.analyticsService.checkCountryBlacklist(project, country)
+
const { deviceType, browserName, browserVersion, osName, osVersion } =
await this.analyticsService.getRequestInformation(headers)
@@ -1503,7 +1509,7 @@ export class AnalyticsController {
const ip = getIPFromHeaders(headers) || reqIP || ''
- await this.analyticsService.validate(logDTO, origin, ip)
+ const project = await this.analyticsService.validate(logDTO, origin, ip)
const [, psid] = await this.analyticsService.generateAndStoreSessionId(
logDTO.pid,
@@ -1515,6 +1521,8 @@ export class AnalyticsController {
const { city, region, regionCode, country } = getGeoDetails(ip)
+ this.analyticsService.checkCountryBlacklist(project, country)
+
const { deviceType, browserName, browserVersion, osName, osVersion } =
await this.analyticsService.getRequestInformation(headers)
diff --git a/backend/apps/cloud/src/analytics/analytics.service.ts b/backend/apps/cloud/src/analytics/analytics.service.ts
index 6f7a6ddae..7ab46949a 100644
--- a/backend/apps/cloud/src/analytics/analytics.service.ts
+++ b/backend/apps/cloud/src/analytics/analytics.service.ts
@@ -430,6 +430,26 @@ export class AnalyticsService {
}
}
+ checkCountryBlacklist(project: Project, country: string | null): void {
+ if (!country) {
+ return
+ }
+
+ const countryBlacklist = _filter(
+ project.countryBlacklist,
+ Boolean,
+ ) as string[]
+
+ if (
+ !_isEmpty(countryBlacklist) &&
+ _includes(countryBlacklist, _toUpper(country))
+ ) {
+ throw new BadRequestException(
+ 'Incoming analytics is disabled for this country',
+ )
+ }
+ }
+
checkIfAccountSuspended(project: Project) {
if (project.admin?.isAccountBillingSuspended) {
throw new HttpException(
@@ -443,7 +463,7 @@ export class AnalyticsService {
logDTO: PageviewsDto | EventsDto | ErrorDto,
origin: string,
ip?: string,
- ): Promise<string | null> {
+ ): Promise<Project> {
const { pid } = logDTO
// 'tz' does not need validation as it's based on getCountryForTimezone detection
@@ -479,14 +499,14 @@ export class AnalyticsService {
this.checkOrigin(project, origin)
- return null
+ return project
}
async validateHeartbeat(
logDTO: PageviewsDto,
origin: string,
ip?: string,
- ): Promise<string | null> {
+ ): Promise<Project> {
const { pid } = logDTO
const project = await this.projectService.getRedisProject(pid)
@@ -503,7 +523,7 @@ export class AnalyticsService {
this.checkOrigin(project, origin)
- return null
+ return project
}
getDataTypeColumns(dataType: DataType): string[] {
diff --git a/backend/apps/cloud/src/project/dto/project.dto.ts b/backend/apps/cloud/src/project/dto/project.dto.ts
index 5bf5bf155..850d3f9cd 100644
--- a/backend/apps/cloud/src/project/dto/project.dto.ts
+++ b/backend/apps/cloud/src/project/dto/project.dto.ts
@@ -43,6 +43,14 @@ export class ProjectDTO {
})
ipBlacklist: string[] | null
+ @ApiProperty({
+ example: 'UA,RU,BY',
+ required: false,
+ description:
+ 'Array of blocked country codes (ISO 3166-1 alpha-2). Traffic from these countries will not be tracked.',
+ })
+ countryBlacklist: string[] | null
+
@ApiProperty({
required: false,
description:
diff --git a/backend/apps/cloud/src/project/entity/project.entity.ts b/backend/apps/cloud/src/project/entity/project.entity.ts
index fd9cbe807..58a8259f9 100644
--- a/backend/apps/cloud/src/project/entity/project.entity.ts
+++ b/backend/apps/cloud/src/project/entity/project.entity.ts
@@ -46,6 +46,10 @@ export class Project {
@Column('simple-array', { nullable: true, default: null })
ipBlacklist: string[]
+ @ApiProperty()
+ @Column('simple-array', { nullable: true, default: null })
+ countryBlacklist: string[]
+
@ApiProperty()
@Column({
default: true,
diff --git a/backend/apps/cloud/src/project/project.controller.ts b/backend/apps/cloud/src/project/project.controller.ts
index f091b2dd2..f728e38bb 100644
--- a/backend/apps/cloud/src/project/project.controller.ts
+++ b/backend/apps/cloud/src/project/project.controller.ts
@@ -1760,6 +1760,15 @@ export class ProjectController {
project.ipBlacklist = null
}
+ if (projectDTO.countryBlacklist) {
+ project.countryBlacklist = _map(
+ projectDTO.countryBlacklist,
+ _trim,
+ ) as string[]
+ } else {
+ project.countryBlacklist = null
+ }
+
if (projectDTO.botsProtectionLevel) {
project.botsProtectionLevel = projectDTO.botsProtectionLevel
}
diff --git a/backend/apps/community/src/analytics/analytics.controller.ts b/backend/apps/community/src/analytics/analytics.controller.ts
index 25343eb52..9fa1ca554 100644
--- a/backend/apps/community/src/analytics/analytics.controller.ts
+++ b/backend/apps/community/src/analytics/analytics.controller.ts
@@ -882,7 +882,7 @@ export class AnalyticsController {
return BOT_RESPONSE
}
- await this.analyticsService.validate(eventsDTO, origin, ip)
+ const project = await this.analyticsService.validate(eventsDTO, origin, ip)
if (eventsDTO.unique) {
const [unique] = await this.analyticsService.generateAndStoreSessionId(
@@ -898,14 +898,16 @@ export class AnalyticsController {
}
}
- const { deviceType, browserName, browserVersion, osName, osVersion } =
- await this.analyticsService.getRequestInformation(headers)
-
const { city, region, regionCode, country } = getGeoDetails(
ip,
eventsDTO.tz,
)
+ this.analyticsService.checkCountryBlacklist(project, country)
+
+ const { deviceType, browserName, browserVersion, osName, osVersion } =
+ await this.analyticsService.getRequestInformation(headers)
+
const [, psid] = await this.analyticsService.generateAndStoreSessionId(
eventsDTO.pid,
userAgent,
@@ -1002,7 +1004,7 @@ export class AnalyticsController {
return BOT_RESPONSE
}
- await this.analyticsService.validate(logDTO, origin, ip)
+ const project = await this.analyticsService.validate(logDTO, origin, ip)
const [unique, psid] =
await this.analyticsService.generateAndStoreSessionId(
@@ -1021,6 +1023,8 @@ export class AnalyticsController {
const { city, region, regionCode, country } = getGeoDetails(ip, logDTO.tz)
+ this.analyticsService.checkCountryBlacklist(project, country)
+
const { deviceType, browserName, browserVersion, osName, osVersion } =
await this.analyticsService.getRequestInformation(headers)
@@ -1134,7 +1138,7 @@ export class AnalyticsController {
const logDTO: PageviewsDto = { pid }
- await this.analyticsService.validate(logDTO, origin, ip)
+ const project = await this.analyticsService.validate(logDTO, origin, ip)
const [, psid] = await this.analyticsService.generateAndStoreSessionId(
logDTO.pid,
@@ -1144,11 +1148,13 @@ export class AnalyticsController {
await this.analyticsService.processInteractionSD(psid, logDTO.pid)
+ const { city, region, regionCode, country } = getGeoDetails(ip, null)
+
+ this.analyticsService.checkCountryBlacklist(project, country)
+
const { deviceType, browserName, browserVersion, osName, osVersion } =
await this.analyticsService.getRequestInformation(headers)
- const { city, region, regionCode, country } = getGeoDetails(ip, null)
-
const transformed = trafficTransformer(
psid,
logDTO.pid,
@@ -1432,7 +1438,7 @@ export class AnalyticsController {
return BOT_RESPONSE
}
- await this.analyticsService.validate(errorDTO, origin, ip)
+ const project = await this.analyticsService.validate(errorDTO, origin, ip)
const [, psid] = await this.analyticsService.generateAndStoreSessionId(
errorDTO.pid,
@@ -1444,6 +1450,8 @@ export class AnalyticsController {
const { city, region, regionCode, country } = getGeoDetails(ip, errorDTO.tz)
+ this.analyticsService.checkCountryBlacklist(project, country)
+
const { deviceType, browserName, browserVersion, osName, osVersion } =
await this.analyticsService.getRequestInformation(headers)
diff --git a/backend/apps/community/src/analytics/analytics.service.ts b/backend/apps/community/src/analytics/analytics.service.ts
index 769e682ea..d335292de 100644
--- a/backend/apps/community/src/analytics/analytics.service.ts
+++ b/backend/apps/community/src/analytics/analytics.service.ts
@@ -395,11 +395,31 @@ export class AnalyticsService {
}
}
+ checkCountryBlacklist(project: Project, country: string | null): void {
+ if (!country) {
+ return
+ }
+
+ const countryBlacklist = _filter(
+ project.countryBlacklist,
+ Boolean,
+ ) as string[]
+
+ if (
+ !_isEmpty(countryBlacklist) &&
+ _includes(countryBlacklist, _toUpper(country))
+ ) {
+ throw new BadRequestException(
+ 'Incoming analytics is disabled for this country',
+ )
+ }
+ }
+
async validate(
logDTO: PageviewsDto | EventsDto | ErrorDto,
origin: string,
ip?: string,
- ): Promise<string | null> {
+ ): Promise<Project> {
if (_isEmpty(logDTO)) {
throw new BadRequestException('The request cannot be empty')
}
@@ -437,14 +457,14 @@ export class AnalyticsService {
this.checkOrigin(project, origin)
- return null
+ return project
}
async validateHeartbeat(
logDTO: PageviewsDto,
origin: string,
ip?: string,
- ): Promise<string | null> {
+ ): Promise<Project> {
if (_isEmpty(logDTO)) {
throw new BadRequestException('The request cannot be empty')
}
@@ -463,7 +483,7 @@ export class AnalyticsService {
this.checkOrigin(project, origin)
- return null
+ return project
}
async getErrorsFilters(pid: string, type: string): Promise<Array<string>> {
diff --git a/backend/apps/community/src/project/entity/project.entity.ts b/backend/apps/community/src/project/entity/project.entity.ts
index f30d19789..6116cd3d1 100644
--- a/backend/apps/community/src/project/entity/project.entity.ts
+++ b/backend/apps/community/src/project/entity/project.entity.ts
@@ -8,6 +8,7 @@ export class Project {
name: string
origins: string[]
ipBlacklist: string[]
+ countryBlacklist: string[]
active: boolean
public: boolean
isPasswordProtected: boolean
diff --git a/web/app/lib/models/Project.ts b/web/app/lib/models/Project.ts
index 70838763a..0a0e034ae 100644
--- a/web/app/lib/models/Project.ts
+++ b/web/app/lib/models/Project.ts
@@ -133,6 +133,7 @@ export interface Project {
name: string
origins: string[] | string | null
ipBlacklist: string[] | null | string
+ countryBlacklist: string[] | null
active: boolean
public: boolean
isAnalyticsProject: boolean
diff --git a/web/app/pages/Project/Settings/ProjectSettings.tsx b/web/app/pages/Project/Settings/ProjectSettings.tsx
index e278c6ef7..3fc4df9c2 100644
--- a/web/app/pages/Project/Settings/ProjectSettings.tsx
+++ b/web/app/pages/Project/Settings/ProjectSettings.tsx
@@ -269,6 +269,7 @@ const ModalMessage = ({
interface Form extends Partial<Project> {
origins: string | null
ipBlacklist: string | null
+ countryBlacklist: string[]
}
const DEFAULT_PROJECT_NAME = 'Untitled Project'
@@ -289,6 +290,7 @@ const ProjectSettings = () => {
isPasswordProtected: false,
origins: null,
ipBlacklist: null,
+ countryBlacklist: [],
botsProtectionLevel: 'basic',
gscPropertyUri: null,
})
@@ -417,6 +419,7 @@ const ProjectSettings = () => {
...result,
ipBlacklist: _isString(result.ipBlacklist) ? result.ipBlacklist : _join(result.ipBlacklist, ', '),
origins: _isString(result.origins) ? result.origins : _join(result.origins, ', '),
+ countryBlacklist: result.countryBlacklist || [],
})
} catch (reason: any) {
setError(reason)
@@ -478,6 +481,7 @@ const ProjectSettings = () => {
}
}),
ipBlacklist: _isEmpty(data.ipBlacklist) ? null : _split(data.ipBlacklist, ','),
+ countryBlacklist: _isEmpty(data.countryBlacklist) ? null : data.countryBlacklist,
}
await updateProject(id, formalisedData as Partial<Project>)
toast.success(t('project.settings.updated'))
@@ -793,6 +797,13 @@ const ProjectSettings = () => {
botsProtectionLevel: name as any,
}))
}
+ countryBlacklist={form.countryBlacklist || []}
+ setCountryBlacklist={(countries) =>
+ setForm((prevForm) => ({
+ ...prevForm,
+ countryBlacklist: countries,
+ }))
+ }
/>
) : null}
diff --git a/web/app/pages/Project/Settings/tabs/Shields.tsx b/web/app/pages/Project/Settings/tabs/Shields.tsx
index e27a642a6..dadc92451 100644
--- a/web/app/pages/Project/Settings/tabs/Shields.tsx
+++ b/web/app/pages/Project/Settings/tabs/Shields.tsx
@@ -1,14 +1,21 @@
-import React from 'react'
+import _filter from 'lodash/filter'
+import _includes from 'lodash/includes'
+import _toUpper from 'lodash/toUpper'
+import React, { useState, useMemo } from 'react'
import { useTranslation } from 'react-i18next'
+import Flag from '~/ui/Flag'
import Input from '~/ui/Input'
+import MultiSelect from '~/ui/MultiSelect'
import Select from '~/ui/Select'
+import countries from '~/utils/isoCountries'
interface ShieldsProps {
form: {
origins: string | null
ipBlacklist: string | null
botsProtectionLevel?: string
+ countryBlacklist?: string[]
}
errors: {
origins?: string
@@ -18,10 +25,69 @@ interface ShieldsProps {
handleInput: (e: React.ChangeEvent<HTMLInputElement>) => void
botsProtectionLevels: readonly { name: string; title: string }[]
setBotsLevel: (name: string) => void
+ countryBlacklist: string[]
+ setCountryBlacklist: (countries: string[]) => void
}
-const Shields = ({ form, errors, beenSubmitted, handleInput, botsProtectionLevels, setBotsLevel }: ShieldsProps) => {
- const { t } = useTranslation('common')
+const Shields = ({
+ form,
+ errors,
+ beenSubmitted,
+ handleInput,
+ botsProtectionLevels,
+ setBotsLevel,
+ countryBlacklist,
+ setCountryBlacklist,
+}: ShieldsProps) => {
+ const {
+ t,
+ i18n: { language },
+ } = useTranslation('common')
+
+ // Get all country codes
+ const allCountries = useMemo(() => {
+ const countryCodes = Object.keys(countries.getAlpha2Codes())
+ return countryCodes.sort((a, b) => {
+ const nameA = countries.getName(a, language) || a
+ const nameB = countries.getName(b, language) || b
+ return nameA.localeCompare(nameB)
+ })
+ }, [language])
+
+ const [searchedCountries, setSearchedCountries] = useState<string[]>(allCountries)
+
+ const handleCountrySearch = (search: string) => {
+ if (search.length > 0) {
+ setSearchedCountries(
+ _filter(allCountries, (cc) => {
+ const countryName = countries.getName(cc, language) || cc
+ return _includes(_toUpper(countryName), _toUpper(search)) || _includes(_toUpper(cc), _toUpper(search))
+ }),
+ )
+ } else {
+ setSearchedCountries(allCountries)
+ }
+ }
+
+ const handleCountrySelect = (cc: string) => {
+ if (_includes(countryBlacklist, cc)) {
+ setCountryBlacklist(_filter(countryBlacklist, (c) => c !== cc))
+ } else {
+ setCountryBlacklist([...countryBlacklist, cc])
+ }
+ }
+
+ const handleCountryRemove = (cc: string) => {
+ setCountryBlacklist(_filter(countryBlacklist, (c) => c !== cc))
+ }
+
+ const renderCountryOption = (cc: string) => (
+ <div className='flex items-center gap-2'>
+ <Flag className='rounded-xs' country={cc} size={21} alt='' aria-hidden='true' />
+ <span>{countries.getName(cc, language) || cc}</span>
+ <span className='text-gray-400'>{cc}</span>
+ </div>
+ )
return (
<>
@@ -44,6 +110,25 @@ const Shields = ({ form, errors, beenSubmitted, handleInput, botsProtectionLevel
onChange={handleInput}
error={beenSubmitted ? errors.ipBlacklist : null}
/>
+ <div className='mt-4'>
+ <label className='block text-sm font-medium text-gray-700 dark:text-gray-200'>
+ {t('project.settings.countryBlacklist')}
+ </label>
+ <MultiSelect
+ className='mt-1'
+ items={searchedCountries}
+ labelExtractor={renderCountryOption as any}
+ itemExtractor={renderCountryOption as any}
+ keyExtractor={(cc) => cc}
+ label={countryBlacklist}
+ searchPlaseholder={t('project.settings.searchCountries')}
+ onSearch={handleCountrySearch}
+ placholder={t('project.settings.selectCountry')}
+ onSelect={handleCountrySelect}
+ onRemove={handleCountryRemove}
+ hint={t('project.settings.countryBlacklistHint')}
+ />
+ </div>
<div className='mt-4'>
<Select
id='botsProtectionLevel'
diff --git a/web/public/locales/en.json b/web/public/locales/en.json
index 3a1ec8d80..c730055d8 100644
--- a/web/public/locales/en.json
+++ b/web/public/locales/en.json
@@ -1247,6 +1247,10 @@
"errorNoRole": "Please select a role.",
"ipBlacklist": "IP's to blacklist",
"ipBlacklistHint": "A list of IP addresses from which no analytics will be collected on this project.\nThis functionality is handy if you want to ignore analytics from your IP, for example.\nExample: 172.126.10.16, 192.168.0.1/32, ::1",
+ "countryBlacklist": "Countries to exclude",
+ "countryBlacklistHint": "Traffic from these countries will not be tracked. This is useful if you want to exclude specific regions from your analytics.",
+ "searchCountries": "Search countries...",
+ "selectCountry": "Select a country to exclude...",
"transfer": "Transfer project",
"transferTo": "Transfer project",
"transferHint": "You can transfer '{{name}}' project to another user.\nThis user will become the project's owner and will be able to manage the project's settings, add/remove members, and invite new users.\nYou will be assigned to the project as an administrator. However, the new owner will be able to remove you from the project.",