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!

Referrer grouping

Blue Mouse7166e7d22a8c
diff --git a/backend/apps/cloud/src/analytics/analytics.service.ts b/backend/apps/cloud/src/analytics/analytics.service.ts
index 8d9ca3c49..b2bdd6c13 100644
--- a/backend/apps/cloud/src/analytics/analytics.service.ts
+++ b/backend/apps/cloud/src/analytics/analytics.service.ts
@@ -58,6 +58,7 @@ import {
REDIS_TRIALS_COUNT_KEY,
} from '../common/constants'
import { clickhouse } from '../common/integrations/clickhouse'
+import { getDomainsForRefName } from './referrers.map'
import {
calculateRelativePercentage,
hash,
@@ -948,6 +949,7 @@ export class AnalyticsService {
customEVFilterApplied = true
} else if (
!_includes(SUPPORTED_COLUMNS, column) &&
+ column !== 'refn' &&
!_includes(TRAFFIC_METAKEY_COLUMNS, column) &&
!_startsWith(column, 'tag:key:') &&
column !== 'entryPage' &&
@@ -1011,6 +1013,34 @@ export class AnalyticsService {
const param = `qf_${col}_${f}`
params[param] = filter
+ // Special: refn (canonical referrer name/root domain)
+ if (column === 'refn') {
+ const patterns = getDomainsForRefName(String(filter)) || [
+ String(filter),
+ ]
+ const parts: string[] = []
+ for (let i = 0; i < patterns.length; i++) {
+ const pattern = String(patterns[i])
+ if (pattern.includes('://')) {
+ // Scheme-specific referrers (e.g., android-app://...) -> prefix match on full ref value
+ const pp = `qf_${col}_${f}_p_${i}`
+ params[pp] = pattern.toLowerCase()
+ parts.push(`startsWith(lower(ref), {${pp}:String})`)
+ continue
+ }
+
+ // Plain domain pattern -> host equals domain OR endsWith('.' + domain)
+ const dp = `qf_${col}_${f}_d_${i}`
+ params[dp] = pattern.toLowerCase()
+ parts.push(
+ `(domain(ref) != '' AND (lower(domain(ref)) = {${dp}:String} OR endsWith(lower(domain(ref)), concat('.', {${dp}:String})))) OR (domain(ref) = '' AND (lower(ref) = {${dp}:String} OR endsWith(lower(ref), concat('.', {${dp}:String}))))`,
+ )
+ }
+ const combined = parts.map(p => `(${p})`).join(' OR ')
+ query += isExclusive ? `NOT (${combined})` : `(${combined})`
+ continue
+ }
+
// Entry/Exit page filters (virtual columns via session scope)
if (column === 'entryPage' || column === 'exitPage') {
const pageSelector =
diff --git a/backend/apps/cloud/src/analytics/referrers.map.ts b/backend/apps/cloud/src/analytics/referrers.map.ts
new file mode 100644
index 000000000..111ea3b34
--- /dev/null
+++ b/backend/apps/cloud/src/analytics/referrers.map.ts
@@ -0,0 +1,34 @@
+import fs from 'fs'
+import path from 'path'
+
+type ReferrerJson = { name: string; patterns: string[] }
+
+let cachedMap: ReferrerJson[] | null = null
+
+const loadMap = (): ReferrerJson[] => {
+ if (cachedMap) return cachedMap
+ const candidates = [
+ // Repo root (when running from project root)
+ path.resolve(process.cwd(), 'web/app/utils/referrers.map.json'),
+ // Relative to compiled file location
+ path.resolve(__dirname, '../../../../../web/app/utils/referrers.map.json'),
+ ]
+ for (const p of candidates) {
+ try {
+ const raw = fs.readFileSync(p, 'utf8')
+ cachedMap = JSON.parse(raw) as ReferrerJson[]
+ return cachedMap
+ } catch {
+ // try next location
+ }
+ }
+ cachedMap = []
+ return cachedMap
+}
+
+export const getDomainsForRefName = (name: string): string[] | null => {
+ const list = loadMap()
+ const found = list.find(g => g.name.toLowerCase() === name.toLowerCase())
+ if (!found) return null
+ return found.patterns
+}
diff --git a/backend/tsconfig.json b/backend/tsconfig.json
index ba8edce4b..98f9f28e5 100644
--- a/backend/tsconfig.json
+++ b/backend/tsconfig.json
@@ -14,6 +14,7 @@
"incremental": true,
"skipLibCheck": true,
"inlineSources": true,
+ "resolveJsonModule": true,
// Set `sourceRoot` to "/" to strip the build path prefix
// from generated source code references.
diff --git a/web/app/lib/models/Entry.ts b/web/app/lib/models/Entry.ts
index 85faea4b6..c8c6250ac 100644
--- a/web/app/lib/models/Entry.ts
+++ b/web/app/lib/models/Entry.ts
@@ -1,5 +1,5 @@
export interface Entry {
- name: string
+ name: string | null
count: number
cc?: string
rgc?: string
diff --git a/web/app/pages/Project/View/Panels.tsx b/web/app/pages/Project/View/Panels.tsx
index b22af398c..769c0e0b9 100644
--- a/web/app/pages/Project/View/Panels.tsx
+++ b/web/app/pages/Project/View/Panels.tsx
@@ -985,7 +985,7 @@ const DetailsTable = ({
const onSortBy = (label: string) => {
const getValue = (entry: Entry): number | string => {
if (label === 'quantity') return entry.count
- if (label === 'name') return entry.name
+ if (label === 'name') return entry.name || ''
const extra = detailsExtraColumns?.find((c) => c.sortLabel === label)
if (extra) return extra.getSortValue(entry)
return 0
diff --git a/web/app/pages/Project/View/ViewProject.helpers.tsx b/web/app/pages/Project/View/ViewProject.helpers.tsx
index 18ec032b2..154be90bd 100644
--- a/web/app/pages/Project/View/ViewProject.helpers.tsx
+++ b/web/app/pages/Project/View/ViewProject.helpers.tsx
@@ -1559,6 +1559,7 @@ const typeNameMapping = (t: typeof i18next.t) => ({
exitPage: t('project.exitPages'),
lc: t('project.mapping.lc'),
ref: t('project.mapping.ref'),
+ refn: t('project.mapping.ref'),
keywords: t('project.mapping.keyword'),
dv: t('project.mapping.dv'),
br: t('project.mapping.br'),
diff --git a/web/app/pages/Project/View/ViewProject.tsx b/web/app/pages/Project/View/ViewProject.tsx
index 0a3421627..7ab5a9eb4 100644
--- a/web/app/pages/Project/View/ViewProject.tsx
+++ b/web/app/pages/Project/View/ViewProject.tsx
@@ -148,6 +148,7 @@ import {
removeDuplicates,
} from '~/utils/generic'
import { getItem, setItem } from '~/utils/localstorage'
+import { groupRefEntries } from '~/utils/referrers'
import routes from '~/utils/routes'
import { useCurrentProject, useProjectPassword } from '../../../providers/CurrentProjectProvider'
@@ -3421,8 +3422,11 @@ const ViewProjectContent = () => {
const { name: entryName, cc } = entry
if (errorsActiveTabs.location === 'lc') {
+ if (entryName === null) {
+ return <CCRow cc={null} language={language} />
+ }
const entryNameArray = entryName.split('-')
- const displayName = getLocaleDisplayName(entryName, language)
+ const displayName = getLocaleDisplayName(entryName || '', language)
return (
<CCRow
@@ -3434,7 +3438,7 @@ const ViewProjectContent = () => {
}
if (cc !== undefined) {
- return <CCRow cc={cc} name={entryName} language={language} />
+ return <CCRow cc={cc} name={entryName || undefined} language={language} />
}
return <CCRow cc={entryName} language={language} />
@@ -3769,7 +3773,7 @@ const ViewProjectContent = () => {
}
if (cc !== undefined) {
- return <CCRow cc={cc} name={entryName} language={language} />
+ return <CCRow cc={cc} name={entryName || undefined} language={language} />
}
return <CCRow cc={entryName} language={language} />
@@ -3954,7 +3958,14 @@ const ViewProjectContent = () => {
key={panelsActiveTabs.source}
icon={panelIconMapping.ref}
id={panelsActiveTabs.source}
- getFilterLink={getFilterLink}
+ getFilterLink={(column: string, value: string) => {
+ if (panelsActiveTabs.source === 'ref') {
+ // If grouped by name/domain (no refn filter active) -> filter by refn
+ const hasRefNameFilter = filters.some((f) => f.column === 'refn')
+ return getFilterLink(hasRefNameFilter ? 'ref' : 'refn', value)
+ }
+ return getFilterLink(column, value)
+ }}
name={t('project.trafficSources')}
tabs={trafficSourcesTabs}
onTabChange={(tab) =>
@@ -3967,7 +3978,15 @@ const ViewProjectContent = () => {
data={
panelsActiveTabs.source === 'keywords'
? keywords
- : panelsData.data[panelsActiveTabs.source]
+ : panelsActiveTabs.source === 'ref'
+ ? (() => {
+ const hasRefNameFilter = filters.some((f) => f.column === 'refn')
+ const raw = panelsData.data?.ref || []
+ return hasRefNameFilter
+ ? (raw as unknown as Entry[])
+ : (groupRefEntries(raw as any) as unknown as Entry[])
+ })()
+ : (panelsData.data[panelsActiveTabs.source] as unknown as Entry[])
}
valuesHeaderName={
panelsActiveTabs.source === 'keywords' ? t('project.clicks') : undefined
@@ -4130,7 +4149,7 @@ const ViewProjectContent = () => {
const { name: entryName, cc } = entry
if (cc !== undefined) {
- return <CCRow cc={cc} name={entryName} language={language} />
+ return <CCRow cc={cc} name={entryName || undefined} language={language} />
}
return <CCRow cc={entryName} language={language} />
diff --git a/web/app/pages/Project/View/components/RefRow.tsx b/web/app/pages/Project/View/components/RefRow.tsx
index 80ca02702..b8ab90087 100644
--- a/web/app/pages/Project/View/components/RefRow.tsx
+++ b/web/app/pages/Project/View/components/RefRow.tsx
@@ -2,15 +2,33 @@ import { LinkIcon } from 'lucide-react'
import { useMemo } from 'react'
import { useTranslation } from 'react-i18next'
+import { REFERRER_MAP, extractHostname } from '~/utils/referrers'
+
const RefRow = ({ rowName }: { rowName: string }) => {
const { t } = useTranslation('common')
- const { isUrl, url } = useMemo(() => {
+ const { isUrl, faviconHost } = useMemo(() => {
+ // Try parse as URL
try {
- const urlObj = new URL(rowName)
- return { isUrl: true, url: urlObj }
+ const urlObj = new URL(rowName as string)
+ return { isUrl: true, faviconHost: urlObj.hostname }
} catch {
- return { isUrl: false, url: null }
+ // Not a full URL. Try to resolve a hostname for grouped names/domains
+ const hostFromValue = extractHostname(rowName as string)
+ if (hostFromValue) {
+ return { isUrl: false, faviconHost: hostFromValue }
+ }
+
+ // Try map canonical name → representative domain (first literal domain pattern)
+ const mapping = REFERRER_MAP.find((m) => (rowName || '').toLowerCase() === m.name.toLowerCase())
+ if (mapping) {
+ const literal =
+ mapping.patterns.find((p) => !['[', ']', '{', '}', '*'].some((c) => p.includes(c))) || mapping.patterns[0]
+ const safe = literal.replace(/\[[^\]]+\]/g, 'com') // e.g., google.[a-z]{2,3} -> google.com
+ return { isUrl: false, faviconHost: safe }
+ }
+
+ return { isUrl: false, faviconHost: null as any }
}
}, [rowName])
@@ -27,10 +45,10 @@ const RefRow = ({ rowName }: { rowName: string }) => {
return (
<div className='scrollbar-thin hover-always-overflow flex items-center'>
- {isUrl ? (
+ {faviconHost ? (
<img
className='float-left mr-1.5 size-5'
- src={`https://icons.duckduckgo.com/ip3/${url?.hostname}.ico`}
+ src={`https://icons.duckduckgo.com/ip3/${faviconHost}.ico`}
loading='lazy'
alt=''
aria-hidden='true'
diff --git a/web/app/pages/Project/View/utils/filters.tsx b/web/app/pages/Project/View/utils/filters.tsx
index bb59dbbc6..55f034a72 100644
--- a/web/app/pages/Project/View/utils/filters.tsx
+++ b/web/app/pages/Project/View/utils/filters.tsx
@@ -25,6 +25,7 @@ const validFilters = [
'exitPage',
'lc',
'ref',
+ 'refn',
'dv',
'br',
'brv',
diff --git a/web/app/utils/referrers.map.json b/web/app/utils/referrers.map.json
new file mode 100644
index 000000000..d5a057806
--- /dev/null
+++ b/web/app/utils/referrers.map.json
@@ -0,0 +1,21 @@
+[
+ { "name": "Linktree", "patterns": ["linktr.ee"] },
+ { "name": "Perplexity", "patterns": ["perplexity.ai"] },
+ { "name": "Yandex", "patterns": ["yandex.ru", "yandex.com", "yandex.kz", "yandex.by", "ya.ru", "yandex.eu", "yandex.fr"] },
+ { "name": "GitHub", "patterns": ["github.com"] },
+ { "name": "Google", "patterns": ["google.com", "doubleclick.net"] },
+ { "name": "Bing", "patterns": ["bing.com", "ntp.msn.com"] },
+ { "name": "DuckDuckGo", "patterns": ["duckduckgo.com", "ddg.gg"] },
+ { "name": "Reddit", "patterns": ["reddit.com", "android-app://com.reddit.frontpage/"] },
+ { "name": "YouTube", "patterns": ["youtube.com", "youtu.be"] },
+ { "name": "Stack Overflow", "patterns": ["stackoverflow.com"] },
+ { "name": "Hacker News", "patterns": ["news.ycombinator.com"] },
+ { "name": "Medium", "patterns": ["medium.com"] },
+ { "name": "Twitter", "patterns": ["twitter.com", "x.com", "t.co"] },
+ { "name": "Facebook", "patterns": ["facebook.com", "m.facebook.com"] },
+ { "name": "LinkedIn", "patterns": ["linkedin.com"] },
+ { "name": "Product Hunt", "patterns": ["producthunt.com"] },
+ { "name": "Microsoft Teams", "patterns": ["teams.microsoft.com", "statics.teams.cdn.office.net"] },
+ { "name": "ChatGPT", "patterns": ["chatgpt.com"] },
+ { "name": "Claude", "patterns": ["claude.ai"] }
+]
diff --git a/web/app/utils/referrers.ts b/web/app/utils/referrers.ts
new file mode 100644
index 000000000..f5a82c2c0
--- /dev/null
+++ b/web/app/utils/referrers.ts
@@ -0,0 +1,87 @@
+/*
+ Canonical referrer name mapping and helpers.
+
+ Group referrers by a friendly name when possible (e.g., *.wikipedia.org -> "Wikipedia").
+ Otherwise, group by hostname (strips leading www.).
+*/
+
+import MAP from './referrers.map.json'
+
+export type ReferrerMapping = {
+ name: string
+ patterns: string[]
+}
+
+// Minimal curated map; extend as needed via JSON
+export const REFERRER_MAP: ReferrerMapping[] = MAP as ReferrerMapping[]
+
+export const extractHostname = (value: string | null | undefined): string | null => {
+ if (!value) return null
+ try {
+ const url = new URL(value)
+ return url.hostname.toLowerCase()
+ } catch {
+ // If it's already a hostname (no protocol), return as lowercased
+ const trimmed = value.trim().toLowerCase()
+ if (trimmed.includes(' ')) return null
+ if (trimmed.includes('.') || /^[a-z0-9-]+\.[a-z]{2,}$/.test(trimmed)) return trimmed
+ return null
+ }
+}
+
+const normaliseHost = (host: string): string => host.replace(/^www\./, '')
+
+const matchByMap = (host: string): string | null => {
+ for (const { name, patterns } of REFERRER_MAP) {
+ for (const p of patterns) {
+ // Exact or subdomain match only
+ if (host === p || host.endsWith(`.${p}`)) {
+ return name
+ }
+ }
+ }
+ return null
+}
+
+export const getCanonicalRefGroup = (refValue: string | null | undefined): { key: string; name: string } | null => {
+ const value = (refValue || '').trim()
+ // If a non-http(s) scheme is present, keep as-is (do not group)
+ const scheme = value.match(/^([a-z][a-z0-9+.-]*):/i)?.[1]
+ if (scheme && !/^https?$/i.test(scheme)) {
+ return null
+ }
+
+ const host = extractHostname(value)
+ if (!host) return null
+ const plainHost = normaliseHost(host)
+ const mapped = matchByMap(plainHost)
+ if (mapped) return { key: mapped, name: mapped }
+ return { key: plainHost, name: plainHost }
+}
+
+export type Entry = { name: string | null; count: number; [k: string]: any }
+
+// Group a list of ref entries by canonical name or hostname.
+export const groupRefEntries = (entries: Entry[]): Entry[] => {
+ const acc = new Map<string, number>()
+ for (const e of entries) {
+ if (e.name === null) {
+ acc.set('null', (acc.get('null') || 0) + e.count)
+ continue
+ }
+ const group = getCanonicalRefGroup(e.name)
+ const key = group?.key || e.name
+ acc.set(key, (acc.get(key) || 0) + e.count)
+ }
+ // Convert map to Entry[]
+ const list: Entry[] = []
+ for (const [key, count] of acc.entries()) {
+ if (key === 'null') {
+ list.push({ name: null, count })
+ } else {
+ list.push({ name: key, count })
+ }
+ }
+ // Sort desc by count
+ return list.sort((a, b) => b.count - a.count)
+}