Skip to content

🐸 Rybbit - open-source and privacy-friendly alternative to Google Analytics that is 10x more intuitive.

Add logic to exclude countries from events and replays (#649)

Stijn35478534037c
diff --git a/client/src/api/admin/excludedCountries.ts b/client/src/api/admin/excludedCountries.ts
new file mode 100644
index 000000000..5644b24fe
--- /dev/null
+++ b/client/src/api/admin/excludedCountries.ts
@@ -0,0 +1,67 @@
+import { useMutation, useQuery, useQueryClient } from "@tanstack/react-query";
+import { toast } from "sonner";
+import { authedFetch } from "../utils";
+import { updateSiteConfig } from "./sites";
+
+export interface ExcludedCountriesResponse {
+ success: boolean;
+ excludedCountries: string[];
+ error?: string;
+}
+
+export interface UpdateExcludedCountriesRequest {
+ siteId: number;
+ excludedCountries: string[];
+}
+
+export interface UpdateExcludedCountriesResponse {
+ success: boolean;
+ message: string;
+ excludedCountries: string[];
+ error?: string;
+ details?: string[];
+}
+
+export const fetchExcludedCountries = async (siteId: string): Promise<ExcludedCountriesResponse> => {
+ return await authedFetch<ExcludedCountriesResponse>(`/site/${siteId}/excluded-countries`);
+};
+
+export const updateExcludedCountries = async (
+ siteId: number,
+ excludedCountries: string[]
+): Promise<UpdateExcludedCountriesResponse> => {
+ const result = await updateSiteConfig(siteId, { excludedCountries });
+
+ return {
+ success: true,
+ message: "Excluded countries updated successfully",
+ excludedCountries: excludedCountries,
+ };
+};
+
+export const useGetExcludedCountries = (siteId: number) => {
+ return useQuery({
+ queryKey: ["excludedCountries", siteId],
+ queryFn: () => fetchExcludedCountries(siteId.toString()),
+ enabled: !!siteId,
+ });
+};
+
+export const useUpdateExcludedCountries = () => {
+ const queryClient = useQueryClient();
+
+ return useMutation<UpdateExcludedCountriesResponse, Error, UpdateExcludedCountriesRequest>({
+ mutationFn: ({ siteId, excludedCountries }: UpdateExcludedCountriesRequest) =>
+ updateExcludedCountries(siteId, excludedCountries),
+ onSuccess: (_: UpdateExcludedCountriesResponse, variables: UpdateExcludedCountriesRequest) => {
+ toast.success("Excluded countries updated successfully");
+ // Invalidate and refetch excluded countries data
+ queryClient.invalidateQueries({
+ queryKey: ["excludedCountries", variables.siteId],
+ });
+ },
+ onError: (error: Error) => {
+ toast.error(error.message || "Failed to update excluded countries");
+ },
+ });
+};
diff --git a/client/src/api/admin/sites.ts b/client/src/api/admin/sites.ts
index 1b47746be..e3b2e4652 100644
--- a/client/src/api/admin/sites.ts
+++ b/client/src/api/admin/sites.ts
@@ -117,6 +117,7 @@ export function updateSiteConfig(
saltUserIds?: boolean;
blockBots?: boolean;
excludedIPs?: string[];
+ excludedCountries?: string[];
sessionReplay?: boolean;
webVitals?: boolean;
trackErrors?: boolean;
diff --git a/client/src/components/SiteSettings/CountryExclusionManager.tsx b/client/src/components/SiteSettings/CountryExclusionManager.tsx
new file mode 100644
index 000000000..5a38e155c
--- /dev/null
+++ b/client/src/components/SiteSettings/CountryExclusionManager.tsx
@@ -0,0 +1,125 @@
+"use client";
+
+import { X } from "lucide-react";
+import React, { useState } from "react";
+import { toast } from "sonner";
+
+import { Button } from "@/components/ui/button";
+import { Label } from "@/components/ui/label";
+
+import { useGetExcludedCountries, useUpdateExcludedCountries } from "@/api/admin/excludedCountries";
+import { CountrySelector } from "./CountrySelector";
+
+interface CountryExclusionManagerProps {
+ siteId: number;
+ disabled?: boolean;
+}
+
+export function CountryExclusionManager({ siteId, disabled = false }: CountryExclusionManagerProps) {
+ const { data: excludedCountriesData, isLoading } = useGetExcludedCountries(siteId);
+ const updateExcludedCountriesMutation = useUpdateExcludedCountries();
+
+ const [countryList, setCountryList] = useState<string[]>([]);
+ const [hasUnsavedChanges, setHasUnsavedChanges] = useState(false);
+
+ React.useEffect(() => {
+ if (excludedCountriesData?.excludedCountries) {
+ setCountryList(excludedCountriesData.excludedCountries);
+ setHasUnsavedChanges(false);
+ }
+ }, [excludedCountriesData]);
+
+ const addCountry = (countryCode: string) => {
+ if (!countryList.includes(countryCode)) {
+ setCountryList([...countryList, countryCode]);
+ setHasUnsavedChanges(true);
+ }
+ };
+
+ const removeCountry = (countryCode: string) => {
+ setCountryList(countryList.filter(c => c !== countryCode));
+ setHasUnsavedChanges(true);
+ };
+
+ const handleSave = async () => {
+ try {
+ await updateExcludedCountriesMutation.mutateAsync({
+ siteId,
+ excludedCountries: countryList,
+ });
+ setHasUnsavedChanges(false);
+ } catch (error) {
+ // Error handling is done in the mutation
+ }
+ };
+
+ const handleReset = () => {
+ if (excludedCountriesData?.excludedCountries) {
+ setCountryList(excludedCountriesData.excludedCountries);
+ } else {
+ setCountryList([]);
+ }
+ setHasUnsavedChanges(false);
+ };
+
+ if (isLoading) {
+ return <div className="text-sm text-muted-foreground">Loading country exclusions...</div>;
+ }
+
+ return (
+ <div className="space-y-4">
+ <div>
+ <Label className="text-sm font-medium text-foreground block">Country Exclusions</Label>
+ <p className="text-xs text-muted-foreground mt-1">
+ Exclude traffic from specific countries. Events from these countries will not be tracked in your analytics.
+ </p>
+ </div>
+
+ <CountrySelector onSelect={addCountry} selectedCountries={countryList} disabled={disabled} />
+
+ {countryList.length > 0 && (
+ <div className="space-y-2">
+ <Label className="text-xs text-muted-foreground">Excluded Countries ({countryList.length})</Label>
+ <div className="flex flex-wrap gap-2">
+ {countryList.map(countryCode => (
+ <div
+ key={countryCode}
+ className="flex items-center space-x-1 px-3 py-1 bg-secondary text-secondary-foreground rounded-md text-sm"
+ >
+ <span>{countryCode}</span>
+ <button
+ type="button"
+ onClick={() => removeCountry(countryCode)}
+ disabled={disabled}
+ className="ml-1 hover:text-destructive disabled:opacity-50"
+ >
+ <X className="h-3 w-3" />
+ </button>
+ </div>
+ ))}
+ </div>
+ </div>
+ )}
+
+ {hasUnsavedChanges && (
+ <div className="flex items-center space-x-2 pt-2">
+ <Button
+ onClick={handleSave}
+ disabled={disabled || updateExcludedCountriesMutation.isPending}
+ size="sm"
+ >
+ {updateExcludedCountriesMutation.isPending ? "Saving..." : "Save Changes"}
+ </Button>
+ <Button
+ variant="outline"
+ onClick={handleReset}
+ disabled={disabled || updateExcludedCountriesMutation.isPending}
+ size="sm"
+ >
+ Reset
+ </Button>
+ </div>
+ )}
+ </div>
+ );
+}
diff --git a/client/src/components/SiteSettings/CountrySelector.tsx b/client/src/components/SiteSettings/CountrySelector.tsx
new file mode 100644
index 000000000..45a905b04
--- /dev/null
+++ b/client/src/components/SiteSettings/CountrySelector.tsx
@@ -0,0 +1,260 @@
+"use client";
+
+import { Check, ChevronsUpDown } from "lucide-react";
+import React, { useState } from "react";
+
+import { Button } from "@/components/ui/button";
+import { Command, CommandEmpty, CommandGroup, CommandInput, CommandItem, CommandList } from "@/components/ui/command";
+import { Popover, PopoverContent, PopoverTrigger } from "@/components/ui/popover";
+import { cn } from "@/lib/utils";
+
+// List of countries with their ISO codes
+const COUNTRIES = [
+ { code: "AF", name: "Afghanistan" },
+ { code: "AL", name: "Albania" },
+ { code: "DZ", name: "Algeria" },
+ { code: "AS", name: "American Samoa" },
+ { code: "AD", name: "Andorra" },
+ { code: "AO", name: "Angola" },
+ { code: "AG", name: "Antigua and Barbuda" },
+ { code: "AR", name: "Argentina" },
+ { code: "AM", name: "Armenia" },
+ { code: "AU", name: "Australia" },
+ { code: "AT", name: "Austria" },
+ { code: "AZ", name: "Azerbaijan" },
+ { code: "BS", name: "Bahamas" },
+ { code: "BH", name: "Bahrain" },
+ { code: "BD", name: "Bangladesh" },
+ { code: "BB", name: "Barbados" },
+ { code: "BY", name: "Belarus" },
+ { code: "BE", name: "Belgium" },
+ { code: "BZ", name: "Belize" },
+ { code: "BJ", name: "Benin" },
+ { code: "BT", name: "Bhutan" },
+ { code: "BO", name: "Bolivia" },
+ { code: "BA", name: "Bosnia and Herzegovina" },
+ { code: "BW", name: "Botswana" },
+ { code: "BR", name: "Brazil" },
+ { code: "BN", name: "Brunei" },
+ { code: "BG", name: "Bulgaria" },
+ { code: "BF", name: "Burkina Faso" },
+ { code: "BI", name: "Burundi" },
+ { code: "KH", name: "Cambodia" },
+ { code: "CM", name: "Cameroon" },
+ { code: "CA", name: "Canada" },
+ { code: "CV", name: "Cape Verde" },
+ { code: "CF", name: "Central African Republic" },
+ { code: "TD", name: "Chad" },
+ { code: "CL", name: "Chile" },
+ { code: "CN", name: "China" },
+ { code: "CO", name: "Colombia" },
+ { code: "KM", name: "Comoros" },
+ { code: "CG", name: "Congo" },
+ { code: "CD", name: "Congo (Democratic Republic)" },
+ { code: "CR", name: "Costa Rica" },
+ { code: "HR", name: "Croatia" },
+ { code: "CU", name: "Cuba" },
+ { code: "CY", name: "Cyprus" },
+ { code: "CZ", name: "Czech Republic" },
+ { code: "DK", name: "Denmark" },
+ { code: "DJ", name: "Djibouti" },
+ { code: "DM", name: "Dominica" },
+ { code: "DO", name: "Dominican Republic" },
+ { code: "EC", name: "Ecuador" },
+ { code: "EG", name: "Egypt" },
+ { code: "SV", name: "El Salvador" },
+ { code: "GQ", name: "Equatorial Guinea" },
+ { code: "ER", name: "Eritrea" },
+ { code: "EE", name: "Estonia" },
+ { code: "ET", name: "Ethiopia" },
+ { code: "FJ", name: "Fiji" },
+ { code: "FI", name: "Finland" },
+ { code: "FR", name: "France" },
+ { code: "GA", name: "Gabon" },
+ { code: "GM", name: "Gambia" },
+ { code: "GE", name: "Georgia" },
+ { code: "DE", name: "Germany" },
+ { code: "GH", name: "Ghana" },
+ { code: "GR", name: "Greece" },
+ { code: "GD", name: "Grenada" },
+ { code: "GT", name: "Guatemala" },
+ { code: "GN", name: "Guinea" },
+ { code: "GW", name: "Guinea-Bissau" },
+ { code: "GY", name: "Guyana" },
+ { code: "HT", name: "Haiti" },
+ { code: "HN", name: "Honduras" },
+ { code: "HU", name: "Hungary" },
+ { code: "IS", name: "Iceland" },
+ { code: "IN", name: "India" },
+ { code: "ID", name: "Indonesia" },
+ { code: "IR", name: "Iran" },
+ { code: "IQ", name: "Iraq" },
+ { code: "IE", name: "Ireland" },
+ { code: "IL", name: "Israel" },
+ { code: "IT", name: "Italy" },
+ { code: "JM", name: "Jamaica" },
+ { code: "JP", name: "Japan" },
+ { code: "JO", name: "Jordan" },
+ { code: "KZ", name: "Kazakhstan" },
+ { code: "KE", name: "Kenya" },
+ { code: "KI", name: "Kiribati" },
+ { code: "KP", name: "Korea (North)" },
+ { code: "KR", name: "Korea (South)" },
+ { code: "KW", name: "Kuwait" },
+ { code: "KG", name: "Kyrgyzstan" },
+ { code: "LA", name: "Laos" },
+ { code: "LV", name: "Latvia" },
+ { code: "LB", name: "Lebanon" },
+ { code: "LS", name: "Lesotho" },
+ { code: "LR", name: "Liberia" },
+ { code: "LY", name: "Libya" },
+ { code: "LI", name: "Liechtenstein" },
+ { code: "LT", name: "Lithuania" },
+ { code: "LU", name: "Luxembourg" },
+ { code: "MK", name: "North Macedonia" },
+ { code: "MG", name: "Madagascar" },
+ { code: "MW", name: "Malawi" },
+ { code: "MY", name: "Malaysia" },
+ { code: "MV", name: "Maldives" },
+ { code: "ML", name: "Mali" },
+ { code: "MT", name: "Malta" },
+ { code: "MH", name: "Marshall Islands" },
+ { code: "MR", name: "Mauritania" },
+ { code: "MU", name: "Mauritius" },
+ { code: "MX", name: "Mexico" },
+ { code: "FM", name: "Micronesia" },
+ { code: "MD", name: "Moldova" },
+ { code: "MC", name: "Monaco" },
+ { code: "MN", name: "Mongolia" },
+ { code: "ME", name: "Montenegro" },
+ { code: "MA", name: "Morocco" },
+ { code: "MZ", name: "Mozambique" },
+ { code: "MM", name: "Myanmar" },
+ { code: "NA", name: "Namibia" },
+ { code: "NR", name: "Nauru" },
+ { code: "NP", name: "Nepal" },
+ { code: "NL", name: "Netherlands" },
+ { code: "NZ", name: "New Zealand" },
+ { code: "NI", name: "Nicaragua" },
+ { code: "NE", name: "Niger" },
+ { code: "NG", name: "Nigeria" },
+ { code: "NO", name: "Norway" },
+ { code: "OM", name: "Oman" },
+ { code: "PK", name: "Pakistan" },
+ { code: "PW", name: "Palau" },
+ { code: "PA", name: "Panama" },
+ { code: "PG", name: "Papua New Guinea" },
+ { code: "PY", name: "Paraguay" },
+ { code: "PE", name: "Peru" },
+ { code: "PH", name: "Philippines" },
+ { code: "PL", name: "Poland" },
+ { code: "PT", name: "Portugal" },
+ { code: "QA", name: "Qatar" },
+ { code: "RO", name: "Romania" },
+ { code: "RU", name: "Russia" },
+ { code: "RW", name: "Rwanda" },
+ { code: "KN", name: "Saint Kitts and Nevis" },
+ { code: "LC", name: "Saint Lucia" },
+ { code: "VC", name: "Saint Vincent and the Grenadines" },
+ { code: "WS", name: "Samoa" },
+ { code: "SM", name: "San Marino" },
+ { code: "ST", name: "Sao Tome and Principe" },
+ { code: "SA", name: "Saudi Arabia" },
+ { code: "SN", name: "Senegal" },
+ { code: "RS", name: "Serbia" },
+ { code: "SC", name: "Seychelles" },
+ { code: "SL", name: "Sierra Leone" },
+ { code: "SG", name: "Singapore" },
+ { code: "SK", name: "Slovakia" },
+ { code: "SI", name: "Slovenia" },
+ { code: "SB", name: "Solomon Islands" },
+ { code: "SO", name: "Somalia" },
+ { code: "ZA", name: "South Africa" },
+ { code: "SS", name: "South Sudan" },
+ { code: "ES", name: "Spain" },
+ { code: "LK", name: "Sri Lanka" },
+ { code: "SD", name: "Sudan" },
+ { code: "SR", name: "Suriname" },
+ { code: "SZ", name: "Eswatini" },
+ { code: "SE", name: "Sweden" },
+ { code: "CH", name: "Switzerland" },
+ { code: "SY", name: "Syria" },
+ { code: "TW", name: "Taiwan" },
+ { code: "TJ", name: "Tajikistan" },
+ { code: "TZ", name: "Tanzania" },
+ { code: "TH", name: "Thailand" },
+ { code: "TL", name: "Timor-Leste" },
+ { code: "TG", name: "Togo" },
+ { code: "TO", name: "Tonga" },
+ { code: "TT", name: "Trinidad and Tobago" },
+ { code: "TN", name: "Tunisia" },
+ { code: "TR", name: "Turkey" },
+ { code: "TM", name: "Turkmenistan" },
+ { code: "TV", name: "Tuvalu" },
+ { code: "UG", name: "Uganda" },
+ { code: "UA", name: "Ukraine" },
+ { code: "AE", name: "United Arab Emirates" },
+ { code: "GB", name: "United Kingdom" },
+ { code: "US", name: "United States" },
+ { code: "UY", name: "Uruguay" },
+ { code: "UZ", name: "Uzbekistan" },
+ { code: "VU", name: "Vanuatu" },
+ { code: "VA", name: "Vatican City" },
+ { code: "VE", name: "Venezuela" },
+ { code: "VN", name: "Vietnam" },
+ { code: "YE", name: "Yemen" },
+ { code: "ZM", name: "Zambia" },
+ { code: "ZW", name: "Zimbabwe" },
+];
+
+interface CountrySelectorProps {
+ onSelect: (countryCode: string) => void;
+ selectedCountries: string[];
+ disabled?: boolean;
+}
+
+export function CountrySelector({ onSelect, selectedCountries, disabled = false }: CountrySelectorProps) {
+ const [open, setOpen] = useState(false);
+
+ const availableCountries = COUNTRIES.filter(country => !selectedCountries.includes(country.code));
+
+ return (
+ <Popover open={open} onOpenChange={setOpen}>
+ <PopoverTrigger asChild>
+ <Button
+ variant="outline"
+ role="combobox"
+ aria-expanded={open}
+ className="w-full justify-between"
+ disabled={disabled || availableCountries.length === 0}
+ >
+ {availableCountries.length === 0 ? "All countries excluded" : "Select country to exclude..."}
+ <ChevronsUpDown className="ml-2 h-4 w-4 shrink-0 opacity-50" />
+ </Button>
+ </PopoverTrigger>
+ <PopoverContent className="w-full p-0" align="start">
+ <Command>
+ <CommandInput placeholder="Search countries..." />
+ <CommandList>
+ <CommandEmpty>No country found.</CommandEmpty>
+ <CommandGroup>
+ {availableCountries.map(country => (
+ <CommandItem
+ key={country.code}
+ value={`${country.name} ${country.code}`}
+ onSelect={() => {
+ onSelect(country.code);
+ setOpen(false);
+ }}
+ >
+ <Check className={cn("mr-2 h-4 w-4", "opacity-0")} />
+ {country.name} ({country.code})
+ </CommandItem>
+ ))}
+ </CommandGroup>
+ </CommandList>
+ </Command>
+ </PopoverContent>
+ </Popover>
+ );
+}
diff --git a/client/src/components/SiteSettings/SiteConfiguration.tsx b/client/src/components/SiteSettings/SiteConfiguration.tsx
index 1d8d87b7f..4eaeef9c4 100644
--- a/client/src/components/SiteSettings/SiteConfiguration.tsx
+++ b/client/src/components/SiteSettings/SiteConfiguration.tsx
@@ -24,6 +24,7 @@ import { Switch } from "@/components/ui/switch";
import { deleteSite, SiteResponse, updateSiteConfig, useGetSitesFromOrg } from "@/api/admin/sites";
import { normalizeDomain } from "@/lib/utils";
import { IPExclusionManager } from "./IPExclusionManager";
+import { CountryExclusionManager } from "./CountryExclusionManager";
import { useStripeSubscription } from "../../lib/subscription/useStripeSubscription";
import { Badge } from "../ui/badge";
import { IS_CLOUD } from "../../lib/const";
@@ -301,6 +302,9 @@ export function SiteConfiguration({ siteMetadata, disabled = false, onClose }: S
{/* IP Exclusions Section */}
<IPExclusionManager siteId={siteMetadata.siteId} disabled={disabled} />
+ {/* Country Exclusions Section */}
+ <CountryExclusionManager siteId={siteMetadata.siteId} disabled={disabled} />
+
{/* Domain Settings Section */}
<div className="space-y-3">
<div>
diff --git a/docs/content/docs/api.mdx b/docs/content/docs/api.mdx
index 4bba21aac..1cb1fac2b 100644
--- a/docs/content/docs/api.mdx
+++ b/docs/content/docs/api.mdx
@@ -843,6 +843,85 @@ When you exceed the rate limit, you'll receive a `429` status code:
}
```
+## Configuration Endpoints
+
+### Get Excluded IPs
+
+Retrieve the list of excluded IP addresses for a site.
+
+```bash
+GET /api/site/:siteId/excluded-ips
+Authorization: Bearer <your-token>
+```
+
+**Response:**
+```json
+{
+ "success": true,
+ "excludedIPs": ["192.168.1.0/24", "10.0.0.1"]
+}
+```
+
+### Get Excluded Countries
+
+Retrieve the list of excluded countries for a site.
+
+```bash
+GET /api/site/:siteId/excluded-countries
+Authorization: Bearer <your-token>
+```
+
+**Response:**
+```json
+{
+ "success": true,
+ "excludedCountries": ["US", "GB", "CN"]
+}
+```
+
+### Update Site Configuration
+
+Update site configuration including IP and country exclusions.
+
+```bash
+POST /api/site/:siteId/config
+Authorization: Bearer <your-token>
+Content-Type: application/json
+
+{
+ "excludedIPs": ["192.168.1.0/24", "10.0.0.1"],
+ "excludedCountries": ["US", "GB"],
+ "blockBots": true,
+ "sessionReplay": false
+}
+```
+
+**Request Parameters:**
+- `excludedIPs` (string[]): List of IP addresses/ranges to exclude (max 100)
+- `excludedCountries` (string[]): List of 2-letter ISO country codes to exclude (max 250)
+- `blockBots` (boolean): Enable/disable bot traffic blocking
+- `sessionReplay` (boolean): Enable/disable session replay
+- Other site configuration options (see [Site Settings](/docs/site-settings))
+
+**Response:**
+```json
+{
+ "success": true,
+ "message": "Site configuration updated successfully",
+ "config": {
+ "excludedIPs": ["192.168.1.0/24"],
+ "excludedCountries": ["US", "GB"],
+ "blockBots": true
+ }
+}
+```
+
+**Country Code Validation:**
+- Must be uppercase 2-letter ISO 3166-1 alpha-2 codes (e.g., `US`, `GB`, `CN`)
+- Invalid codes will return a 400 error with validation details
+
+See the [Filter Traffic](/docs/filter-traffic) documentation for more details on traffic filtering.
+
## Best Practices
<Callout type="info">
diff --git a/docs/content/docs/filter-traffic.mdx b/docs/content/docs/filter-traffic.mdx
new file mode 100644
index 000000000..b9c18c712
--- /dev/null
+++ b/docs/content/docs/filter-traffic.mdx
@@ -0,0 +1,118 @@
+---
+title: Filter Traffic
+description: Block traffic from specific IP addresses or countries to improve analytics accuracy
+---
+
+import { Callout } from 'fumadocs-ui/components/callout';
+
+Rybbit provides server-side filtering to exclude traffic from your analytics. This helps you maintain accurate data by blocking unwanted visits, bot traffic, or your own pageviews.
+
+## IP Exclusion
+
+Block traffic from specific IP addresses or ranges at the server level. For detailed information on IP exclusion including setup instructions, supported formats (CIDR, ranges), and best practices, see [Hiding Your Own Traffic](/docs/hiding-own-traffic).
+
+**Quick overview:**
+- Supports single IPs, CIDR notation, and IPv4 ranges
+- Maximum 100 IP exclusions per site
+- Works at server level before data reaches your database
+- Configure in Site Settings → IP Exclusions section
+
+## Country Exclusion
+
+Block all traffic from specific countries to filter out unwanted analytics data or comply with regional requirements.
+
+### Setting Up Country Exclusion
+
+1. **Navigate to Site Settings**: Go to your site's settings page in the Rybbit dashboard
+2. **Find Country Exclusions section**: Scroll down to the "Country Exclusions" configuration
+3. **Select countries to exclude**: Use the searchable dropdown to select countries you want to block
+
+### How It Works
+
+When an event is received, Rybbit:
+1. Extracts the visitor's IP address
+2. Performs a GeoIP lookup using the MaxMind GeoLite2 database
+3. Checks if the country matches your exclusion list
+4. Blocks the event if the country is excluded (returns 200 response but doesn't track)
+
+### Supported Country Codes
+
+All countries are supported using 2-letter ISO country codes (ISO 3166-1 alpha-2):
+
+- **Examples**: `US` (United States), `GB` (United Kingdom), `CN` (China), `RU` (Russia), `IN` (India), `DE` (Germany)
+- **Case-insensitive**: Both `US` and `us` are accepted
+- **Maximum**: Up to 250 countries can be excluded
+
+### Use Cases
+
+- **Filter bot traffic**: Block countries known for generating bot traffic
+- **Privacy compliance**: Exclude regions for data protection requirements
+- **Analytics accuracy**: Remove traffic from regions where your service isn't available
+- **Development testing**: Block production traffic from specific regions during testing
+
+### Key Features
+
+- **Server-side filtering**: Traffic is blocked before it reaches your analytics database
+- **GeoIP-based**: Uses MaxMind GeoLite2 for accurate country detection
+- **Near real-time updates**: Changes take effect within 60 seconds (cache TTL)
+- **No browser dependency**: Works regardless of browser or device
+- **Applies to all events**: Blocks pageviews, custom events, session replay, and performance metrics
+
+<Callout type="warning">
+**Private IP addresses**: Country exclusion won't work for private IP addresses (e.g., `127.0.0.1`, `192.168.x.x`, `10.x.x.x`, `172.16.x.x`) as these cannot be geolocated. This includes localhost and Docker container IPs during local development.
+</Callout>
+
+<Callout type="info">
+**Testing locally**: To test country exclusion during development, send events with a public IP address using the `ip_address` field in your event payload. The GeoIP lookup will use the custom IP instead of the request IP.
+
+Example:
+```bash
+curl -X POST http://localhost:3000/track \
+ -H "Content-Type: application/json" \
+ -d '{
+ "type": "pageview",
+ "site_id": "your-site-id",
+ "ip_address": "8.8.8.8",
+ "url": "https://example.com/test"
+ }'
+```
+</Callout>
+
+<Callout type="info">
+**VPNs and proxies**: Visitors using VPNs or proxies will be detected based on the VPN/proxy server location, not their actual physical location.
+</Callout>
+
+## Combining Filters
+
+You can use both IP and country exclusions together for comprehensive filtering:
+
+- **IP exclusions** are checked first, then **country exclusions**
+- Both filters work at the server level before data reaches your database
+- Excluded events return a `200` status code but with a message indicating they were not tracked
+
+## API Access
+
+Both IP and country exclusions can be managed via the API:
+
+### Get Excluded IPs
+```bash
+GET /api/site/:siteId/excluded-ips
+```
+
+### Get Excluded Countries
+```bash
+GET /api/site/:siteId/excluded-countries
+```
+
+### Update Site Configuration
+```bash
+POST /api/site/:siteId/config
+Content-Type: application/json
+
+{
+ "excludedIPs": ["192.168.1.0/24", "10.0.0.1"],
+ "excludedCountries": ["US", "GB", "CN"]
+}
+```
+
+See the [API documentation](/docs/api) for more details on authentication and request formats.
diff --git a/docs/content/docs/meta.json b/docs/content/docs/meta.json
index 0af5bb1cd..b5eda1e7f 100644
--- a/docs/content/docs/meta.json
+++ b/docs/content/docs/meta.json
@@ -12,6 +12,7 @@
"api",
"localhost-tracking",
"hiding-own-traffic",
+ "filter-traffic",
"---Self-hosting---",
"self-hosting",
"troubleshooting",
diff --git a/docs/content/docs/site-settings.mdx b/docs/content/docs/site-settings.mdx
index 402034062..517c4d01c 100644
--- a/docs/content/docs/site-settings.mdx
+++ b/docs/content/docs/site-settings.mdx
@@ -32,6 +32,15 @@ When enabled, Rybbit will forget about unique users every day. If a user visits
- Unique user count over a period longer than 24 hours will be inflated
- The user retention page will effectively be useless
+## Traffic Filtering
+
+You can filter unwanted traffic from your analytics using IP and country exclusions. See the [Filter Traffic](/docs/filter-traffic) guide for detailed information on:
+
+- **IP Exclusions**: Block specific IP addresses or ranges (supports CIDR notation and IPv4 ranges)
+- **Country Exclusions**: Block all traffic from specific countries using ISO country codes
+
+Both filtering methods work at the server level, ensuring blocked traffic never reaches your analytics database.
+
## Changing Domains
You can update the domain of your site directly from the settings page.
diff --git a/server/src/api/sessionReplay/recordSessionReplay.ts b/server/src/api/sessionReplay/recordSessionReplay.ts
index 04431a562..a862f07bf 100644
--- a/server/src/api/sessionReplay/recordSessionReplay.ts
+++ b/server/src/api/sessionReplay/recordSessionReplay.ts
@@ -37,7 +37,7 @@ export async function recordSessionReplay(
) {
try {
// Get the site configuration to get the numeric siteId
- const { siteId, excludedIPs, sessionReplay } = (await siteConfig.getConfig(request.params.site)) ?? {};
+ const { siteId, excludedIPs, excludedCountries, sessionReplay } = (await siteConfig.getConfig(request.params.site)) ?? {};
if (!sessionReplay) {
logger.info(`[SessionReplay] Skipping event for site ${siteId} - session replay not enabled`);
@@ -94,6 +94,24 @@ export async function recordSessionReplay(
});
}
+ // Check if the country should be excluded from tracking
+ if (excludedCountries && excludedCountries.length > 0) {
+ const { getLocation } = await import("../../db/geolocation/geolocation.js");
+ const locationResults = await getLocation([requestIP]);
+ const locationData = locationResults[requestIP];
+
+ if (locationData?.countryIso) {
+ const isCountryExcluded = await siteConfig.isCountryExcluded(locationData.countryIso, request.params.site);
+ if (isCountryExcluded) {
+ logger.info(`[SessionReplay] Country ${locationData.countryIso} excluded from tracking for site ${siteId}`);
+ return reply.status(200).send({
+ success: true,
+ message: "Session replay not recorded - country excluded",
+ });
+ }
+ }
+ }
+
// Extract request metadata for tracking
const userAgent = request.headers["user-agent"] || "";
const ipAddress = getIpAddress(request);
diff --git a/server/src/api/sites/getSiteExcludedCountries.ts b/server/src/api/sites/getSiteExcludedCountries.ts
new file mode 100644
index 000000000..9d1c6e2cd
--- /dev/null
+++ b/server/src/api/sites/getSiteExcludedCountries.ts
@@ -0,0 +1,72 @@
+import { FastifyReply, FastifyRequest } from "fastify";
+import { z } from "zod";
+import { db } from "../../db/postgres/postgres.js";
+import { sites } from "../../db/postgres/schema.js";
+import { eq } from "drizzle-orm";
+import { getUserHasAccessToSite } from "../../lib/auth-utils.js";
+
+const getSiteExcludedCountriesSchema = z.object({
+ siteId: z.string().min(1),
+});
+
+export async function getSiteExcludedCountries(request: FastifyRequest, reply: FastifyReply) {
+ try {
+ const validationResult = getSiteExcludedCountriesSchema.safeParse(request.params);
+
+ if (!validationResult.success) {
+ return reply.status(400).send({
+ success: false,
+ error: "Invalid site ID",
+ details: validationResult.error.flatten(),
+ });
+ }
+
+ const { siteId } = validationResult.data;
+ const numericSiteId = Number(siteId);
+
+ if (!Number.isInteger(numericSiteId) || isNaN(numericSiteId) || numericSiteId <= 0) {
+ return reply.status(400).send({
+ success: false,
+ error: "Invalid site ID: must be a positive integer",
+ });
+ }
+
+ // Check if user has access to this site
+ const hasAccess = await getUserHasAccessToSite(request, numericSiteId);
+
+ if (!hasAccess) {
+ return reply.status(403).send({
+ success: false,
+ error: "Forbidden: You don't have access to this site",
+ });
+ }
+
+ const site = await db
+ .select({
+ excludedCountries: sites.excludedCountries,
+ })
+ .from(sites)
+ .where(eq(sites.siteId, numericSiteId))
+ .limit(1);
+
+ if (site.length === 0) {
+ return reply.status(404).send({
+ success: false,
+ error: "Site not found",
+ });
+ }
+
+ const excludedCountries = Array.isArray(site[0].excludedCountries) ? site[0].excludedCountries : [];
+
+ return reply.send({
+ success: true,
+ excludedCountries,
+ });
+ } catch (error) {
+ console.error("Error getting excluded countries:", error);
+ return reply.status(500).send({
+ success: false,
+ error: "Failed to get excluded countries",
+ });
+ }
+}
diff --git a/server/src/api/sites/updateSiteConfig.ts b/server/src/api/sites/updateSiteConfig.ts
index 1c55fa051..5a4a1a24b 100644
--- a/server/src/api/sites/updateSiteConfig.ts
+++ b/server/src/api/sites/updateSiteConfig.ts
@@ -34,6 +34,16 @@ const updateSiteConfigSchema = z.object({
)
.optional(),
excludedIPs: z.array(z.string().trim().min(1)).max(100).optional(),
+ excludedCountries: z
+ .array(
+ z
+ .string()
+ .trim()
+ .length(2)
+ .regex(/^[A-Z]{2}$/, "Country code must be a 2-letter ISO code (e.g., US, GB, CN)")
+ )
+ .max(250)
+ .optional(),
// Analytics features
sessionReplay: z.boolean().optional(),
@@ -109,6 +119,7 @@ export async function updateSiteConfig(
"blockBots",
"domain",
"excludedIPs",
+ "excludedCountries",
"sessionReplay",
"webVitals",
"trackErrors",
diff --git a/server/src/db/postgres/schema.ts b/server/src/db/postgres/schema.ts
index c44befe6b..5e68c839c 100644
--- a/server/src/db/postgres/schema.ts
+++ b/server/src/db/postgres/schema.ts
@@ -70,6 +70,7 @@ export const sites = pgTable(
saltUserIds: boolean().default(false),
blockBots: boolean().default(true).notNull(),
excludedIPs: jsonb("excluded_ips").default([]), // Array of IP addresses/ranges to exclude
+ excludedCountries: jsonb("excluded_countries").default([]), // Array of ISO country codes to exclude (e.g., ["US", "GB"])
sessionReplay: boolean().default(false),
webVitals: boolean().default(false),
trackErrors: boolean().default(false),
diff --git a/server/src/index.ts b/server/src/index.ts
index aaa30fb7a..73102741f 100644
--- a/server/src/index.ts
+++ b/server/src/index.ts
@@ -50,6 +50,7 @@ import { deleteSite } from "./api/sites/deleteSite.js";
import { getSite } from "./api/sites/getSite.js";
import { getSiteApiConfig } from "./api/sites/getSiteApiConfig.js";
import { getSiteExcludedIPs } from "./api/sites/getSiteExcludedIPs.js";
+import { getSiteExcludedCountries } from "./api/sites/getSiteExcludedCountries.js";
import { getSiteHasData } from "./api/sites/getSiteHasData.js";
import { getSiteIsPublic } from "./api/sites/getSiteIsPublic.js";
import { getSitesFromOrg } from "./api/sites/getSitesFromOrg.js";
@@ -340,6 +341,7 @@ server.get("/api/site/:siteId/api-config", getSiteApiConfig);
server.post("/api/site/:siteId/api-config", updateSiteApiConfig);
server.get("/api/site/:siteId/tracking-config", getTrackingConfig);
server.get("/api/site/:siteId/excluded-ips", getSiteExcludedIPs);
+server.get("/api/site/:siteId/excluded-countries", getSiteExcludedCountries);
server.get("/api/list-organization-members/:organizationId", listOrganizationMembers);
server.get("/api/user/organizations", getUserOrganizations);
server.post("/api/add-user-to-organization", addUserToOrganization);
diff --git a/server/src/lib/siteConfig.ts b/server/src/lib/siteConfig.ts
index c05f4c004..2f0bb3955 100644
--- a/server/src/lib/siteConfig.ts
+++ b/server/src/lib/siteConfig.ts
@@ -13,6 +13,7 @@ export interface SiteConfigData {
domain: string;
blockBots: boolean;
excludedIPs: string[];
+ excludedCountries: string[];
apiKey?: string | null;
sessionReplay: boolean;
webVitals: boolean;
@@ -58,6 +59,7 @@ class SiteConfig {
domain: sites.domain,
blockBots: sites.blockBots,
excludedIPs: sites.excludedIPs,
+ excludedCountries: sites.excludedCountries,
apiKey: sites.apiKey,
sessionReplay: sites.sessionReplay,
webVitals: sites.webVitals,
@@ -84,6 +86,7 @@ class SiteConfig {
domain: site.domain || "",
blockBots: site.blockBots === undefined ? true : site.blockBots,
excludedIPs: Array.isArray(site.excludedIPs) ? site.excludedIPs : [],
+ excludedCountries: Array.isArray(site.excludedCountries) ? site.excludedCountries : [],
apiKey: site.apiKey,
sessionReplay: site.sessionReplay || false,
webVitals: site.webVitals || false,
@@ -187,6 +190,25 @@ class SiteConfig {
return false;
}
+ /**
+ * Check if a country code is in the excluded countries list
+ * @param countryIso - ISO country code (e.g., "US", "GB", "CN")
+ * @param siteIdOrId - Site identifier
+ * @returns true if country should be excluded
+ */
+ async isCountryExcluded(countryIso: string | undefined, siteIdOrId?: string | number): Promise<boolean> {
+ if (!siteIdOrId || !countryIso) return false;
+ const config = await this.getSiteByAnyId(siteIdOrId);
+ const excludedCountries = config?.excludedCountries || [];
+ if (!excludedCountries || excludedCountries.length === 0) {
+ return false;
+ }
+
+ // Convert to uppercase for case-insensitive comparison
+ const normalizedCountry = countryIso.toUpperCase();
+ return excludedCountries.some(country => country.toUpperCase() === normalizedCountry);
+ }
+
/**
* Check if an IP address matches a specific pattern
* Supports:
diff --git a/server/src/services/shared/requestValidation.test.ts b/server/src/services/shared/requestValidation.test.ts
index 015bd86fe..be31ec872 100644
--- a/server/src/services/shared/requestValidation.test.ts
+++ b/server/src/services/shared/requestValidation.test.ts
@@ -10,6 +10,7 @@ interface SiteConfigData {
saltUserIds: boolean;
blockBots: boolean;
excludedIPs: string[];
+ excludedCountries: string[];
sessionReplay: boolean;
webVitals: boolean;
trackErrors: boolean;
@@ -77,6 +78,7 @@ describe("validateApiKey", () => {
saltUserIds: false,
blockBots: true,
excludedIPs: [],
+ excludedCountries: [],
sessionReplay: false,
webVitals: false,
trackErrors: false,
@@ -110,6 +112,7 @@ describe("validateApiKey", () => {
saltUserIds: false,
blockBots: true,
excludedIPs: [],
+ excludedCountries: [],
sessionReplay: false,
webVitals: false,
trackErrors: false,
@@ -137,6 +140,7 @@ describe("validateApiKey", () => {
saltUserIds: false,
blockBots: true,
excludedIPs: [],
+ excludedCountries: [],
sessionReplay: false,
webVitals: false,
trackErrors: false,
@@ -180,6 +184,7 @@ describe("validateApiKey", () => {
saltUserIds: false,
blockBots: true,
excludedIPs: [],
+ excludedCountries: [],
sessionReplay: false,
webVitals: false,
trackErrors: false,
diff --git a/server/src/services/tracker/trackEvent.ts b/server/src/services/tracker/trackEvent.ts
index b8de474a4..8a4553f3b 100644
--- a/server/src/services/tracker/trackEvent.ts
+++ b/server/src/services/tracker/trackEvent.ts
@@ -288,6 +288,27 @@ export async function trackEvent(request: FastifyRequest, reply: FastifyReply) {
}
}
+ // Check if the country should be excluded from tracking
+ if (siteConfiguration.excludedCountries && siteConfiguration.excludedCountries.length > 0) {
+ const { getLocation } = await import("../../db/geolocation/geolocation.js");
+ const locationResults = await getLocation([requestIP]);
+ const locationData = locationResults[requestIP];
+
+ if (locationData?.countryIso) {
+ const isCountryExcluded = await siteConfig.isCountryExcluded(locationData.countryIso, validatedPayload.site_id);
+ if (isCountryExcluded) {
+ logger.info(
+ { siteId: validatedPayload.site_id, country: locationData.countryIso },
+ "Country excluded from tracking"
+ );
+ return reply.status(200).send({
+ success: true,
+ message: "Event not tracked - country excluded",
+ });
+ }
+ }
+ }
+
// Create base payload for the event using validated data
const payload = await createBasePayload(
request, // Pass request for IP/UA