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!

SEO & GEO insights

Blue Mouse11c6b9b16d5f
diff --git a/backend/apps/cloud/src/analytics/analytics.controller.ts b/backend/apps/cloud/src/analytics/analytics.controller.ts
index daae298ed..78e06f56d 100644
--- a/backend/apps/cloud/src/analytics/analytics.controller.ts
+++ b/backend/apps/cloud/src/analytics/analytics.controller.ts
@@ -883,6 +883,147 @@ export class AnalyticsController {
return { keywords }
}
+ @Get('gsc-dashboard')
+ @Auth(true, true)
+ async getGSCDashboard(
+ @Query() data: GetKeywordsDto,
+ @Query('filters') filtersStr: string,
+ @CurrentUserId() uid: string,
+ @Headers() headers: { 'x-password'?: string },
+ ) {
+ const {
+ pid,
+ period,
+ from,
+ to,
+ timezone = DEFAULT_TIMEZONE,
+ timeBucket,
+ } = data
+ const filters = filtersStr || data.filters
+
+ await this.analyticsService.checkProjectAccess(
+ pid,
+ uid,
+ headers['x-password'],
+ )
+
+ await this.analyticsService.checkBillingAccess(pid)
+
+ const finalTimeBucket =
+ timeBucket ||
+ (['1h', 'today', 'yesterday', '1d'].includes(period) ? 'hour' : 'day')
+
+ this.logger.log(
+ `pid: ${pid}, period: ${period}, timeBucket: ${finalTimeBucket}, filters: ${filters}`,
+ 'GET /analytics/gsc-dashboard',
+ )
+
+ let diff
+
+ if (period === 'all') {
+ const res = await this.analyticsService.calculateTimeBucketForAllTime(
+ pid,
+ 'analytics',
+ )
+
+ diff = res.diff
+ }
+
+ const safeTimezone = this.analyticsService.getSafeTimezone(timezone)
+ const { groupFrom, groupTo } = this.analyticsService.getGroupFromTo(
+ from,
+ to,
+ null,
+ period,
+ safeTimezone,
+ diff,
+ )
+
+ return this.gscService.getDashboard(
+ pid,
+ groupFrom,
+ groupTo,
+ finalTimeBucket,
+ filters,
+ )
+ }
+
+ @Get('gsc-details')
+ @Auth(true, true)
+ async getGSCDetails(
+ @Query() data: GetKeywordsDto,
+ @Query('page') pageStr: string,
+ @Query('query') queryStr: string,
+ @CurrentUserId() uid: string,
+ @Headers() headers: { 'x-password'?: string },
+ ) {
+ const { pid, period, from, to, timezone = DEFAULT_TIMEZONE } = data
+ const page = pageStr || data.page
+ const query = queryStr || data.query
+
+ this.logger.log(
+ `pid: ${pid}, period: ${period}, page: ${page}, query: ${query}`,
+ 'GET /analytics/gsc-details',
+ )
+
+ await this.analyticsService.checkProjectAccess(
+ pid,
+ uid,
+ headers['x-password'],
+ )
+
+ await this.analyticsService.checkBillingAccess(pid)
+
+ let diff
+
+ if (period === 'all') {
+ const res = await this.analyticsService.calculateTimeBucketForAllTime(
+ pid,
+ 'analytics',
+ )
+
+ diff = res.diff
+ }
+
+ const safeTimezone = this.analyticsService.getSafeTimezone(timezone)
+ const { groupFrom, groupTo } = this.analyticsService.getGroupFromTo(
+ from,
+ to,
+ null,
+ period,
+ safeTimezone,
+ diff,
+ )
+
+ if (page) {
+ const keywords = await this.gscService.getKeywords(
+ pid,
+ groupFrom,
+ groupTo,
+ 50,
+ 0,
+ undefined,
+ page,
+ )
+ return { type: 'queries', data: keywords }
+ }
+
+ if (query) {
+ const pages = await this.gscService.getTopPages(
+ pid,
+ groupFrom,
+ groupTo,
+ 50,
+ 0,
+ undefined,
+ query,
+ )
+ return { type: 'pages', data: pages }
+ }
+
+ return { type: 'none', data: [] }
+ }
+
@Get('birdseye')
@Auth(true, true)
// returns overall short statistics per project
diff --git a/backend/apps/cloud/src/analytics/dto/get-keywords.dto.ts b/backend/apps/cloud/src/analytics/dto/get-keywords.dto.ts
index d39e40b75..a46fb74d2 100644
--- a/backend/apps/cloud/src/analytics/dto/get-keywords.dto.ts
+++ b/backend/apps/cloud/src/analytics/dto/get-keywords.dto.ts
@@ -18,4 +18,20 @@ export class GetKeywordsDto {
@IsOptional()
@IsString()
timezone?: string
+
+ @IsOptional()
+ @IsString()
+ timeBucket?: string
+
+ @IsOptional()
+ @IsString()
+ filters?: string
+
+ @IsOptional()
+ @IsString()
+ page?: string
+
+ @IsOptional()
+ @IsString()
+ query?: string
}
diff --git a/backend/apps/cloud/src/project/gsc.service.ts b/backend/apps/cloud/src/project/gsc.service.ts
index 9e72864fe..b82e765ba 100644
--- a/backend/apps/cloud/src/project/gsc.service.ts
+++ b/backend/apps/cloud/src/project/gsc.service.ts
@@ -270,10 +270,52 @@ export class GSCService {
} as any)
}
+ private parseFilters(filtersStr?: string) {
+ if (!filtersStr) return undefined
+ try {
+ const filters = JSON.parse(filtersStr)
+ const mappedFilters = []
+
+ for (const filter of filters) {
+ const { column, filter: value, isExclusive, isContains } = filter
+
+ let dimension
+ if (column === 'pg') dimension = 'page'
+ else if (column === 'keywords') dimension = 'query'
+ else continue // Ignore unsupported dimensions for GSC
+
+ let operator = 'equals'
+ if (isExclusive) {
+ operator = isContains ? 'notContains' : 'notEquals'
+ } else if (isContains) {
+ operator = 'contains'
+ }
+
+ const filterObj: any = { dimension, expression: value }
+ if (operator !== 'equals') {
+ filterObj.operator = operator
+ }
+
+ mappedFilters.push(filterObj)
+ }
+
+ if (mappedFilters.length > 0) {
+ return [{ groupType: 'and', filters: mappedFilters }]
+ }
+ } catch {
+ // Ignore parse errors
+ }
+ return undefined
+ }
+
async getKeywords(
pid: string,
from: string,
to: string,
+ limit = 250,
+ offset = 0,
+ filtersStr?: string,
+ page?: string,
): Promise<
{
name: string
@@ -293,10 +335,18 @@ export class GSCService {
const auth = await this.getAuthedClientForPid(pid)
const sc = searchconsole({ version: 'v1', auth })
- // Dates must be YYYY-MM-DD
const startDate = dayjs(from).format('YYYY-MM-DD')
const endDate = dayjs(to).format('YYYY-MM-DD')
+ const dimensionFilterGroups = this.parseFilters(filtersStr) || []
+
+ if (page) {
+ dimensionFilterGroups.push({
+ groupType: 'and',
+ filters: [{ dimension: 'page', expression: page }],
+ })
+ }
+
try {
const { data } = await sc.searchanalytics.query({
siteUrl: tokens.property_uri as string,
@@ -304,8 +354,12 @@ export class GSCService {
startDate,
endDate,
dimensions: ['query'],
- rowLimit: 250, // enough for UI panel
- dataState: 'final',
+ rowLimit: limit,
+ startRow: offset,
+ dataState: 'all',
+ ...(dimensionFilterGroups.length > 0
+ ? { dimensionFilterGroups }
+ : {}),
},
})
@@ -322,7 +376,7 @@ export class GSCService {
count: Math.round(row.clicks || 0),
impressions: Math.round(row.impressions || 0),
position: Number(Number(row.position || 0).toFixed(2)),
- ctr: Number(Number((row.ctr || 0) * 100).toFixed(2)), // return CTR in percent
+ ctr: Number(Number((row.ctr || 0) * 100).toFixed(2)),
}))
.filter(Boolean)
} catch {
@@ -331,4 +385,250 @@ export class GSCService {
)
}
}
+
+ private async ensurePropertyLinked(pid: string) {
+ const tokens = await this.getStoredTokens(pid)
+ if (_isEmpty(tokens) || _isEmpty(tokens.property_uri)) {
+ throw new BadRequestException(
+ 'Search Console property is not linked for this project',
+ )
+ }
+ return tokens
+ }
+
+ async getSummary(
+ pid: string,
+ from: string,
+ to: string,
+ filtersStr?: string,
+ ): Promise<{
+ 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,
+ dataState: 'all',
+ ...(dimensionFilterGroups.length > 0
+ ? { dimensionFilterGroups }
+ : {}),
+ },
+ })
+
+ const row = data.rows?.[0] as
+ | {
+ clicks?: number
+ impressions?: number
+ ctr?: number
+ position?: number
+ }
+ | undefined
+
+ return {
+ 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 summary from Search Console',
+ )
+ }
+ }
+
+ async getDateSeries(
+ pid: string,
+ from: string,
+ to: string,
+ timeBucket?: string,
+ filtersStr?: string,
+ ): Promise<
+ {
+ date: 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) || []
+ const isHourly = timeBucket === 'hour'
+
+ try {
+ const { data } = await sc.searchanalytics.query({
+ siteUrl: tokens.property_uri as string,
+ requestBody: {
+ startDate,
+ endDate,
+ dimensions: isHourly ? ['HOUR'] : ['date'],
+ rowLimit: 5000,
+ dataState: isHourly ? 'HOURLY_ALL' : '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) => ({
+ date: row.keys?.[0]
+ ? isHourly
+ ? dayjs(row.keys[0]).format('YYYY-MM-DD HH:mm:ss')
+ : row.keys[0]
+ : '',
+ 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 date series from Search Console',
+ )
+ }
+ }
+
+ async getTopPages(
+ pid: string,
+ from: string,
+ to: string,
+ limit = 50,
+ offset = 0,
+ filtersStr?: string,
+ query?: string,
+ ): Promise<
+ {
+ page: 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) || []
+
+ if (query) {
+ dimensionFilterGroups.push({
+ groupType: 'and',
+ filters: [{ dimension: 'query', expression: query }],
+ })
+ }
+
+ try {
+ const { data } = await sc.searchanalytics.query({
+ siteUrl: tokens.property_uri as string,
+ requestBody: {
+ startDate,
+ endDate,
+ dimensions: ['page'],
+ 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) => ({
+ page: row.keys?.[0] || '(not set)',
+ 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 pages from Search Console',
+ )
+ }
+ }
+
+ async getDashboard(
+ pid: string,
+ from: string,
+ to: string,
+ timeBucket?: string,
+ filtersStr?: string,
+ ) {
+ const connected = await this.isConnected(pid)
+ if (!connected) {
+ return { notConnected: true }
+ }
+
+ const tokens = await this.getStoredTokens(pid)
+ if (_isEmpty(tokens.property_uri)) {
+ return { notConnected: true, noProperty: true }
+ }
+
+ const fromDate = dayjs(from)
+ const toDate = dayjs(to)
+ const durationMs = toDate.diff(fromDate)
+ const prevTo = fromDate.subtract(1, 'day').format('YYYY-MM-DD HH:mm:ss')
+ const prevFrom = fromDate
+ .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),
+ ])
+
+ return {
+ notConnected: false,
+ summary,
+ previousSummary,
+ dateSeries,
+ topPages,
+ topQueries,
+ }
+ }
}
diff --git a/web/app/api/api.server.ts b/web/app/api/api.server.ts
index 0b3452878..1a40e2c64 100644
--- a/web/app/api/api.server.ts
+++ b/web/app/api/api.server.ts
@@ -2406,6 +2406,140 @@ export async function getGSCKeywordsServer(
)
}
+// ============================================================================
+// MARK: GSC Dashboard API
+// ============================================================================
+
+interface GSCDateSeriesEntry {
+ date: string
+ clicks: number
+ impressions: number
+ ctr: number
+ position: number
+}
+
+interface GSCTopPageEntry {
+ page: string
+ clicks: number
+ impressions: number
+ ctr: number
+ position: number
+}
+
+interface GSCTopQueryEntry {
+ name: string
+ count: number
+ impressions: number
+ position: number
+ ctr: number
+}
+
+export interface GSCDashboardResponse {
+ notConnected?: boolean
+ noProperty?: boolean
+ summary?: {
+ clicks: number
+ impressions: number
+ ctr: number
+ position: number
+ }
+ previousSummary?: {
+ clicks: number
+ impressions: number
+ ctr: number
+ position: number
+ } | null
+ dateSeries?: GSCDateSeriesEntry[]
+ topPages?: GSCTopPageEntry[]
+ topQueries?: GSCTopQueryEntry[]
+}
+
+export async function getGSCDashboardServer(
+ request: Request,
+ pid: string,
+ params: {
+ period?: string
+ from?: string
+ to?: string
+ timezone?: string
+ password?: string
+ timeBucket?: string
+ filters?: AnalyticsFilter[]
+ } = {},
+): Promise<ServerFetchResult<GSCDashboardResponse>> {
+ const queryParams = new URLSearchParams()
+ queryParams.append('pid', pid)
+ queryParams.append('period', params.period || '7d')
+ if (params.from) queryParams.append('from', params.from)
+ if (params.to) queryParams.append('to', params.to)
+ if (params.timezone) queryParams.append('timezone', params.timezone)
+ if (params.timeBucket) queryParams.append('timeBucket', params.timeBucket)
+ if (params.filters)
+ queryParams.append('filters', serializeFiltersForUrl(params.filters))
+
+ const headers: Record<string, string> = {}
+ if (params.password) {
+ headers['x-password'] = params.password
+ }
+
+ return serverFetch<GSCDashboardResponse>(
+ request,
+ `log/gsc-dashboard?${queryParams.toString()}`,
+ { headers },
+ )
+}
+
+// ============================================================================
+// MARK: GSC Details API (Keyword-to-Page mapping)
+// ============================================================================
+
+export interface GSCDetailsResponse {
+ type: 'queries' | 'pages' | 'none'
+ data: Array<{
+ name?: string
+ page?: string
+ count?: number
+ clicks?: number
+ impressions: number
+ ctr: number
+ position: number
+ }>
+}
+
+export async function getGSCDetailsServer(
+ request: Request,
+ pid: string,
+ params: {
+ period?: string
+ from?: string
+ to?: string
+ timezone?: string
+ password?: string
+ page?: string
+ query?: string
+ } = {},
+): Promise<ServerFetchResult<GSCDetailsResponse>> {
+ const queryParams = new URLSearchParams()
+ queryParams.append('pid', pid)
+ queryParams.append('period', params.period || '7d')
+ if (params.from) queryParams.append('from', params.from)
+ if (params.to) queryParams.append('to', params.to)
+ if (params.timezone) queryParams.append('timezone', params.timezone)
+ if (params.page) queryParams.append('page', params.page)
+ if (params.query) queryParams.append('query', params.query)
+
+ const headers: Record<string, string> = {}
+ if (params.password) {
+ headers['x-password'] = params.password
+ }
+
+ return serverFetch<GSCDetailsResponse>(
+ request,
+ `log/gsc-details?${queryParams.toString()}`,
+ { headers },
+ )
+}
+
// ============================================================================
// MARK: Revenue API
// ============================================================================
diff --git a/web/app/hooks/useAnalyticsProxy.ts b/web/app/hooks/useAnalyticsProxy.ts
index a1f0a85be..b1bea1157 100644
--- a/web/app/hooks/useAnalyticsProxy.ts
+++ b/web/app/hooks/useAnalyticsProxy.ts
@@ -25,6 +25,8 @@ import type {
ProjectDataCustomEventsResponse,
UserFlowResponse,
GSCKeywordsResponse,
+ GSCDashboardResponse,
+ GSCDetailsResponse,
RevenueStatus,
RevenueDataResponse,
OverallObject,
@@ -839,6 +841,38 @@ export function useGSCKeywordsProxy() {
return { fetchKeywords, data, error, isLoading }
}
+export function useGSCDashboardProxy() {
+ const [data, setData] = useState<GSCDashboardResponse | null>(null)
+ const [error, setError] = useState<string | null>(null)
+ const [isLoading, setIsLoading] = useState(false)
+
+ const fetchDashboard = useCallback(
+ async (projectId: string, params: ClientAnalyticsParams = {}) => {
+ setIsLoading(true)
+ setError(null)
+
+ try {
+ const result = await postAnalytics<GSCDashboardResponse>({
+ action: 'getGSCDashboard',
+ projectId,
+ params,
+ })
+ setData(result.data)
+ setError(result.error)
+ return result.data
+ } catch (err) {
+ setError(err instanceof Error ? err.message : 'Unknown error')
+ return null
+ } finally {
+ setIsLoading(false)
+ }
+ },
+ [],
+ )
+
+ return { fetchDashboard, data, error, isLoading }
+}
+
export function useRevenueProxy() {
const [statusData, setStatusData] = useState<RevenueStatus | null>(null)
const [revenueData, setRevenueData] = useState<RevenueDataResponse | null>(
diff --git a/web/app/lib/constants/index.ts b/web/app/lib/constants/index.ts
index 233e4c746..3dc24e8c3 100644
--- a/web/app/lib/constants/index.ts
+++ b/web/app/lib/constants/index.ts
@@ -499,6 +499,7 @@ const SELFHOSTED_PROJECT_TABS = {
const PRODUCTION_PROJECT_TABS = {
traffic: 'traffic',
performance: 'performance',
+ seo: 'seo',
profiles: 'profiles',
funnels: 'funnels',
sessions: 'sessions',
diff --git a/web/app/pages/Project/View/Panels.tsx b/web/app/pages/Project/View/Panels.tsx
index 3a422dc83..4c49f29a5 100644
--- a/web/app/pages/Project/View/Panels.tsx
+++ b/web/app/pages/Project/View/Panels.tsx
@@ -1529,6 +1529,8 @@ interface PanelProps {
}>
dataLoading?: boolean
activeTab?: keyof typeof PROJECT_TABS
+ onRowClick?: (entryName: string) => void
+ selectedRow?: string | null
}
interface DetailsTableProps extends Pick<
@@ -1929,6 +1931,8 @@ const Panel = ({
detailsExtraColumns,
dataLoading: dataLoadingProp,
activeTab: activeTabProp,
+ onRowClick,
+ selectedRow,
}: PanelProps) => {
const ctx = useViewProjectContext()
const dataLoading = dataLoadingProp ?? ctx.dataLoading
@@ -2010,6 +2014,9 @@ const Panel = ({
const link = getFilterLink(id, entryName)
+ const isSelected =
+ selectedRow != null && selectedRow === entryName
+
return (
<div
key={`${id}-${entryName}-${Object.values(rest).join('-')}`}
@@ -2022,10 +2029,19 @@ const Panel = ({
'group hover:bg-gray-50 dark:hover:bg-slate-900/60':
!hideFilters &&
!dataLoading &&
- (link || hasVersionsForItem),
+ (link || hasVersionsForItem || onRowClick),
+ 'cursor-pointer': onRowClick && !dataLoading,
'cursor-wait': dataLoading,
+ 'bg-gray-50 ring-1 ring-slate-400/60 dark:bg-slate-800/60 dark:ring-slate-500/60':
+ isSelected,
},
)}
+ onClick={
+ onRowClick && entryName
+ ? () => onRowClick(entryName)
+ : undefined
+ }
+ role='presentation'
>
<div
className={cx('absolute inset-0 rounded-sm', {
diff --git a/web/app/pages/Project/View/ViewProject.helpers.tsx b/web/app/pages/Project/View/ViewProject.helpers.tsx
index f23b603ee..4864bf3cf 100644
--- a/web/app/pages/Project/View/ViewProject.helpers.tsx
+++ b/web/app/pages/Project/View/ViewProject.helpers.tsx
@@ -2148,12 +2148,12 @@ const typeNameMapping = (t: typeof i18next.t) => ({
rg: t('project.mapping.rg'),
ct: t('project.mapping.ct'),
pg: t('project.mapping.pg'),
+ keywords: t('dashboard.seoTopQueries'),
entryPage: t('project.entryPages'),
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'),
brv: t('project.mapping.brv'),
@@ -2170,6 +2170,8 @@ const typeNameMapping = (t: typeof i18next.t) => ({
'tag:value': t('project.metamapping.tag.value'),
'ev:key': t('project.metamapping.ev.key'),
'ev:value': t('project.metamapping.ev.value'),
+ searchEngine: t('project.mapping.searchEngine'),
+ aiReferral: t('project.mapping.aiReferral'),
// Combined panel types
location: t('project.location'),
browser: t('project.browser'),
diff --git a/web/app/pages/Project/View/ViewProject.tsx b/web/app/pages/Project/View/ViewProject.tsx
index e2e0a66dc..21cbeb65e 100644
--- a/web/app/pages/Project/View/ViewProject.tsx
+++ b/web/app/pages/Project/View/ViewProject.tsx
@@ -22,6 +22,7 @@ import {
IdentificationCardIcon,
UserListIcon,
ToggleRightIcon,
+ MagnifyingGlassIcon,
} from '@phosphor-icons/react'
import React, {
useState,
@@ -92,6 +93,7 @@ import GoalsView from '../tabs/Goals/GoalsView'
import PerformanceView from '../tabs/Performance/PerformanceView'
import ProfilesView from '../tabs/Profiles/ProfilesView'
import SessionsView from '../tabs/Sessions/SessionsView'
+import SEOView from '../tabs/SEO/SEOView'
import TrafficView from '../tabs/Traffic/TrafficView'
import AddAViewModal from './components/AddAViewModal'
@@ -183,6 +185,7 @@ interface RefreshTriggersContextType {
trafficRefreshTrigger: number
funnelsRefreshTrigger: number
profilesRefreshTrigger: number
+ seoRefreshTrigger: number
}
const defaultViewProjectContext: ViewProjectContextType = {
@@ -245,6 +248,7 @@ const defaultRefreshTriggersContext: RefreshTriggersContextType = {
trafficRefreshTrigger: 0,
funnelsRefreshTrigger: 0,
profilesRefreshTrigger: 0,
+ seoRefreshTrigger: 0,
}
export const ViewProjectContext = createContext<ViewProjectContextType>(
@@ -329,6 +333,7 @@ const ViewProjectContent = () => {
const [trafficRefreshTrigger, setTrafficRefreshTrigger] = useState(0)
const [funnelsRefreshTrigger, setFunnelsRefreshTrigger] = useState(0)
const [profilesRefreshTrigger, setProfilesRefreshTrigger] = useState(0)
+ const [seoRefreshTrigger, setSeoRefreshTrigger] = useState(0)
const [activeChartMetrics] = useState<
Record<keyof typeof CHART_METRICS_MAPPING, boolean>
>({
@@ -718,6 +723,11 @@ const ViewProjectContent = () => {
label: t('dashboard.performance'),
icon: GaugeIcon,
},
+ {
+ id: PROJECT_TABS.seo,
+ label: t('dashboard.seo'),
+ icon: MagnifyingGlassIcon,
+ },
{
id: PROJECT_TABS.profiles,
label: t('dashboard.profiles'),
@@ -919,6 +929,11 @@ const ViewProjectContent = () => {
setTrafficRefreshTrigger((prev) => prev + 1)
return
}
+
+ if (activeTab === PROJECT_TABS.seo) {
+ setSeoRefreshTrigger((prev) => prev + 1)
+ return
+ }
}
},
[authLoading, dataLoading, activeTab],
@@ -1253,6 +1268,7 @@ const ViewProjectContent = () => {
trafficRefreshTrigger,
funnelsRefreshTrigger,
profilesRefreshTrigger,
+ seoRefreshTrigger,
}),
[
captchaRefreshTrigger,
@@ -1265,6 +1281,7 @@ const ViewProjectContent = () => {
trafficRefreshTrigger,
funnelsRefreshTrigger,
profilesRefreshTrigger,
+ seoRefreshTrigger,
],
)
@@ -1532,6 +1549,9 @@ const ViewProjectContent = () => {
{activeTab === PROJECT_TABS.performance ? (
<PerformanceView tnMapping={tnMapping} />
) : null}
+ {activeTab === PROJECT_TABS.seo ? (
+ <SEOView projectId={id} tnMapping={tnMapping} />
+ ) : null}
{activeTab === PROJECT_TABS.funnels ? (
<FunnelsView />
) : null}
diff --git a/web/app/pages/Project/View/components/ProjectSidebar.tsx b/web/app/pages/Project/View/components/ProjectSidebar.tsx
index 3277420b6..24878b5d8 100644
--- a/web/app/pages/Project/View/components/ProjectSidebar.tsx
+++ b/web/app/pages/Project/View/components/ProjectSidebar.tsx
@@ -63,6 +63,7 @@ const ICON_COLORS: Record<string, string> = {
// Web Analytics
traffic: 'text-blue-500',
performance: 'text-amber-500',
+ seo: 'text-green-500',
funnels: 'text-teal-500',
alerts: 'text-cyan-500',
// Product Analytics
@@ -402,6 +403,7 @@ const ProjectSidebar: React.FC<ProjectSidebarProps> = ({
[
PROJECT_TABS.traffic,
PROJECT_TABS.performance,
+ PROJECT_TABS.seo,
PROJECT_TABS.funnels,
PROJECT_TABS.alerts,
]
diff --git a/web/app/pages/Project/View/utils/filters.tsx b/web/app/pages/Project/View/utils/filters.tsx
index 2e466dc3c..03a277208 100644
--- a/web/app/pages/Project/View/utils/filters.tsx
+++ b/web/app/pages/Project/View/utils/filters.tsx
@@ -39,6 +39,7 @@ const validFilters = [
'te',
'co',
'ev',
+ 'keywords',
'tag:key',
'tag:value',
'ev:key',
diff --git a/web/app/pages/Project/tabs/SEO/SEOView.tsx b/web/app/pages/Project/tabs/SEO/SEOView.tsx
new file mode 100644
index 000000000..d36dba64e
--- /dev/null
+++ b/web/app/pages/Project/tabs/SEO/SEOView.tsx
@@ -0,0 +1,805 @@
+import {
+ ArrowClockwiseIcon,
+ EyeIcon,
+ LinkIcon,
+ PlugIcon,
+ RobotIcon,
+ MagnifyingGlassIcon,
+} from '@phosphor-icons/react'
+import type { ChartOptions } from 'billboard.js'
+import { area } from 'billboard.js'
+import * as d3 from 'd3'
+import dayjs from 'dayjs'
+import isoWeek from 'dayjs/plugin/isoWeek'
+import quarterOfYear from 'dayjs/plugin/quarterOfYear'
+import _isEmpty from 'lodash/isEmpty'
+import _round from 'lodash/round'
+import React, {
+ useEffect,
+ useCallback,
+ useMemo,
+ useRef,
+ use,
+ useState,
+} from 'react'
+import { useTranslation } from 'react-i18next'
+import { Link, useLoaderData, useSearchParams } from 'react-router'
+
+dayjs.extend(isoWeek)
+dayjs.extend(quarterOfYear)
+
+import { useGSCDashboardProxy } from '~/hooks/useAnalyticsProxy'
+import type { TimeBucket } from '~/lib/constants'
+import type { Entry } from '~/lib/models/Entry'
+import DashboardHeader from '~/pages/Project/View/components/DashboardHeader'
+import { MainChart } from '~/pages/Project/View/components/MainChart'
+import Filters from '~/pages/Project/View/components/Filters'
+import { Panel } from '~/pages/Project/View/Panels'
+import {
+ useViewProjectContext,
+ useRefreshTriggers,
+} from '~/pages/Project/View/ViewProject'
+import { panelIconMapping } from '~/pages/Project/View/ViewProject.helpers'
+import { MetricCard } from '~/pages/Project/tabs/Traffic/MetricCards'
+import RefRow from '~/pages/Project/tabs/Traffic/RefRow'
+import { useCurrentProject } from '~/providers/CurrentProjectProvider'
+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 { getSearchEngineReferrals, getAIReferrals } from '~/utils/referrers'
+import routes from '~/utils/routes'
+
+interface SEOViewProps {
+ projectId: string
+ tnMapping: Record<string, string>
+}
+
+const SEO_METRICS = {
+ clicks: 'clicks',
+ impressions: 'impressions',
+ position: 'position',
+ ctr: 'ctr',
+} as const
+
+type SEOMetricKey = keyof typeof SEO_METRICS
+
+interface DateSeriesEntry {
+ date: string
+ clicks: number
+ impressions: number
+ ctr: number
+ position: number
+}
+
+const getBucketKey = (date: string, bucket: string): string => {
+ const d = dayjs(date)
+ switch (bucket) {
+ case 'hour':
+ case 'day':
+ return date
+ case 'week':
+ return d.startOf('isoWeek').format('YYYY-MM-DD')
+ case 'month':
+ return d.startOf('month').format('YYYY-MM-DD')
+ case 'quarter':
+ return d.startOf('quarter').format('YYYY-MM-DD')
+ case 'year':
+ return d.startOf('year').format('YYYY-MM-DD')
+ default:
+ return date
+ }
+}
+
+const aggregateDateSeries = (
+ series: DateSeriesEntry[],
+ bucket: string,
+): DateSeriesEntry[] => {
+ if (!series.length || bucket === 'day' || bucket === 'hour') return series
+
+ const buckets = new Map<
+ string,
+ {
+ clicks: number
+ impressions: number
+ ctr: number
+ position: number
+ count: number
+ }
+ >()
+ const orderedKeys: string[] = []
+
+ for (const entry of series) {
+ const key = getBucketKey(entry.date, bucket)
+ const existing = buckets.get(key)
+ if (existing) {
+ existing.clicks += entry.clicks
+ existing.impressions += entry.impressions
+ existing.ctr += entry.ctr
+ existing.position += entry.position
+ existing.count += 1
+ } else {
+ orderedKeys.push(key)
+ buckets.set(key, {
+ clicks: entry.clicks,
+ impressions: entry.impressions,
+ ctr: entry.ctr,
+ position: entry.position,
+ count: 1,
+ })
+ }
+ }
+
+ return orderedKeys.map((key) => {
+ const b = buckets.get(key)!
+ return {
+ date: key,
+ clicks: b.clicks,
+ impressions: b.impressions,
+ ctr: Number((b.ctr / b.count).toFixed(2)),
+ position: Number((b.position / b.count).toFixed(1)),
+ }
+ })
+}
+
+const SEOViewInner = ({ projectId, tnMapping }: SEOViewProps) => {
+ const { t } = useTranslation('common')
+ const { id } = useCurrentProject()
+ const {
+ period,
+ timezone,
+ timeFormat,
+ timeBucket,
+ periodPairs,
+ filters,
+ getFilterLink,
+ } = useViewProjectContext()
+ const { seoRefreshTrigger } = useRefreshTriggers()
+ const { fetchDashboard, data, isLoading } = useGSCDashboardProxy()
+ const [searchParams] = useSearchParams()
+
+ const [activeMetrics, setActiveMetrics] = useState<
+ Record<SEOMetricKey, boolean>
+ >({
+ clicks: true,
+ impressions: true,
+ position: false,
+ ctr: false,
+ })
+
+ const seoPeriodPairs = useMemo(
+ () =>
+ periodPairs
+ .filter(
+ (p) =>
+ p.period !== '1h' &&
+ p.period !== 'today' &&
+ p.period !== 'yesterday',
+ )
+ .map((p) => {
+ const tbs = p.tbs.filter((tb): tb is TimeBucket => tb !== 'minute')
+ return { ...p, tbs: tbs.length ? tbs : (['day'] as TimeBucket[]) }
+ }),
+ [periodPairs],
+ )
+
+ const metricItems = useMemo(
+ () => [
+ {
+ id: SEO_METRICS.clicks,
+ label: t('dashboard.seoClicks'),
+ active: activeMetrics.clicks,
+ },
+ {
+ id: SEO_METRICS.impressions,
+ label: t('dashboard.seoImpressions'),
+ active: activeMetrics.impressions,
+ },
+ {
+ id: SEO_METRICS.position,
+ label: t('dashboard.seoAvgPosition'),
+ active: activeMetrics.position,
+ },
+ {
+ id: SEO_METRICS.ctr,
+ label: t('dashboard.seoAvgCTR'),
+ active: activeMetrics.ctr,
+ },
+ ],
+ [t, activeMetrics],
+ )
+
+ const toggleMetric = useCallback((metricId: string) => {
+ setActiveMetrics((prev) => ({
+ ...prev,
+ [metricId]: !prev[metricId as SEOMetricKey],
+ }))
+ }, [])
+
+ const { trafficData: trafficDataPromise } = useLoaderData<ProjectLoaderData>()
+
+ const trafficData = trafficDataPromise ? use(trafficDataPromise) : null
+
+ const refEntries: Entry[] = useMemo(() => {
+ const refParams = trafficData?.params?.ref
+ if (!refParams) return []
+ return refParams.map((r: { name: string; count: number }) => ({
+ name: r.name,
+ count: r.count,
+ }))
+ }, [trafficData])
+
+ const searchEngineEntries = useMemo(
+ () => getSearchEngineReferrals(refEntries),
+ [refEntries],
+ )
+ const aiReferralEntries = useMemo(
+ () => getAIReferrals(refEntries),
+ [refEntries],
+ )
+
+ const refRowMapper = useCallback(
+ ({ name: entryName }: any) => <RefRow rowName={entryName} />,
+ [],
+ )
+
+ const noopFilterLink = useCallback(() => '#', [])
+
+ const [isManualRefreshing, setIsManualRefreshing] = useState(false)
+
+ const prevTrigger = useRef(seoRefreshTrigger)
+
+ const from = searchParams.get('from') || undefined
+ const to = searchParams.get('to') || undefined
+
+ const loadData = useCallback(async () => {
+ await fetchDashboard(projectId, {
+ period,
+ from,
+ to,
+ timezone,
+ timeBucket,
+ filters,
+ })
+ }, [
+ fetchDashboard,
+ projectId,
+ period,
+ from,
+ to,
+ timezone,
+ timeBucket,
+ filters,
+ ])
+
+ useEffect(() => {
+ loadData()
+ }, [loadData])
+
+ useEffect(() => {
+ if (seoRefreshTrigger !== prevTrigger.current) {
+ prevTrigger.current = seoRefreshTrigger
+ loadData()
+ }
+ }, [seoRefreshTrigger, loadData])
+
+ const handleManualRefresh = useCallback(async () => {
+ if (isManualRefreshing) return
+ setIsManualRefreshing(true)
+ await loadData()
+ setIsManualRefreshing(false)
+ }, [isManualRefreshing, loadData])
+
+ const manualRefreshButton = useMemo(
+ () => (
+ <button
+ type='button'
+ title={t('project.refreshStats')}
+ onClick={handleManualRefresh}
+ className='relative rounded-md border border-transparent p-2 transition-all ring-inset hover:border-gray-300 hover:bg-white focus:z-10 focus:ring-1 focus:ring-slate-900 focus:outline-hidden hover:dark:border-slate-700/80 dark:hover:bg-slate-900 dark:focus:ring-slate-300'
+ >
+ <ArrowClockwiseIcon
+ className={`h-5 w-5 text-gray-700 dark:text-gray-50 ${isManualRefreshing ? 'animate-spin' : ''}`}
+ />
+ </button>
+ ),
+ [t, handleManualRefresh, isManualRefreshing],
+ )
+
+ const aggregatedSeries = useMemo(
+ () => aggregateDateSeries(data?.dateSeries || [], timeBucket),
+ [data?.dateSeries, timeBucket],
+ )
+
+ const topPagesAsEntries: Entry[] = useMemo(
+ () =>
+ (data?.topPages || []).map(
+ (p) =>
+ ({
+ name: p.page,
+ count: p.clicks,
+ impressions: p.impressions,
+ ctr: p.ctr,
+ position: p.position,
+ }) as Entry & { impressions: number; ctr: number; position: number },
+ ),
+ [data?.topPages],
+ )
+
+ const topQueriesAsEntries: Entry[] = useMemo(
+ () =>
+ (data?.topQueries || []).map(
+ (q) =>
+ ({
+ name: q.name,
+ count: q.count,
+ impressions: q.impressions,
+ ctr: q.ctr,
+ position: q.position,
+ }) as Entry & { impressions: number; ctr: number; position: number },
+ ),
+ [data?.topQueries],
+ )
+
+ const anyMetricActive = Object.values(activeMetrics).some(Boolean)
+
+ const chartOptions: ChartOptions = useMemo(() => {
+ if (!aggregatedSeries.length) return {}
+
+ const dates = aggregatedSeries.map((d) => d.date)
+ const columns: any[] = [['x', ...dates]]
+ const colors: Record<string, string> = {}
+ const axes: Record<string, string> = {}
+ let needsY2 = false
+
+ if (activeMetrics.clicks) {
+ const label = t('dashboard.seoClicks')
+ columns.push([label, ...aggregatedSeries.map((d) => d.clicks)])
+ colors[label] = '#3b82f6' // blue-500 - matching GSC
+ }
+
+ if (activeMetrics.impressions) {
+ const label = t('dashboard.seoImpressions')
+ columns.push([label, ...aggregatedSeries.map((d) => d.impressions)])
+ colors[label] = '#5b21b6' // violet-800 - matching GSC
+ if (activeMetrics.clicks) {
+ axes[label] = 'y2'
+ needsY2 = true
+ }
+ }
+
+ if (activeMetrics.position) {
+ const label = t('dashboard.seoAvgPosition')
+ columns.push([label, ...aggregatedSeries.map((d) => d.position)])
+ colors[label] = '#d97706' // amber-600 - matching GSC
+ if (activeMetrics.clicks || activeMetrics.impressions) {
+ axes[label] = 'y2'
+ needsY2 = true
+ }
+ }
+
+ if (activeMetrics.ctr) {
+ const label = t('dashboard.seoAvgCTR')
+ columns.push([label, ...aggregatedSeries.map((d) => d.ctr)])
+ colors[label] = '#0d9488' // teal-600 - matching GSC
+ if (activeMetrics.clicks || activeMetrics.impressions) {
+ axes[label] = 'y2'
+ needsY2 = true
+ }
+ }
+
+ const tickFormatMap: Record<string, string> = {
+ hour: '%b %d %H:%M',
+ day: '%b %d',
+ week: '%b %d',
+ month: '%b %Y',
+ quarter: '%b %Y',
+ year: '%Y',
+ }
+ const tickFormat = tickFormatMap[timeBucket] || '%b %d'
+
+ return {
+ data: {
+ x: 'x',
+ xFormat: timeBucket === 'hour' ? '%Y-%m-%d %H:%M:%S' : '%Y-%m-%d',
+ columns,
+ type: area(),
+ axes,
+ colors,
+ },
+ area: {
+ linearGradient: true,
+ },
+ transition: {
+ duration: 200,
+ },
+ resize: {
+ auto: true,
+ timer: false,
+ },
+ axis: {
+ x: {
+ clipPath: false,
+ type: 'timeseries',
+ tick: {
+ fit: true,
+ format: tickFormat,
+ rotate: 0,
+ },
+ },
+ y: {
+ tick: {
+ format: (d: number) => nFormatter(d, 1),
+ },
+ show: true,
+ inner: true,
+ min: 0,
+ padding: { bottom: 0 },
+ },
+ y2: {
+ show: needsY2,
+ tick: {
+ format: (d: number) => nFormatter(d, 1),
+ },
+ inner: true,
+ min: 0,
+ padding: { bottom: 0 },
+ },
+ },
+ point: {
+ focus: {
+ only: dates.length > 1,
+ },
+ pattern: ['circle'],
+ r: 2,
+ },
+ grid: {
+ y: {
+ show: true,
+ },
+ },
+ legend: {
+ item: {
+ tile: {
+ type: 'circle',
+ width: 10,
+ r: 3,
+ },
+ },
+ },
+ tooltip: {
+ contents: (items, _defaultTitleFormat, _defaultValueFormat, color) => {
+ const tooltipFormatMap: Record<string, string> = {
+ hour: '%b %d, %Y %H:%M',
+ day: '%b %d, %Y',
+ week: 'Week of %b %d, %Y',
+ month: '%B %Y',
+ quarter: '%B %Y',
+ year: '%Y',
+ }
+ const tooltipFmt = tooltipFormatMap[timeBucket] || '%b %d, %Y'
+ const headerLabel = d3.timeFormat(tooltipFmt)(items[0].x)
+ return `<ul class='bg-gray-50 dark:text-gray-50 dark:bg-slate-900 rounded-md ring-1 ring-black/10 px-2 py-1 text-xs md:text-sm max-h-[250px] md:max-h-[350px] overflow-y-auto shadow-md z-50'>
+ <li class='font-semibold pb-1 mb-1 border-b border-gray-200 dark:border-slate-800 sticky top-0 bg-gray-50 dark:bg-slate-900'>${headerLabel}</li>
+ ${items
+ .map((el: any) => {
+ const isCtr = el.name === t('dashboard.seoAvgCTR')
+ const isPos = el.name === t('dashboard.seoAvgPosition')
+ let formatted = nFormatter(el.value, 1)
+ if (isCtr) formatted = `${Number(el.value).toFixed(1)}%`
+ else if (isPos) formatted = Number(el.value).toFixed(1)
+
+ return `
+ <li class='flex justify-between items-center py-px leading-snug'>
+ <div class='flex items-center min-w-0 mr-4'>
+ <div class='w-2.5 h-2.5 rounded-xs mr-1.5 shrink-0' style=background-color:${color(el.id)}></div>
+ <span class="truncate">${el.name}</span>
+ </div>
+ <span class='font-mono whitespace-nowrap'>${formatted}</span>
+ </li>`
+ })
+ .join('')}
+ </ul>`
+ },
+ },
+ padding: { right: needsY2 ? 20 : undefined },
+ }
+ }, [aggregatedSeries, activeMetrics, timeBucket, t])
+
+ const detailsExtraColumns = useMemo(
+ () => [
+ {
+ header: t('dashboard.seoImpressions'),
+ render: (entry: any) => nFormatter(entry.impressions ?? 0, 1),
+ sortLabel: 'impressions',
+ getSortValue: (entry: any) => entry.impressions ?? 0,
+ },
+ {
+ header: t('dashboard.seoCTR'),
+ render: (entry: any) => `${entry.ctr ?? 0}%`,
+ sortLabel: 'ctr',
+ getSortValue: (entry: any) => entry.ctr ?? 0,
+ },
+ {
+ header: t('dashboard.seoPosition'),
+ render: (entry: any) => entry.position ?? 0,
+ sortLabel: 'position',
+ getSortValue: (entry: any) => entry.position ?? 0,
+ },
+ ],
+ [t],
+ )
+
+ if (isLoading && !data) {
+ return (
+ <>
+ <DashboardHeader
+ showSearchButton={false}
+ showRefreshButton={false}
+ rightContent={manualRefreshButton}
+ timeBucketSelectorItems={seoPeriodPairs}
+ />
+ <div className='flex min-h-[400px] items-center justify-center'>
+ <Loader />
+ </div>
+ </>
+ )
+ }
+
+ if (data?.notConnected) {
+ return (
+ <>
+ <DashboardHeader
+ showSearchButton={false}
+ showRefreshButton={false}
+ rightContent={manualRefreshButton}
+ timeBucketSelectorItems={seoPeriodPairs}
+ />
+ <div className='mx-auto flex max-w-lg flex-col items-center justify-center py-16 text-center'>
+ <div className='mb-4 flex size-16 items-center justify-center rounded-2xl bg-gray-100 dark:bg-slate-800'>
+ <PlugIcon
+ className='size-8 text-gray-400 dark:text-gray-500'
+ weight='duotone'
+ />
+ </div>
+ <Text size='xl' weight='bold' className='mb-2'>
+ {t('dashboard.seoConnectGSC')}
+ </Text>
+ <Text size='sm' className='mb-6 text-gray-500 dark:text-gray-400'>
+ {t('dashboard.seoConnectGSCDesc')}
+ </Text>
+ {data?.noProperty ? (
+ <Text size='sm' className='mb-4 text-amber-600 dark:text-amber-400'>
+ {t('dashboard.seoNoProperty')}
+ </Text>
+ ) : null}
+ <Link
+ to={`${routes.project_settings.replace(':id', id)}?tab=integrations`}
+ className='inline-flex items-center gap-2 rounded-lg bg-slate-900 px-5 py-2.5 text-sm font-medium text-white transition-colors hover:bg-slate-800 dark:bg-slate-100 dark:text-slate-900 dark:hover:bg-slate-200'
+ >
+ <LinkIcon className='size-4' />
+ {t('dashboard.seoConnectButton')}
+ </Link>
+
+ {refEntries.length > 0 ? (
+ <div className='mt-10 grid w-full grid-cols-1 gap-3 sm:grid-cols-2'>
+ <Panel
+ name={t('dashboard.seoSearchEngines')}
+ data={searchEngineEntries}
+ icon={panelIconMapping.ref}
+ id='seo-search-engines'
+ activeTabId='searchEngine'
+ disableRowClick
+ rowMapper={refRowMapper}
+ getFilterLink={noopFilterLink}
+ valuesHeaderName={t('project.visitors')}
+ />
+ <Panel
+ name={t('dashboard.seoAIReferrals')}
+ data={aiReferralEntries}
+ icon={<RobotIcon className='h-5 w-5' />}
+ id='seo-ai-referrals'
+ activeTabId='aiReferral'
+ disableRowClick
+ rowMapper={refRowMapper}
+ getFilterLink={noopFilterLink}
+ valuesHeaderName={t('project.visitors')}
+ />
+ </div>
+ ) : null}
+ </div>
+ </>
+ )
+ }
+
+ return (
+ <>
+ <DashboardHeader
+ showSearchButton={false}
+ showRefreshButton={false}
+ rightContent={manualRefreshButton}
+ timeBucketSelectorItems={seoPeriodPairs}
+ />
+ {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
+ header={t('project.metricVis')}
+ items={metricItems}
+ title={[
+ <EyeIcon
+ key='eye-icon'
+ aria-label={t('project.metricVis')}
+ className='h-5 w-5'
+ />,
+ ]}
+ labelExtractor={(pair) => {
+ if (!pair) return null
+ return (
+ <Checkbox
+ classes={{ label: 'p-2' }}
+ label={pair.label}
+ checked={pair.active}
+ onChange={() => toggleMetric(pair.id)}
+ />
+ )
+ }}
+ buttonClassName='!p-1.5 rounded-md border border-transparent hover:border-gray-300 hover:bg-white hover:dark:border-slate-700/80 hover:dark:bg-slate-950 dark:focus:ring-slate-300'
+ selectItemClassName='p-0'
+ keyExtractor={(pair) => pair?.id || ''}
+ onSelect={(pair, e) => {
+ if (!pair) return
+ e?.stopPropagation()
+ e?.preventDefault()
+ toggleMetric(pair.id)
+ }}
+ chevron='mini'
+ headless
+ />
+ </div>
+ <div className='mb-5 flex flex-wrap justify-center gap-5 lg:justify-start'>
+ <MetricCard
+ label={t('dashboard.seoClicks')}
+ value={data?.summary?.clicks ?? 0}
+ change={
+ data?.previousSummary
+ ? (data.summary?.clicks ?? 0) - data.previousSummary.clicks
+ : undefined
+ }
+ goodChangeDirection='down'
+ valueMapper={(value, type) =>
+ `${type === 'badge' && value > 0 ? '+' : ''}${nFormatter(value, 1)}`
+ }
+ />
+ <MetricCard
+ label={t('dashboard.seoImpressions')}
+ value={data?.summary?.impressions ?? 0}
+ change={
+ data?.previousSummary
+ ? (data.summary?.impressions ?? 0) -
+ data.previousSummary.impressions
+ : undefined
+ }
+ goodChangeDirection='down'
+ valueMapper={(value, type) =>
+ `${type === 'badge' && value > 0 ? '+' : ''}${nFormatter(value, 1)}`
+ }
+ />
+ <MetricCard
+ label={t('dashboard.seoAvgCTR')}
+ value={_round(data?.summary?.ctr ?? 0, 2)}
+ change={
+ data?.previousSummary
+ ? _round((data.summary?.ctr ?? 0) - data.previousSummary.ctr, 2)
+ : undefined
+ }
+ type='percent'
+ goodChangeDirection='down'
+ valueMapper={(value, type) =>
+ `${type === 'badge' && value > 0 ? '+' : ''}${value}%`
+ }
+ />
+ <MetricCard
+ label={t('dashboard.seoAvgPosition')}
+ value={_round(data?.summary?.position ?? 0, 1)}
+ change={
+ data?.previousSummary
+ ? _round(
+ (data.summary?.position ?? 0) -
+ data.previousSummary.position,
+ 1,
+ )
+ : undefined
+ }
+ goodChangeDirection='up'
+ valueMapper={(value, type) =>
+ `${type === 'badge' && value > 0 ? '+' : ''}${value}`
+ }
+ />
+ </div>
+ {anyMetricActive && !_isEmpty(aggregatedSeries) ? (
+ <MainChart
+ chartId='seo-main-chart'
+ options={chartOptions}
+ className='h-80 [&_svg]:overflow-visible!'
+ deps={[aggregatedSeries, activeMetrics, timeBucket, timeFormat]}
+ />
+ ) : null}
+ </div>
+
+ <div className='mt-3 grid grid-cols-1 gap-3 sm:grid-cols-2'>
+ <Panel
+ name={t('dashboard.seoSearchEngines')}
+ data={searchEngineEntries}
+ icon={panelIconMapping.ref}
+ id='seo-search-engines'
+ activeTabId='searchEngine'
+ disableRowClick
+ rowMapper={refRowMapper}
+ getFilterLink={noopFilterLink}
+ valuesHeaderName={t('project.visitors')}
+ />
+ <Panel
+ name={t('dashboard.seoAIReferrals')}
+ data={aiReferralEntries}
+ icon={<RobotIcon className='h-5 w-5' />}
+ id='seo-ai-referrals'
+ activeTabId='aiReferral'
+ disableRowClick
+ rowMapper={refRowMapper}
+ getFilterLink={noopFilterLink}
+ valuesHeaderName={t('project.visitors')}
+ />
+ </div>
+
+ <div className='mt-3 grid grid-cols-1 gap-3 sm:grid-cols-2'>
+ <Panel
+ name={t('dashboard.seoTopPages')}
+ data={topPagesAsEntries}
+ icon={panelIconMapping.pg}
+ id='pg'
+ activeTabId='pg'
+ disableRowClick={false}
+ getFilterLink={getFilterLink}
+ valuesHeaderName={t('dashboard.seoClicks')}
+ detailsExtraColumns={detailsExtraColumns}
+ hidePercentageInDetails
+ dataLoading={isLoading}
+ />
+ <Panel
+ name={t('dashboard.seoTopQueries')}
+ data={topQueriesAsEntries}
+ icon={<MagnifyingGlassIcon className='h-5 w-5' />}
+ id='keywords'
+ activeTabId='keywords'
+ disableRowClick={false}
+ getFilterLink={getFilterLink}
+ valuesHeaderName={t('dashboard.seoClicks')}
+ detailsExtraColumns={detailsExtraColumns}
+ hidePercentageInDetails
+ dataLoading={isLoading}
+ />
+ </div>
+ </>
+ )
+}
+
+const SEOView = ({ projectId, tnMapping }: SEOViewProps) => {
+ return (
+ <React.Suspense
+ fallback={
+ <div className='flex min-h-[400px] items-center justify-center'>
+ <Loader />
+ </div>
+ }
+ >
+ <SEOViewInner projectId={projectId} tnMapping={tnMapping} />
+ </React.Suspense>
+ )
+}
+
+export default SEOView
diff --git a/web/app/referrers.map.json b/web/app/referrers.map.json
index eaded6200..4e2117d51 100644
--- a/web/app/referrers.map.json
+++ b/web/app/referrers.map.json
@@ -1,9 +1,10 @@
[
{ "name": "Linktree", "patterns": ["linktr.ee"] },
- { "name": "Perplexity", "patterns": ["perplexity.ai"] },
+ { "name": "Perplexity", "patterns": ["perplexity.ai"], "category": "ai" },
{ "name": "Wikipedia", "patterns": ["wikipedia.org"] },
{
"name": "Yandex",
+ "category": "search",
"patterns": [
"yandex.ru",
"yandex.com",
@@ -17,14 +18,23 @@
{ "name": "GitHub", "patterns": ["github.com"] },
{
"name": "Google",
+ "category": "search",
"patterns": [
"google.com",
"doubleclick.net",
"android-app://com.google.android.gm/"
]
},
- { "name": "Bing", "patterns": ["bing.com", "ntp.msn.com"] },
- { "name": "DuckDuckGo", "patterns": ["duckduckgo.com", "ddg.gg"] },
+ {
+ "name": "Bing",
+ "category": "search",
+ "patterns": ["bing.com", "ntp.msn.com"]
+ },
+ {
+ "name": "DuckDuckGo",
+ "category": "search",
+ "patterns": ["duckduckgo.com", "ddg.gg"]
+ },
{
"name": "Reddit",
"patterns": ["reddit.com", "android-app://com.reddit.frontpage/"]
@@ -41,16 +51,32 @@
"name": "Microsoft Teams",
"patterns": ["teams.microsoft.com", "statics.teams.cdn.office.net"]
},
- { "name": "ChatGPT", "patterns": ["chatgpt.com"] },
- { "name": "Claude", "patterns": ["claude.ai"] },
+ { "name": "ChatGPT", "category": "ai", "patterns": ["chatgpt.com"] },
+ { "name": "Claude", "category": "ai", "patterns": ["claude.ai"] },
{ "name": "Telegram", "patterns": ["telegram.org", "t.me"] },
- { "name": "Sogou", "patterns": ["sogou.com"] },
- { "name": "Brave Search", "patterns": ["search.brave.com"] },
- { "name": "Ecosia", "patterns": ["ecosia.org"] },
- { "name": "Baidu", "patterns": ["baidu.com"] },
- { "name": "Yahoo!", "patterns": ["yahoo.com", "yahoo.co.jp"] },
- { "name": "Qwant", "patterns": ["www.qwant.com"] },
- { "name": "Startpage", "patterns": ["startpage.com"] },
+ { "name": "Sogou", "category": "search", "patterns": ["sogou.com"] },
+ {
+ "name": "Brave Search",
+ "category": "search",
+ "patterns": ["search.brave.com"]
+ },
+ { "name": "Ecosia", "category": "search", "patterns": ["ecosia.org"] },
+ { "name": "Baidu", "category": "search", "patterns": ["baidu.com"] },
+ {
+ "name": "Yahoo!",
+ "category": "search",
+ "patterns": ["yahoo.com", "yahoo.co.jp"]
+ },
+ { "name": "Qwant", "category": "search", "patterns": ["www.qwant.com"] },
+ { "name": "Startpage", "category": "search", "patterns": ["startpage.com"] },
{ "name": "Instagram", "patterns": ["instagram.com"] },
- { "name": "Discord", "patterns": ["discord.com", "discordapp.com"] }
+ { "name": "Discord", "patterns": ["discord.com", "discordapp.com"] },
+ { "name": "Gemini", "category": "ai", "patterns": ["gemini.google.com"] },
+ {
+ "name": "Copilot",
+ "category": "ai",
+ "patterns": ["copilot.microsoft.com"]
+ },
+ { "name": "OpenAI", "category": "ai", "patterns": ["openai.com"] },
+ { "name": "Kagi", "category": "ai", "patterns": ["kagi.com"] }
]
diff --git a/web/app/routes/api.analytics.ts b/web/app/routes/api.analytics.ts
index 6e61fdbca..48819b32a 100644
--- a/web/app/routes/api.analytics.ts
+++ b/web/app/routes/api.analytics.ts
@@ -32,6 +32,8 @@ import {
getProjectDataCustomEventsServer,
getUserFlowServer,
getGSCKeywordsServer,
+ getGSCDashboardServer,
+ getGSCDetailsServer,
getRevenueStatusServer,
getRevenueDataServer,
getOverallStatsServer,
@@ -62,6 +64,8 @@ import {
type ProjectDataCustomEventsResponse,
type UserFlowResponse,
type GSCKeywordsResponse,
+ type GSCDashboardResponse,
+ type GSCDetailsResponse,
type RevenueStatus,
type RevenueDataResponse,
type OverallObject,
@@ -117,6 +121,8 @@ interface ProxyRequest {
| 'getProjectDataCustomEvents'
| 'getUserFlow'
| 'getGSCKeywords'
+ | 'getGSCDashboard'
+ | 'getGSCDetails'
| 'getRevenueStatus'
| 'getRevenueData'
| 'getOverallStats'
@@ -786,6 +792,46 @@ export async function action({ request }: ActionFunctionArgs) {
})
}
+ case 'getGSCDashboard': {
+ const result = await getGSCDashboardServer(request, projectId, {
+ period: params.period,
+ from: formatDateForBackend(params.from),
+ to: formatDateForBackend(params.to),
+ timezone: params.timezone,
+ password: password || undefined,
+ timeBucket: params.timeBucket,
+ filters: params.filters,
+ })
+ return data<ProxyResponse<GSCDashboardResponse>>({
+ data: result.data,
+ error: result.error
+ ? Array.isArray(result.error)
+ ? result.error.join(', ')
+ : result.error
+ : null,
+ })
+ }
+
+ case 'getGSCDetails': {
+ const result = await getGSCDetailsServer(request, projectId, {
+ period: params.period,
+ from: formatDateForBackend(params.from),
+ to: formatDateForBackend(params.to),
+ timezone: params.timezone,
+ password: password || undefined,
+ page: (body as any).page,
+ query: (body as any).query,
+ })
+ return data<ProxyResponse<GSCDetailsResponse>>({
+ data: result.data,
+ error: result.error
+ ? Array.isArray(result.error)
+ ? result.error.join(', ')
+ : result.error
+ : null,
+ })
+ }
+
case 'getRevenueStatus': {
const result = await getRevenueStatusServer(request, projectId)
return data<ProxyResponse<RevenueStatus>>({
diff --git a/web/app/routes/projects.$id.tsx b/web/app/routes/projects.$id.tsx
index e724719ea..d2624e57f 100644
--- a/web/app/routes/projects.$id.tsx
+++ b/web/app/routes/projects.$id.tsx
@@ -167,6 +167,7 @@ export const meta: MetaFunction<typeof loader> = ({ data, location }) => {
const tabNames: Record<keyof typeof PROJECT_TABS | 'settings', string> = {
[PROJECT_TABS.traffic]: t('dashboard.traffic'),
[PROJECT_TABS.performance]: t('dashboard.performance'),
+ [PROJECT_TABS.seo]: t('dashboard.seo'),
[PROJECT_TABS.profiles]: t('dashboard.profiles'),
[PROJECT_TABS.sessions]: t('dashboard.sessions'),
[PROJECT_TABS.errors]: t('dashboard.errors'),
@@ -478,6 +479,13 @@ export async function loader({ request, params }: LoaderFunctionArgs) {
customEvents,
).then((res) => res.data)
}
+ } else if (tab === PROJECT_TABS.seo) {
+ // Fetch traffic data for referral breakdowns (search engines / AI referrals)
+ trafficData = getProjectDataServer(
+ request,
+ projectId,
+ analyticsParams,
+ ).then((res) => res.data)
} else if (tab === PROJECT_TABS.performance) {
// Use measure from URL, or 'quantiles' if perfMetric is quantiles
const effectiveMeasure =
diff --git a/web/app/utils/referrers.ts b/web/app/utils/referrers.ts
index 70b3a053d..d7abf393b 100644
--- a/web/app/utils/referrers.ts
+++ b/web/app/utils/referrers.ts
@@ -2,13 +2,23 @@ import type { Entry } from '~/lib/models/Entry'
import MAP from '../referrers.map.json'
+type ReferrerCategory = 'search' | 'ai'
+
type ReferrerMapping = {
name: string
patterns: string[]
+ category?: ReferrerCategory
}
const REFERRER_MAP: ReferrerMapping[] = MAP as ReferrerMapping[]
+const SEARCH_ENGINE_NAMES = new Set(
+ REFERRER_MAP.filter((m) => m.category === 'search').map((m) => m.name),
+)
+const AI_REFERRAL_NAMES = new Set(
+ REFERRER_MAP.filter((m) => m.category === 'ai').map((m) => m.name),
+)
+
const extractHostname = (value: string | null | undefined): string | null => {
if (!value) return null
try {
@@ -97,6 +107,16 @@ export const groupRefEntries = (entries: Entry[]): Entry[] => {
return list.sort((a, b) => b.count - a.count)
}
+export const getSearchEngineReferrals = (entries: Entry[]): Entry[] => {
+ const grouped = groupRefEntries(entries)
+ return grouped.filter((e) => e.name && SEARCH_ENGINE_NAMES.has(e.name))
+}
+
+export const getAIReferrals = (entries: Entry[]): Entry[] => {
+ const grouped = groupRefEntries(entries)
+ return grouped.filter((e) => e.name && AI_REFERRAL_NAMES.has(e.name))
+}
+
export const getFaviconHost = (value: string | null): string | null => {
if (!value) return null
diff --git a/web/public/locales/en.json b/web/public/locales/en.json
index da9bbb826..811ba198b 100644
--- a/web/public/locales/en.json
+++ b/web/public/locales/en.json
@@ -1085,6 +1085,34 @@
"cumulativeMode": "Cumulative mode",
"traffic": "Traffic",
"performance": "Performance",
+ "seo": "SEO",
+ "seoDesc": "Search performance for {{url}}",
+ "seoConnectGSC": "Connect Google Search Console to see search performance data",
+ "seoConnectGSCDesc": "Link your Google Search Console account to view clicks, impressions, search queries, and top pages from Google Search.",
+ "seoConnectButton": "Connect Search Console",
+ "seoSearchEngines": "Search engines",
+ "seoAIReferrals": "AI referrals",
+ "seoClicks": "Clicks",
+ "seoImpressions": "Impressions",
+ "seoAvgCTR": "Avg CTR",
+ "seoAvgPosition": "Avg Position",
+ "seoClicksAndImpressions": "Clicks & Impressions",
+ "seoAvgPositionChart": "Avg Position",
+ "seoCTRvsPosition": "CTR vs Position",
+ "seoTopPages": "Top pages",
+ "seoTopQueries": "Top queries",
+ "seoQueriesForPage": "Queries for this page",
+ "seoPagesForQuery": "Pages ranking for this query",
+ "seoPage": "Page",
+ "seoQuery": "Query",
+ "seoCTR": "CTR",
+ "seoPosition": "Pos.",
+ "seoLowerIsBetter": "Lower is better",
+ "seoYourCTR": "Your CTR",
+ "seoBenchmark": "Benchmark",
+ "seoSearchPages": "Search pages",
+ "seoSearchQueries": "Search queries",
+ "seoNoProperty": "No Search Console property selected. Go to Settings to select one.",
"profiles": "Profiles",
"funnels": "Funnels",
"sessions": "Sessions",
@@ -1609,7 +1637,9 @@
"entryPage": "Entry page",
"exitPage": "Exit page",
"keywords": "Keywords",
- "keyword": "Keyword"
+ "keyword": "Keyword",
+ "searchEngine": "Search engine",
+ "aiReferral": "AI referral"
},
"connectGsc": "Connect Google Search Console to see keywords for this project.",
"gscConnectionRequired": "Google Search Console connection is required to view keywords for this project. Ask the project administrator to connect it first.",