📈 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!
TypeScript chartsclickhousedockergdprgoogle-analyticsmetricsmonitoringmysqlnestjsprivacyredisself-hostedselfhostedstatisticstailwindcssweb-analyticswebanalyticswebsite
Branded vs Non-branded traffic analytics
Blue Mousef0327dd22f04
diff --git a/backend/apps/cloud/src/project/dto/project.dto.ts b/backend/apps/cloud/src/project/dto/project.dto.tsindex 49b1b4a02..1496aaef2 100644--- a/backend/apps/cloud/src/project/dto/project.dto.ts+++ b/backend/apps/cloud/src/project/dto/project.dto.ts@@ -5,6 +5,7 @@ import {IsEnum,IsOptional,IsArray,+ IsString,IsUrl,MaxLength,ValidateIf,@@ -87,4 +88,15 @@ export class ProjectDTO {@IsUrl({}, { message: 'websiteUrl must be a valid URL' })@MaxLength(512)websiteUrl?: string | null++ @ApiProperty({+ example: ['swetrix', 'swetrix analytics'],+ required: false,+ description:+ 'Brand keywords used to classify search queries as branded vs non-branded traffic.',+ })+ @IsOptional()+ @IsArray()+ @IsString({ each: true })+ brandKeywords?: string[] | null}diff --git a/backend/apps/cloud/src/project/entity/project.entity.ts b/backend/apps/cloud/src/project/entity/project.entity.tsindex 7f2758ed9..e023d7769 100644--- a/backend/apps/cloud/src/project/entity/project.entity.ts+++ b/backend/apps/cloud/src/project/entity/project.entity.ts@@ -179,4 +179,8 @@ export class Project {@ApiProperty()@Column('varchar', { nullable: true, default: null, length: 512 })websiteUrl: string | null++ @ApiProperty()+ @Column('text', { nullable: true, default: null })+ brandKeywords: string | null}diff --git a/backend/apps/cloud/src/project/project.controller.ts b/backend/apps/cloud/src/project/project.controller.tsindex 79cde1fb9..758fe3b53 100644--- a/backend/apps/cloud/src/project/project.controller.ts+++ b/backend/apps/cloud/src/project/project.controller.ts@@ -1805,11 +1805,28 @@ export class ProjectController {: null}+ if (projectDTO.brandKeywords !== undefined) {+ project.brandKeywords =+ Array.isArray(projectDTO.brandKeywords) &&+ projectDTO.brandKeywords.length > 0+ ? JSON.stringify(projectDTO.brandKeywords.map((k) => _trim(k)))+ : null+ }+await this.projectService.update({ id }, _omit(project, ['share', 'admin']))await deleteProjectRedis(id)- return _omit(project, ['admin', 'passwordHash', 'share'])+ const result = _omit(project, ['admin', 'passwordHash', 'share']) as any+ if (result.brandKeywords) {+ try {+ result.brandKeywords = JSON.parse(result.brandKeywords)+ } catch {+ result.brandKeywords = null+ }+ }++ return result}// The routes related to sharing projects feature@@ -1931,6 +1948,15 @@ export class ProjectController {const isManagerRole = role === 'owner' || role === 'admin'const isViewerRole = role === 'viewer'+ let parsedBrandKeywords: string[] | null = null+ if (project.brandKeywords) {+ try {+ parsedBrandKeywords = JSON.parse(project.brandKeywords)+ } catch {+ parsedBrandKeywords = null+ }+ }+return {..._omit(project, ['admin',@@ -1944,6 +1970,7 @@ export class ProjectController {!isManagerRole && !isViewerRole && 'share',!isManagerRole && 'captchaSecretKey',]),+ brandKeywords: parsedBrandKeywords,isAccessConfirmed,isLocked: !!project.admin?.dashboardBlockReason,isDataExists,diff --git a/backend/migrations/mysql/2026_04_05_brand_keywords.sql b/backend/migrations/mysql/2026_04_05_brand_keywords.sqlnew file mode 100644index 000000000..1da7b3454--- /dev/null+++ b/backend/migrations/mysql/2026_04_05_brand_keywords.sql@@ -0,0 +1 @@+ALTER TABLE `project` ADD COLUMN `brandKeywords` text DEFAULT NULL;diff --git a/web/app/api/api.server.ts b/web/app/api/api.server.tsindex 380351e0e..b8a13c0a8 100644--- a/web/app/api/api.server.ts+++ b/web/app/api/api.server.ts@@ -2511,7 +2511,7 @@ export async function getGSCDashboardServer(// MARK: GSC Details API (Keyword-to-Page mapping)// ============================================================================-export interface GSCDetailsResponse {+interface GSCDetailsResponse {type: 'queries' | 'pages' | 'none'data: Array<{name?: stringdiff --git a/web/app/hooks/useAnalyticsProxy.ts b/web/app/hooks/useAnalyticsProxy.tsindex b1bea1157..d282dd738 100644--- a/web/app/hooks/useAnalyticsProxy.ts+++ b/web/app/hooks/useAnalyticsProxy.ts@@ -26,7 +26,6 @@ import type {UserFlowResponse,GSCKeywordsResponse,GSCDashboardResponse,- GSCDetailsResponse,RevenueStatus,RevenueDataResponse,OverallObject,diff --git a/web/app/lib/models/Project.ts b/web/app/lib/models/Project.tsindex f63ed9f9c..e032a881e 100644--- a/web/app/lib/models/Project.ts+++ b/web/app/lib/models/Project.ts@@ -224,4 +224,5 @@ export interface Project {isPinned?: booleanrevenueCurrency?: stringwebsiteUrl?: string | null+ brandKeywords?: string[] | null}diff --git a/web/app/pages/Project/Settings/ProjectSettings.tsx b/web/app/pages/Project/Settings/ProjectSettings.tsxindex 6977b7585..4f63cd23a 100644--- a/web/app/pages/Project/Settings/ProjectSettings.tsx+++ b/web/app/pages/Project/Settings/ProjectSettings.tsx@@ -286,6 +286,7 @@ interface Form extends Partial<Project> {ipBlacklist: string | nullcountryBlacklist: string[]websiteUrl?: string | null+ brandKeywords?: string}const DEFAULT_PROJECT_NAME = 'Untitled Project'@@ -322,6 +323,7 @@ const ProjectSettings = () => {(initialProject.botsProtectionLevel as 'off' | 'basic') || 'basic',gscPropertyUri: initialProject.gscPropertyUri || null,websiteUrl: initialProject.websiteUrl || null,+ brandKeywords: initialProject.brandKeywords?.join(', ') || '',}))const [validated, setValidated] = useState(false)const [errors, setErrors] = useState<{@@ -702,6 +704,8 @@ const ProjectSettings = () => {formData.set('countryBlacklist', JSON.stringify(data.countryBlacklist))if (data.websiteUrl !== undefined)formData.set('websiteUrl', data.websiteUrl || '')+ if (data.brandKeywords !== undefined)+ formData.set('brandKeywords', data.brandKeywords || '')fetcher.submit(formData, { method: 'post' })}diff --git a/web/app/pages/Project/Settings/tabs/General.tsx b/web/app/pages/Project/Settings/tabs/General.tsxindex 3f855e579..eb3c3b22f 100644--- a/web/app/pages/Project/Settings/tabs/General.tsx+++ b/web/app/pages/Project/Settings/tabs/General.tsx@@ -8,6 +8,7 @@ interface GeneralProps {name?: stringid?: stringwebsiteUrl?: string | null+ brandKeywords?: string}errors: {name?: string@@ -60,6 +61,16 @@ const General = ({onChange={handleInput}error={beenSubmitted ? errors.websiteUrl : null}/>+ <Input+ name='brandKeywords'+ label={t('project.settings.brandKeywords')}+ hint={t('project.settings.brandKeywordsHint')}+ value={form.brandKeywords || ''}+ placeholder={t('project.settings.brandKeywordsPlaceholder')}+ className='mt-4'+ onChange={handleInput}+ error={null}+ /><Inputname='sharableLink'label={t('project.settings.sharableLink')}diff --git a/web/app/pages/Project/tabs/SEO/SEOView.tsx b/web/app/pages/Project/tabs/SEO/SEOView.tsxindex f93c0819b..4d76e8942 100644--- a/web/app/pages/Project/tabs/SEO/SEOView.tsx+++ b/web/app/pages/Project/tabs/SEO/SEOView.tsx@@ -8,7 +8,7 @@ import {MapPinIcon,} from '@phosphor-icons/react'import type { ChartOptions } from 'billboard.js'-import { area } from 'billboard.js'+import { area, donut } from 'billboard.js'import * as d3 from 'd3'import dayjs from 'dayjs'import isoWeek from 'dayjs/plugin/isoWeek'@@ -32,6 +32,8 @@ dayjs.extend(quarterOfYear)import { useGSCDashboardProxy } from '~/hooks/useAnalyticsProxy'import type { TimeBucket } from '~/lib/constants'import type { Entry } from '~/lib/models/Entry'+import type { Project } from '~/lib/models/Project'+import BillboardChart from '~/ui/BillboardChart'import DashboardHeader from '~/pages/Project/View/components/DashboardHeader'import { MainChart } from '~/pages/Project/View/components/MainChart'import Filters from '~/pages/Project/View/components/Filters'@@ -151,13 +153,203 @@ const aggregateDateSeries = (})}+const deriveBrandKeywords = (project: Project): string[] => {+ if (project.brandKeywords?.length) {+ return project.brandKeywords.map((k) => k.toLowerCase().trim())+ }++ const keywords: string[] = []++ if (project.websiteUrl) {+ try {+ const url = new URL(project.websiteUrl)+ const domain = url.hostname.replace(/^www\./, '')+ const parts = domain.split('.')+ if (parts.length >= 2) {+ const main = parts[parts.length - 2]+ if (main && main.length >= 3) keywords.push(main.toLowerCase())+ }+ } catch {+ // invalid URL, skip+ }+ }++ if (project.name) {+ const name = project.name.toLowerCase().trim()+ if (name.length >= 3 && !keywords.includes(name)) {+ keywords.push(name)+ }+ }++ return keywords+}++const classifyBrandedTraffic = (+ queries: Array<{ name: string; count: number; impressions?: number }>,+ brandKeywords: string[],+): { branded: number; nonBranded: number } => {+ let branded = 0+ let nonBranded = 0++ for (const q of queries) {+ const lower = q.name.toLowerCase()+ const isBranded = brandKeywords.some((kw) => lower.includes(kw))+ if (isBranded) {+ branded += q.count+ } else {+ nonBranded += q.count+ }+ }++ return { branded, nonBranded }+}++const COMPACT_MAX_ENTRIES = 10+const COMPACT_ENTRIES_PER_COL = 5++interface CompactReferralPanelProps {+ title: string+ data: Entry[]+ icon: React.ReactNode+ rowMapper: (entry: any) => React.ReactNode+}++const CompactReferralPanel = ({+ title,+ data,+ icon,+ rowMapper,+}: CompactReferralPanelProps) => {+ const { t } = useTranslation('common')+ const total = useMemo(() => data.reduce((sum, e) => sum + e.count, 0), [data])++ const { displayEntries, othersCount } = useMemo(() => {+ if (data.length <= COMPACT_MAX_ENTRIES) {+ return { displayEntries: data, othersCount: 0 }+ }+ const top = data.slice(0, COMPACT_MAX_ENTRIES - 1)+ const rest = data.slice(COMPACT_MAX_ENTRIES - 1)+ return {+ displayEntries: top,+ othersCount: rest.reduce((sum, e) => sum + e.count, 0),+ }+ }, [data])++ const allRows: Array<{ entry: Entry; isOther: boolean }> = useMemo(() => {+ const rows = displayEntries.map((e) => ({ entry: e, isOther: false }))+ if (othersCount > 0) {+ rows.push({+ entry: { name: t('project.seo.others'), count: othersCount },+ isOther: true,+ })+ }+ return rows+ }, [displayEntries, othersCount, t])++ const col1 = allRows.slice(0, COMPACT_ENTRIES_PER_COL)+ const col2 = allRows.slice(COMPACT_ENTRIES_PER_COL)++ if (_isEmpty(data)) {+ return (+ <div className='overflow-hidden rounded-lg border border-gray-200 bg-white px-4 py-3 dark:border-slate-800/60 dark:bg-slate-900/25'>+ <div className='flex items-center gap-2'>+ {icon}+ <Text size='sm' weight='semibold'>+ {title}+ </Text>+ </div>+ <div className='flex h-32 items-center justify-center'>+ <Text+ size='xs'+ colour='inherit'+ className='text-gray-400 dark:text-gray-500'+ >+ {t('project.noParamData')}+ </Text>+ </div>+ </div>+ )+ }++ const renderRow = (+ { entry, isOther }: { entry: Entry; isOther: boolean },+ idx: number,+ ) => {+ const perc = total > 0 ? _round((entry.count / total) * 100, 0) : 0+ return (+ <div+ key={isOther ? 'others' : `${entry.name}-${idx}`}+ className='group relative flex h-7 items-center justify-between rounded-sm px-1.5 hover:bg-gray-50 dark:hover:bg-slate-900/60'+ >+ <div+ className='absolute inset-0 rounded-sm bg-blue-50 dark:bg-blue-900/30'+ style={{ width: `${perc}%` }}+ />+ <div className='relative z-10 flex min-w-0 flex-1 items-center gap-1.5'>+ {isOther ? (+ <div className='size-5 shrink-0' />+ ) : (+ <div className='min-w-0'>{rowMapper(entry)}</div>+ )}+ {isOther ? (+ <Text+ size='xs'+ colour='inherit'+ truncate+ className='text-gray-500 italic dark:text-gray-400'+ >+ {entry.name}+ </Text>+ ) : null}+ </div>+ <div className='relative z-10 flex min-w-fit items-center justify-end pl-2'>+ <Text+ size='xs'+ colour='inherit'+ className='mr-1.5 hidden text-gray-500 group-hover:inline dark:text-gray-400'+ >+ ({perc}%)+ </Text>+ <Text size='xs' weight='medium'>+ {nFormatter(entry.count, 1)}+ </Text>+ </div>+ </div>+ )+ }++ return (+ <div className='overflow-hidden rounded-lg border border-gray-200 bg-white px-4 py-3 dark:border-slate-800/60 dark:bg-slate-900/25'>+ <div className='mb-2 flex items-center justify-between'>+ <div className='flex items-center gap-2'>+ {icon}+ <Text size='sm' weight='semibold'>+ {title}+ </Text>+ </div>+ <Text size='sm' weight='medium' className='tabular-nums'>+ {nFormatter(total, 1)}+ </Text>+ </div>+ <div className='grid grid-cols-2 gap-x-3'>+ <div className='space-y-0.5'>+ {col1.map((row, i) => renderRow(row, i))}+ </div>+ <div className='space-y-0.5'>+ {col2.map((row, i) => renderRow(row, i + COMPACT_ENTRIES_PER_COL))}+ </div>+ </div>+ </div>+ )+}+const SEOViewInner = ({ projectId, tnMapping }: SEOViewProps) => {const {t,i18n: { language },} = useTranslation('common')const { theme } = useTheme()- const { id } = useCurrentProject()+ const { id, project } = useCurrentProject()const {period,timezone,@@ -386,6 +578,66 @@ const SEOViewInner = ({ projectId, tnMapping }: SEOViewProps) => {[data?.topDevices],)+ const brandKeywords = useMemo(+ () => (project ? deriveBrandKeywords(project) : []),+ [project],+ )++ const brandedTraffic = useMemo(+ () => classifyBrandedTraffic(data?.topQueries || [], brandKeywords),+ [data?.topQueries, brandKeywords],+ )++ const donutChartOptions: ChartOptions = useMemo(() => {+ const total = brandedTraffic.branded + brandedTraffic.nonBranded+ if (total === 0) return {}++ const brandedLabel = t('project.seo.branded')+ const nonBrandedLabel = t('project.seo.nonBranded')++ return {+ data: {+ columns: [+ [brandedLabel, brandedTraffic.branded],+ [nonBrandedLabel, brandedTraffic.nonBranded],+ ],+ type: donut(),+ colors: {+ [brandedLabel]: theme === 'dark' ? '#818cf8' : '#6366f1',+ [nonBrandedLabel]: theme === 'dark' ? '#475569' : '#94a3b8',+ },+ },+ donut: {+ title: `${total > 0 ? _round((brandedTraffic.branded / total) * 100, 0) : 0}%`,+ label: {+ show: false,+ },+ width: 16,+ },+ transition: { duration: 200 },+ resize: { auto: true },+ legend: {+ show: true,+ position: 'bottom',+ item: {+ tile: { type: 'circle', width: 8, r: 4 },+ },+ },+ tooltip: {+ format: {+ value: (value: number, ratio: number) => {+ const pct = (ratio * 100).toFixed(1)+ return `${nFormatter(value, 1)} (${pct}%)`+ },+ },+ },+ size: {+ height: 180,+ },+ padding: { top: 0, bottom: 0, left: 0, right: 0 },+ }+ }, [brandedTraffic, t, theme])+const countryRowMapper = useCallback((entry: any) => <CCRow cc={entry.name} language={language} />,[language],@@ -678,6 +930,7 @@ const SEOViewInner = ({ projectId, tnMapping }: SEOViewProps) => {{filters.length > 0 ? (<Filters className='mb-3' tnMapping={tnMapping} />) : null}+<div className='relative overflow-hidden rounded-lg border border-gray-200 bg-white p-4 dark:border-slate-800/60 dark:bg-slate-900/25'><div className='mb-3 flex w-full items-center justify-end gap-1 lg:absolute lg:top-2 lg:right-2 lg:mb-0 lg:w-auto lg:justify-normal'><Dropdown@@ -784,29 +1037,44 @@ const SEOViewInner = ({ projectId, tnMapping }: SEOViewProps) => {) : null}</div>- <div className='mt-3 grid grid-cols-1 gap-3 sm:grid-cols-2'>- <Panel- name={t('project.seo.searchEngines')}+ <div className='mt-3 grid grid-cols-1 gap-3 lg:grid-cols-[1fr_1fr_minmax(0,0.7fr)]'>+ <CompactReferralPanel+ title={t('project.seo.searchEngines')}data={searchEngineEntries}icon={panelIconMapping.ref}- id='seo-search-engines'- activeTabId='searchEngine'- disableRowClickrowMapper={refRowMapper}- getFilterLink={noopFilterLink}- valuesHeaderName={t('project.visitors')}/>- <Panel- name={t('project.seo.aiReferrals')}+ <CompactReferralPanel+ title={t('project.seo.aiReferrals')}data={aiReferralEntries}icon={<RobotIcon className='h-5 w-5' />}- id='seo-ai-referrals'- activeTabId='aiReferral'- disableRowClickrowMapper={refRowMapper}- getFilterLink={noopFilterLink}- valuesHeaderName={t('project.visitors')}/>+ <div className='overflow-hidden rounded-lg border border-gray-200 bg-white px-4 py-3 dark:border-slate-800/60 dark:bg-slate-900/25'>+ <div className='mb-1 flex items-center gap-2'>+ <MagnifyingGlassIcon className='size-5 text-gray-500 dark:text-gray-400' />+ <Text size='sm' weight='semibold'>+ {t('project.seo.brandedTraffic')}+ </Text>+ </div>+ {brandedTraffic.branded + brandedTraffic.nonBranded > 0 ? (+ <BillboardChart+ options={donutChartOptions}+ className='[&_.bb-chart-arc]:text-xs [&_.bb-chart-arcs-title]:fill-gray-900 [&_.bb-chart-arcs-title]:text-lg [&_.bb-chart-arcs-title]:font-semibold dark:[&_.bb-chart-arcs-title]:fill-gray-100'+ deps={[brandedTraffic, theme]}+ />+ ) : (+ <div className='flex h-32 items-center justify-center'>+ <Text+ size='xs'+ colour='inherit'+ className='text-gray-400 dark:text-gray-500'+ >+ {t('project.seo.noBrandData')}+ </Text>+ </div>+ )}+ </div></div><div className='mt-3 grid grid-cols-1 gap-3 sm:grid-cols-2'>diff --git a/web/app/routes/projects.settings.$id.tsx b/web/app/routes/projects.settings.$id.tsxindex 3edf4578a..703935440 100644--- a/web/app/routes/projects.settings.$id.tsx+++ b/web/app/routes/projects.settings.$id.tsx@@ -115,6 +115,7 @@ export async function action({ request, params }: ActionFunctionArgs) {?.toString()const countryBlacklist = formData.get('countryBlacklist')?.toString()const websiteUrl = formData.get('websiteUrl')?.toString()+ const brandKeywords = formData.get('brandKeywords')?.toString()const captchaDifficulty = formData.get('captchaDifficulty')?.toString()const fieldErrors: ProjectSettingsActionData['fieldErrors'] = {}@@ -150,6 +151,13 @@ export async function action({ request, params }: ActionFunctionArgs) {? JSON.parse(countryBlacklist): []if (websiteUrl !== undefined) updateData.websiteUrl = websiteUrl || null+ if (brandKeywords !== undefined)+ updateData.brandKeywords = brandKeywords+ ? brandKeywords+ .split(',')+ .map((k) => k.trim())+ .filter(Boolean)+ : nullif (captchaDifficulty !== undefined)updateData.captchaDifficulty = Number(captchaDifficulty)diff --git a/web/public/locales/en.json b/web/public/locales/en.jsonindex 95979fc64..65a4f3101 100644--- a/web/public/locales/en.json+++ b/web/public/locales/en.json@@ -1410,7 +1410,12 @@"benchmark": "Benchmark","searchPages": "Search pages","searchQueries": "Search queries",- "noProperty": "No Search Console property selected. Go to Settings to select one."+ "noProperty": "No Search Console property selected. Go to Settings to select one.",+ "branded": "Branded",+ "nonBranded": "Non-branded",+ "brandedTraffic": "Branded traffic",+ "others": "Others",+ "noBrandData": "No query data"},"passwordProtectedHint": "Please enter the password to view this dashboard.","captchaCompletions": "CAPTCHA completions",@@ -1895,6 +1900,9 @@"websiteUrl": "Website URL","websiteUrlPlaceholder": "https://example.com","websiteUrlHint": "Optional. Your website URL is used to display a favicon next to your project name and to make page paths clickable in analytics.",+ "brandKeywords": "Brand keywords",+ "brandKeywordsPlaceholder": "swetrix, swetrix analytics",+ "brandKeywordsHint": "Comma-separated keywords to classify search queries as branded traffic. If empty, auto-detected from your website URL and project name.","invalidUrl": "Please enter a valid URL (e.g., https://example.com)","origins": "Allowed origins","originsHint": "A list of origins (domains) which are allowed to use script with your ProjectID, separated by commas.\nLeave it empty to allow all origins (default setting).\nExample: cornell.edu, app.example.com, *.gov.ua",