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!

fix: improve SEO loading state and GSC long-range data

Blue Mouse4b93d5aae369
diff --git a/backend/apps/cloud/src/analytics/analytics.controller.ts b/backend/apps/cloud/src/analytics/analytics.controller.ts
index dd608effc..7e76bb1e3 100644
--- a/backend/apps/cloud/src/analytics/analytics.controller.ts
+++ b/backend/apps/cloud/src/analytics/analytics.controller.ts
@@ -43,7 +43,7 @@ import { DEFAULT_TIMEZONE } from '../user/entities/user.entity'
import { AuthenticationGuard } from '../auth/guards/authentication.guard'
import { PageviewsDto } from './dto/pageviews.dto'
import { EventsDto } from './dto/events.dto'
-import { GetDataDto, ChartRenderMode } from './dto/getData.dto'
+import { GetDataDto, ChartRenderMode, TimeBucketType } from './dto/getData.dto'
import { GetCustomEventMetadata } from './dto/get-custom-event-meta.dto'
import { GetPagePropertyMetaDto } from './dto/get-page-property-meta.dto'
import { GetUserFlowDto } from './dto/getUserFlow.dto'
@@ -1084,9 +1084,16 @@ export class AnalyticsController {
await this.analyticsService.checkBillingAccess(pid)
- const finalTimeBucket =
- timeBucket ||
- (['1h', 'today', 'yesterday', '1d'].includes(period) ? 'hour' : 'day')
+ const defaultTimeBucket = ['1h', 'today', 'yesterday', '1d'].includes(
+ period,
+ )
+ ? TimeBucketType.HOUR
+ : TimeBucketType.DAY
+ const finalTimeBucket = (timeBucket || defaultTimeBucket) as TimeBucketType
+ let groupTimeBucket: TimeBucketType | null = finalTimeBucket
+ if (period === 'all' || period === 'custom') {
+ groupTimeBucket = null
+ }
this.logger.log(
`pid: ${pid}, period: ${period}, timeBucket: ${finalTimeBucket}, filters: ${filters}`,
@@ -1099,7 +1106,7 @@ export class AnalyticsController {
const { groupFrom, groupTo } = this.analyticsService.getGroupFromTo(
from,
to,
- null,
+ groupTimeBucket,
period,
safeTimezone,
diff,
diff --git a/backend/apps/cloud/src/project/gsc.service.ts b/backend/apps/cloud/src/project/gsc.service.ts
index c01dcdb9f..b174775cd 100644
--- a/backend/apps/cloud/src/project/gsc.service.ts
+++ b/backend/apps/cloud/src/project/gsc.service.ts
@@ -41,6 +41,7 @@ const MAX_ROW_LIMIT = 25000
const MAX_BRANDED_PAGES = 10
const MAX_FILTER_EXPRESSION_LENGTH = 500
const MAX_FILTERS = 20
+const MAX_EXPENSIVE_ANALYTICS_RANGE_DAYS = 180
const IMPRESSION_POSITION_BUCKETS = [
{ key: 'pos1To3', label: '1-3' },
@@ -511,7 +512,7 @@ export class GSCService {
}
} else if (column === 'device' || column === 'dv') {
dimension = 'device'
- expression = expression.toLowerCase()
+ expression = expression.toUpperCase()
} else {
continue
}
@@ -747,9 +748,9 @@ export class GSCService {
try {
const rows = await this.queryGSC(gsc, from, to, {
- dimensions: isHourly ? ['HOUR'] : ['date'],
+ dimensions: isHourly ? ['hour'] : ['date'],
rowLimit: 5000,
- dataState: isHourly ? 'HOURLY_ALL' : 'all',
+ dataState: isHourly ? 'hourly_all' : 'all',
dimensionFilterGroups,
})
@@ -1091,6 +1092,9 @@ export class GSCService {
const fromDate = dayjs(from)
const toDate = dayjs(to)
const durationMs = toDate.diff(fromDate)
+ const rangeDays = Math.abs(toDate.diff(fromDate, 'day'))
+ const shouldLoadExpensiveAnalytics =
+ rangeDays <= MAX_EXPENSIVE_ANALYTICS_RANGE_DAYS
const prevTo = fromDate
.subtract(1, 'millisecond')
.format('YYYY-MM-DD HH:mm:ss')
@@ -1116,10 +1120,17 @@ export class GSCService {
this.getKeywords(pid, from, to, 50, 0, filtersStr, undefined, ctx),
this.getTopCountries(pid, from, to, 50, 0, filtersStr, ctx),
this.getTopDevices(pid, from, to, 50, 0, filtersStr, ctx),
- this.getBrandedTraffic(pid, from, to, filtersStr, ctx),
- this.getPositionAnalytics(pid, from, to, filtersStr, ctx).catch(() =>
- emptyPositionAnalytics(),
- ),
+ shouldLoadExpensiveAnalytics
+ ? this.getBrandedTraffic(pid, from, to, filtersStr, ctx).catch(() => ({
+ branded: 0,
+ nonBranded: 0,
+ }))
+ : Promise.resolve({ branded: 0, nonBranded: 0 }),
+ shouldLoadExpensiveAnalytics
+ ? this.getPositionAnalytics(pid, from, to, filtersStr, ctx).catch(() =>
+ emptyPositionAnalytics(),
+ )
+ : Promise.resolve(emptyPositionAnalytics()),
])
return {
diff --git a/backend/apps/community/src/analytics/analytics.controller.ts b/backend/apps/community/src/analytics/analytics.controller.ts
index 80d35a8fd..39e718913 100644
--- a/backend/apps/community/src/analytics/analytics.controller.ts
+++ b/backend/apps/community/src/analytics/analytics.controller.ts
@@ -40,7 +40,7 @@ import { DEFAULT_TIMEZONE } from '../user/entities/user.entity'
import { AuthenticationGuard } from '../auth/guards/authentication.guard'
import { PageviewsDto } from './dto/pageviews.dto'
import { EventsDto } from './dto/events.dto'
-import { GetDataDto, ChartRenderMode } from './dto/getData.dto'
+import { GetDataDto, ChartRenderMode, TimeBucketType } from './dto/getData.dto'
import { GetFiltersDto } from './dto/get-filters.dto'
import { GetVersionFiltersDto } from './dto/get-version-filters.dto'
import { GetCustomEventMetadata } from './dto/get-custom-event-meta.dto'
@@ -2720,9 +2720,16 @@ export class AnalyticsController {
headers['x-password'],
)
- const finalTimeBucket =
- timeBucket ||
- (['1h', 'today', 'yesterday', '1d'].includes(period) ? 'hour' : 'day')
+ const defaultTimeBucket = ['1h', 'today', 'yesterday', '1d'].includes(
+ period,
+ )
+ ? TimeBucketType.HOUR
+ : TimeBucketType.DAY
+ const finalTimeBucket = (timeBucket || defaultTimeBucket) as TimeBucketType
+ let groupTimeBucket: TimeBucketType | null = finalTimeBucket
+ if (period === 'all' || period === 'custom') {
+ groupTimeBucket = null
+ }
this.logger.log(
`pid: ${pid}, period: ${period}, timeBucket: ${finalTimeBucket}, filters: ${filters}`,
@@ -2735,7 +2742,7 @@ export class AnalyticsController {
const { groupFrom, groupTo } = this.analyticsService.getGroupFromTo(
from,
to,
- null,
+ groupTimeBucket,
period,
safeTimezone,
diff,
diff --git a/backend/apps/community/src/project/gsc.service.ts b/backend/apps/community/src/project/gsc.service.ts
index d525ba03e..9ad84452e 100644
--- a/backend/apps/community/src/project/gsc.service.ts
+++ b/backend/apps/community/src/project/gsc.service.ts
@@ -41,6 +41,7 @@ const MAX_ROW_LIMIT = 25000
const MAX_BRANDED_PAGES = 10
const MAX_FILTER_EXPRESSION_LENGTH = 500
const MAX_FILTERS = 20
+const MAX_EXPENSIVE_ANALYTICS_RANGE_DAYS = 180
const IMPRESSION_POSITION_BUCKETS = [
{ key: 'pos1To3', label: '1-3' },
@@ -570,7 +571,7 @@ export class GSCService {
}
} else if (column === 'device' || column === 'dv') {
dimension = 'device'
- expression = expression.toLowerCase()
+ expression = expression.toUpperCase()
} else {
continue
}
@@ -808,9 +809,9 @@ export class GSCService {
try {
const rows = await this.queryGSC(gsc, from, to, {
- dimensions: isHourly ? ['HOUR'] : ['date'],
+ dimensions: isHourly ? ['hour'] : ['date'],
rowLimit: 5000,
- dataState: isHourly ? 'HOURLY_ALL' : 'all',
+ dataState: isHourly ? 'hourly_all' : 'all',
dimensionFilterGroups,
})
@@ -1156,6 +1157,9 @@ export class GSCService {
const fromDate = dayjs(from)
const toDate = dayjs(to)
const durationMs = toDate.diff(fromDate)
+ const rangeDays = Math.abs(toDate.diff(fromDate, 'day'))
+ const shouldLoadExpensiveAnalytics =
+ rangeDays <= MAX_EXPENSIVE_ANALYTICS_RANGE_DAYS
const prevTo = fromDate
.subtract(1, 'millisecond')
.format('YYYY-MM-DD HH:mm:ss')
@@ -1181,10 +1185,17 @@ export class GSCService {
this.getKeywords(pid, from, to, 50, 0, filtersStr, undefined, ctx),
this.getTopCountries(pid, from, to, 50, 0, filtersStr, ctx),
this.getTopDevices(pid, from, to, 50, 0, filtersStr, ctx),
- this.getBrandedTraffic(pid, from, to, filtersStr, ctx),
- this.getPositionAnalytics(pid, from, to, filtersStr, ctx).catch(() =>
- emptyPositionAnalytics(),
- ),
+ shouldLoadExpensiveAnalytics
+ ? this.getBrandedTraffic(pid, from, to, filtersStr, ctx).catch(() => ({
+ branded: 0,
+ nonBranded: 0,
+ }))
+ : Promise.resolve({ branded: 0, nonBranded: 0 }),
+ shouldLoadExpensiveAnalytics
+ ? this.getPositionAnalytics(pid, from, to, filtersStr, ctx).catch(() =>
+ emptyPositionAnalytics(),
+ )
+ : Promise.resolve(emptyPositionAnalytics()),
])
return {
diff --git a/web/app/api/api.server.ts b/web/app/api/api.server.ts
index 597c85713..58bed3dd1 100644
--- a/web/app/api/api.server.ts
+++ b/web/app/api/api.server.ts
@@ -49,6 +49,7 @@ interface ServerFetchOptions {
headers?: Record<string, string>
/** Skip authentication - for public endpoints */
skipAuth?: boolean
+ timeoutMs?: number
}
interface ServerFetchResult<T> {
@@ -69,6 +70,7 @@ export async function serverFetch<T = unknown>(
body,
headers: customHeaders = {},
skipAuth = false,
+ timeoutMs = 15000,
} = options
const cleanEndpoint = endpoint.startsWith('/') ? endpoint.slice(1) : endpoint
@@ -105,11 +107,15 @@ export async function serverFetch<T = unknown>(
: undefined
try {
- const response = await fetchWithTimeout(url, {
- method,
- headers: fetchHeaders,
- body: serializedBody,
- })
+ const response = await fetchWithTimeout(
+ url,
+ {
+ method,
+ headers: fetchHeaders,
+ body: serializedBody,
+ },
+ timeoutMs,
+ )
if ((response.status === 401 || response.status === 403) && !skipAuth) {
const refreshResult = await tryRefreshToken(request)
@@ -118,11 +124,15 @@ export async function serverFetch<T = unknown>(
fetchHeaders['Authorization'] =
`Bearer ${refreshResult.tokens.accessToken}`
- const retryResponse = await fetchWithTimeout(url, {
- method,
- headers: fetchHeaders,
- body: serializedBody,
- })
+ const retryResponse = await fetchWithTimeout(
+ url,
+ {
+ method,
+ headers: fetchHeaders,
+ body: serializedBody,
+ },
+ timeoutMs,
+ )
if (retryResponse.ok) {
const retryContentType = retryResponse.headers.get('content-type')
@@ -2801,6 +2811,7 @@ export async function getGSCDashboardServer(
`log/gsc-dashboard?${queryParams.toString()}`,
{
headers,
+ timeoutMs: 60000,
},
)
}
diff --git a/web/app/hooks/useAnalyticsProxy.ts b/web/app/hooks/useAnalyticsProxy.ts
index 2040f0d4e..db8985df8 100644
--- a/web/app/hooks/useAnalyticsProxy.ts
+++ b/web/app/hooks/useAnalyticsProxy.ts
@@ -1,4 +1,4 @@
-import { useCallback, useState } from 'react'
+import { useCallback, useRef, useState } from 'react'
import type {
SessionsResponse,
@@ -837,9 +837,12 @@ export function useGSCDashboardProxy() {
const [data, setData] = useState<GSCDashboardResponse | null>(null)
const [error, setError] = useState<string | null>(null)
const [isLoading, setIsLoading] = useState(false)
+ const requestIdRef = useRef(0)
const fetchDashboard = useCallback(
async (projectId: string, params: ClientAnalyticsParams = {}) => {
+ const requestId = requestIdRef.current + 1
+ requestIdRef.current = requestId
setIsLoading(true)
setError(null)
@@ -849,20 +852,32 @@ export function useGSCDashboardProxy() {
projectId,
params,
})
- setData(result.data)
+
+ if (requestId !== requestIdRef.current) {
+ return result.data
+ }
+
+ if (result.data) {
+ setData(result.data)
+ }
setError(result.error)
return result.data
} catch (err) {
- setError(err instanceof Error ? err.message : 'Unknown error')
+ if (requestId === requestIdRef.current) {
+ setError(err instanceof Error ? err.message : 'Unknown error')
+ }
return null
} finally {
- setIsLoading(false)
+ if (requestId === requestIdRef.current) {
+ setIsLoading(false)
+ }
}
},
[],
)
const resetData = useCallback(() => {
+ requestIdRef.current += 1
setData(null)
setError(null)
setIsLoading(false)
diff --git a/web/app/pages/Project/tabs/SEO/SEOView.tsx b/web/app/pages/Project/tabs/SEO/SEOView.tsx
index 023e79137..ea08fab3a 100644
--- a/web/app/pages/Project/tabs/SEO/SEOView.tsx
+++ b/web/app/pages/Project/tabs/SEO/SEOView.tsx
@@ -56,6 +56,7 @@ import type { ProjectLoaderData } from '~/routes/projects.$id'
import Checkbox from '~/ui/Checkbox'
import Dropdown from '~/ui/Dropdown'
import Loader from '~/ui/Loader'
+import LoadingBar from '~/ui/LoadingBar'
import { Text } from '~/ui/Text'
import Tooltip from '~/ui/Tooltip'
import { nFormatter } from '~/utils/generic'
@@ -103,10 +104,12 @@ const SEOViewInner = ({ projectId, tnMapping }: SEOViewProps) => {
isActiveCompare,
} = useViewProjectContext()
const { seoRefreshTrigger } = useRefreshTriggers()
- const { fetchDashboard, data, isLoading } = useGSCDashboardProxy()
+ const { fetchDashboard, data, error, isLoading } = useGSCDashboardProxy()
const {
fetchDashboard: fetchCompareDashboard,
data: compareData,
+ error: compareError,
+ isLoading: isCompareLoading,
resetData: resetCompareData,
} = useGSCDashboardProxy()
const [searchParams, setSearchParams] = useSearchParams()
@@ -237,6 +240,8 @@ const SEOViewInner = ({ projectId, tnMapping }: SEOViewProps) => {
const noopFilterLink = useCallback(() => '#', [])
const gscFilters = useMemo(() => getGSCCompatibleFilters(filters), [filters])
+ const gscLoading = isLoading || isCompareLoading
+ const gscError = error || compareError
const [isManualRefreshing, setIsManualRefreshing] = useState(false)
@@ -307,8 +312,11 @@ const SEOViewInner = ({ projectId, tnMapping }: SEOViewProps) => {
const handleManualRefresh = useCallback(async () => {
if (isManualRefreshing) return
setIsManualRefreshing(true)
- await loadData()
- setIsManualRefreshing(false)
+ try {
+ await loadData()
+ } finally {
+ setIsManualRefreshing(false)
+ }
}, [isManualRefreshing, loadData])
const manualRefreshButton = useMemo(
@@ -645,7 +653,7 @@ const SEOViewInner = ({ projectId, tnMapping }: SEOViewProps) => {
[t],
)
- if (isLoading && !data) {
+ if (gscLoading && !data) {
return (
<>
<DashboardHeader
@@ -666,6 +674,32 @@ const SEOViewInner = ({ projectId, tnMapping }: SEOViewProps) => {
)
}
+ if (gscError && !data) {
+ return (
+ <>
+ <DashboardHeader
+ showSearchButton={false}
+ showRefreshButton={false}
+ rightContent={
+ <ProjectViewHeaderActions
+ tnMapping={tnMapping}
+ extraActions={manualRefreshButton}
+ />
+ }
+ timeBucketSelectorItems={seoPeriodPairs}
+ />
+ <div className='mx-auto flex min-h-[400px] max-w-xl flex-col items-center justify-center px-4 text-center'>
+ <Text as='h3' size='lg' weight='medium'>
+ {t('apiNotifications.somethingWentWrong')}
+ </Text>
+ <Text as='p' size='sm' colour='secondary' className='mt-2'>
+ {gscError}
+ </Text>
+ </div>
+ </>
+ )
+ }
+
if (data?.notConnected) {
return (
<>
@@ -735,6 +769,7 @@ const SEOViewInner = ({ projectId, tnMapping }: SEOViewProps) => {
{filters.length > 0 ? (
<Filters className='mb-3' tnMapping={tnMapping} />
) : null}
+ {gscLoading && data ? <LoadingBar /> : 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'>
@@ -928,7 +963,7 @@ const SEOViewInner = ({ projectId, tnMapping }: SEOViewProps) => {
valuesHeaderName={t('project.seo.clicks')}
detailsExtraColumns={detailsExtraColumns}
hidePercentageInDetails
- dataLoading={isLoading}
+ dataLoading={gscLoading}
rowTooltipRenderer={seoGscRowTooltip}
rowTooltipFollowCursor
/>
@@ -943,7 +978,7 @@ const SEOViewInner = ({ projectId, tnMapping }: SEOViewProps) => {
valuesHeaderName={t('project.seo.clicks')}
detailsExtraColumns={detailsExtraColumns}
hidePercentageInDetails
- dataLoading={isLoading}
+ dataLoading={gscLoading}
rowTooltipRenderer={seoGscRowTooltip}
rowTooltipFollowCursor
/>
@@ -998,7 +1033,7 @@ const SEOViewInner = ({ projectId, tnMapping }: SEOViewProps) => {
valuesHeaderName={t('project.seo.clicks')}
detailsExtraColumns={detailsExtraColumns}
hidePercentageInDetails
- dataLoading={isLoading}
+ dataLoading={gscLoading}
/>
<Panel
name={t('project.devices')}
@@ -1013,7 +1048,7 @@ const SEOViewInner = ({ projectId, tnMapping }: SEOViewProps) => {
valuesHeaderName={t('project.seo.clicks')}
detailsExtraColumns={detailsExtraColumns}
hidePercentageInDetails
- dataLoading={isLoading}
+ dataLoading={gscLoading}
/>
</div>
</>