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!

Pull devices & countries from GSC

Blue Mousee4798f26f387
diff --git a/backend/apps/cloud/src/project/gsc.service.ts b/backend/apps/cloud/src/project/gsc.service.ts
index b82e765ba..10afa470a 100644
--- a/backend/apps/cloud/src/project/gsc.service.ts
+++ b/backend/apps/cloud/src/project/gsc.service.ts
@@ -282,7 +282,9 @@ export class GSCService {
let dimension
if (column === 'pg') dimension = 'page'
else if (column === 'keywords') dimension = 'query'
- else continue // Ignore unsupported dimensions for GSC
+ else if (column === 'country') dimension = 'country'
+ else if (column === 'device') dimension = 'device'
+ else continue
let operator = 'equals'
if (isExclusive) {
@@ -588,6 +590,132 @@ export class GSCService {
}
}
+ async getTopCountries(
+ pid: string,
+ from: string,
+ to: string,
+ limit = 50,
+ offset = 0,
+ filtersStr?: string,
+ ): Promise<
+ {
+ country: string
+ clicks: number
+ impressions: number
+ ctr: number
+ position: number
+ }[]
+ > {
+ const tokens = await this.ensurePropertyLinked(pid)
+ const auth = await this.getAuthedClientForPid(pid)
+ const sc = searchconsole({ version: 'v1', auth })
+
+ const startDate = dayjs(from).format('YYYY-MM-DD')
+ const endDate = dayjs(to).format('YYYY-MM-DD')
+
+ const dimensionFilterGroups = this.parseFilters(filtersStr) || []
+
+ try {
+ const { data } = await sc.searchanalytics.query({
+ siteUrl: tokens.property_uri as string,
+ requestBody: {
+ startDate,
+ endDate,
+ dimensions: ['country'],
+ rowLimit: limit,
+ startRow: offset,
+ dataState: 'all',
+ ...(dimensionFilterGroups.length > 0
+ ? { dimensionFilterGroups }
+ : {}),
+ },
+ })
+
+ const rows = (data.rows || []) as Array<{
+ keys: string[]
+ clicks?: number
+ impressions?: number
+ ctr?: number
+ position?: number
+ }>
+
+ return rows.map((row) => ({
+ country: (row.keys?.[0] || '').toLowerCase(),
+ clicks: Math.round(row.clicks || 0),
+ impressions: Math.round(row.impressions || 0),
+ ctr: Number(Number((row.ctr || 0) * 100).toFixed(2)),
+ position: Number(Number(row.position || 0).toFixed(1)),
+ }))
+ } catch {
+ throw new InternalServerErrorException(
+ 'Failed to fetch top countries from Search Console',
+ )
+ }
+ }
+
+ async getTopDevices(
+ pid: string,
+ from: string,
+ to: string,
+ limit = 50,
+ offset = 0,
+ filtersStr?: string,
+ ): Promise<
+ {
+ device: string
+ clicks: number
+ impressions: number
+ ctr: number
+ position: number
+ }[]
+ > {
+ const tokens = await this.ensurePropertyLinked(pid)
+ const auth = await this.getAuthedClientForPid(pid)
+ const sc = searchconsole({ version: 'v1', auth })
+
+ const startDate = dayjs(from).format('YYYY-MM-DD')
+ const endDate = dayjs(to).format('YYYY-MM-DD')
+
+ const dimensionFilterGroups = this.parseFilters(filtersStr) || []
+
+ try {
+ const { data } = await sc.searchanalytics.query({
+ siteUrl: tokens.property_uri as string,
+ requestBody: {
+ startDate,
+ endDate,
+ dimensions: ['device'],
+ rowLimit: limit,
+ startRow: offset,
+ dataState: 'all',
+ ...(dimensionFilterGroups.length > 0
+ ? { dimensionFilterGroups }
+ : {}),
+ },
+ })
+
+ const rows = (data.rows || []) as Array<{
+ keys: string[]
+ clicks?: number
+ impressions?: number
+ ctr?: number
+ position?: number
+ }>
+
+ return rows.map((row) => ({
+ device: (row.keys?.[0] || '').toLowerCase(),
+ clicks: Math.round(row.clicks || 0),
+ impressions: Math.round(row.impressions || 0),
+ ctr: Number(Number((row.ctr || 0) * 100).toFixed(2)),
+ position: Number(Number(row.position || 0).toFixed(1)),
+ }))
+ } catch {
+ throw new InternalServerErrorException(
+ 'Failed to fetch top devices from Search Console',
+ )
+ }
+ }
+
async getDashboard(
pid: string,
from: string,
@@ -613,14 +741,23 @@ export class GSCService {
.subtract(durationMs, 'millisecond')
.format('YYYY-MM-DD HH:mm:ss')
- const [summary, previousSummary, dateSeries, topPages, topQueries] =
- await Promise.all([
- this.getSummary(pid, from, to, filtersStr),
- this.getSummary(pid, prevFrom, prevTo, filtersStr).catch(() => null),
- this.getDateSeries(pid, from, to, timeBucket, filtersStr),
- this.getTopPages(pid, from, to, 50, 0, filtersStr),
- this.getKeywords(pid, from, to, 50, 0, filtersStr),
- ])
+ const [
+ summary,
+ previousSummary,
+ dateSeries,
+ topPages,
+ topQueries,
+ topCountries,
+ topDevices,
+ ] = await Promise.all([
+ this.getSummary(pid, from, to, filtersStr),
+ this.getSummary(pid, prevFrom, prevTo, filtersStr).catch(() => null),
+ this.getDateSeries(pid, from, to, timeBucket, filtersStr),
+ this.getTopPages(pid, from, to, 50, 0, filtersStr),
+ this.getKeywords(pid, from, to, 50, 0, filtersStr),
+ this.getTopCountries(pid, from, to, 50, 0, filtersStr),
+ this.getTopDevices(pid, from, to, 50, 0, filtersStr),
+ ])
return {
notConnected: false,
@@ -629,6 +766,8 @@ export class GSCService {
dateSeries,
topPages,
topQueries,
+ topCountries,
+ topDevices,
}
}
}
diff --git a/web/app/api/api.server.ts b/web/app/api/api.server.ts
index 1a40e2c64..380351e0e 100644
--- a/web/app/api/api.server.ts
+++ b/web/app/api/api.server.ts
@@ -2434,6 +2434,22 @@ interface GSCTopQueryEntry {
ctr: number
}
+interface GSCTopCountryEntry {
+ country: string
+ clicks: number
+ impressions: number
+ ctr: number
+ position: number
+}
+
+interface GSCTopDeviceEntry {
+ device: string
+ clicks: number
+ impressions: number
+ ctr: number
+ position: number
+}
+
export interface GSCDashboardResponse {
notConnected?: boolean
noProperty?: boolean
@@ -2452,6 +2468,8 @@ export interface GSCDashboardResponse {
dateSeries?: GSCDateSeriesEntry[]
topPages?: GSCTopPageEntry[]
topQueries?: GSCTopQueryEntry[]
+ topCountries?: GSCTopCountryEntry[]
+ topDevices?: GSCTopDeviceEntry[]
}
export async function getGSCDashboardServer(
diff --git a/web/app/pages/Project/tabs/SEO/SEOView.tsx b/web/app/pages/Project/tabs/SEO/SEOView.tsx
index d36dba64e..47af31929 100644
--- a/web/app/pages/Project/tabs/SEO/SEOView.tsx
+++ b/web/app/pages/Project/tabs/SEO/SEOView.tsx
@@ -5,6 +5,7 @@ import {
PlugIcon,
RobotIcon,
MagnifyingGlassIcon,
+ MapPinIcon,
} from '@phosphor-icons/react'
import type { ChartOptions } from 'billboard.js'
import { area } from 'billboard.js'
@@ -39,16 +40,22 @@ import {
useViewProjectContext,
useRefreshTriggers,
} from '~/pages/Project/View/ViewProject'
-import { panelIconMapping } from '~/pages/Project/View/ViewProject.helpers'
+import {
+ panelIconMapping,
+ getDeviceRowMapper,
+} from '~/pages/Project/View/ViewProject.helpers'
import { MetricCard } from '~/pages/Project/tabs/Traffic/MetricCards'
import RefRow from '~/pages/Project/tabs/Traffic/RefRow'
+import CCRow from '~/pages/Project/View/components/CCRow'
import { useCurrentProject } from '~/providers/CurrentProjectProvider'
+import { useTheme } from '~/providers/ThemeProvider'
import type { ProjectLoaderData } from '~/routes/projects.$id'
import Checkbox from '~/ui/Checkbox'
import Dropdown from '~/ui/Dropdown'
import Loader from '~/ui/Loader'
import { Text } from '~/ui/Text'
import { nFormatter } from '~/utils/generic'
+import countries from '~/utils/isoCountries'
import { getSearchEngineReferrals, getAIReferrals } from '~/utils/referrers'
import routes from '~/utils/routes'
@@ -145,7 +152,11 @@ const aggregateDateSeries = (
}
const SEOViewInner = ({ projectId, tnMapping }: SEOViewProps) => {
- const { t } = useTranslation('common')
+ const {
+ t,
+ i18n: { language },
+ } = useTranslation('common')
+ const { theme } = useTheme()
const { id } = useCurrentProject()
const {
period,
@@ -343,6 +354,48 @@ const SEOViewInner = ({ projectId, tnMapping }: SEOViewProps) => {
[data?.topQueries],
)
+ const topCountriesAsEntries: Entry[] = useMemo(
+ () =>
+ (data?.topCountries || []).map((c) => {
+ const alpha2 =
+ countries.alpha3ToAlpha2(c.country.toUpperCase())?.toLowerCase() ||
+ c.country
+ return {
+ name: alpha2,
+ count: c.clicks,
+ impressions: c.impressions,
+ ctr: c.ctr,
+ position: c.position,
+ } as Entry & { impressions: number; ctr: number; position: number }
+ }),
+ [data?.topCountries],
+ )
+
+ const topDevicesAsEntries: Entry[] = useMemo(
+ () =>
+ (data?.topDevices || []).map(
+ (d) =>
+ ({
+ name: d.device,
+ count: d.clicks,
+ impressions: d.impressions,
+ ctr: d.ctr,
+ position: d.position,
+ }) as Entry & { impressions: number; ctr: number; position: number },
+ ),
+ [data?.topDevices],
+ )
+
+ const countryRowMapper = useCallback(
+ (entry: any) => <CCRow cc={entry.name} language={language} />,
+ [language],
+ )
+
+ const deviceRowMapper = useMemo(
+ () => getDeviceRowMapper('dv', theme, t),
+ [theme, t],
+ )
+
const anyMetricActive = Object.values(activeMetrics).some(Boolean)
const chartOptions: ChartOptions = useMemo(() => {
@@ -784,6 +837,38 @@ const SEOViewInner = ({ projectId, tnMapping }: SEOViewProps) => {
dataLoading={isLoading}
/>
</div>
+
+ <div className='mt-3 grid grid-cols-1 gap-3 sm:grid-cols-2'>
+ <Panel
+ name={t('project.location')}
+ data={topCountriesAsEntries}
+ icon={<MapPinIcon className='h-5 w-5' />}
+ id='country'
+ activeTabId='cc'
+ disableRowClick
+ getFilterLink={noopFilterLink}
+ rowMapper={countryRowMapper}
+ valuesHeaderName={t('dashboard.seoClicks')}
+ detailsExtraColumns={detailsExtraColumns}
+ hidePercentageInDetails
+ dataLoading={isLoading}
+ />
+ <Panel
+ name={t('project.devices')}
+ data={topDevicesAsEntries}
+ icon={panelIconMapping.dv}
+ id='device'
+ activeTabId='dv'
+ disableRowClick
+ getFilterLink={noopFilterLink}
+ rowMapper={deviceRowMapper}
+ capitalize
+ valuesHeaderName={t('dashboard.seoClicks')}
+ detailsExtraColumns={detailsExtraColumns}
+ hidePercentageInDetails
+ dataLoading={isLoading}
+ />
+ </div>
</>
)
}