Add Web Vitals performance tracking (LCP, INP, CLS, FCP, TTFB)
End-to-end performance metrics tracking: dedicated database table with percentile aggregation, tracker collection behind data-perf attribute, /api/send handling, report API endpoints, and Performance dashboard page with threshold-based metric cards, time-series chart, and per-page breakdown. Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
This commit is contained in:
1 parent
8cd3c03702
commit
ce9e2416fb
24 files changed
+1028
-8
No files matched your search
@@ -0,0 +1,3 @@
|
||||
.sampleCount {
|
||||
color: var(--base-color-text-secondary);
|
||||
}
|
||||
@@ -0,0 +1,184 @@
|
||||
'use client';
|
||||
import { Column, Grid, Row, Text } from '@umami/react-zen';
|
||||
import { colord } from 'colord';
|
||||
import { useCallback, useMemo, useState } from 'react';
|
||||
import { BarChart } from '@/components/charts/BarChart';
|
||||
import { LoadingPanel } from '@/components/common/LoadingPanel';
|
||||
import { Panel } from '@/components/common/Panel';
|
||||
import { useLocale, useMessages, useResultQuery } from '@/components/hooks';
|
||||
import { ListTable } from '@/components/metrics/ListTable';
|
||||
import { MetricsBar } from '@/components/metrics/MetricsBar';
|
||||
import { PerformanceCard } from '@/components/metrics/PerformanceCard';
|
||||
import { renderDateLabels } from '@/lib/charts';
|
||||
import { CHART_COLORS, WEB_VITALS_THRESHOLDS } from '@/lib/constants';
|
||||
import { generateTimeSeries } from '@/lib/date';
|
||||
import { formatLongNumber } from '@/lib/format';
|
||||
import styles from './Performance.module.css';
|
||||
|
||||
export interface PerformanceProps {
|
||||
websiteId: string;
|
||||
startDate: Date;
|
||||
endDate: Date;
|
||||
unit: string;
|
||||
}
|
||||
|
||||
const METRICS = ['lcp', 'inp', 'cls', 'fcp', 'ttfb'] as const;
|
||||
|
||||
const METRIC_LABELS: Record<string, string> = {
|
||||
lcp: 'Largest Contentful Paint',
|
||||
inp: 'Interaction to Next Paint',
|
||||
cls: 'Cumulative Layout Shift',
|
||||
fcp: 'First Contentful Paint',
|
||||
ttfb: 'Time to First Byte',
|
||||
};
|
||||
|
||||
function formatMetricValue(metric: string, value: number): string {
|
||||
if (metric === 'cls') {
|
||||
return value.toFixed(3);
|
||||
}
|
||||
return `${Math.round(value)} ms`;
|
||||
}
|
||||
|
||||
export function Performance({ websiteId, startDate, endDate, unit }: PerformanceProps) {
|
||||
const [selectedMetric, setSelectedMetric] = useState<string>('lcp');
|
||||
const { t, labels } = useMessages();
|
||||
const { locale, dateLocale } = useLocale();
|
||||
|
||||
const { data, error, isLoading } = useResultQuery<any>('performance', {
|
||||
websiteId,
|
||||
startDate,
|
||||
endDate,
|
||||
metric: selectedMetric,
|
||||
});
|
||||
|
||||
const chartData: any = useMemo(() => {
|
||||
if (!data?.chart) return { datasets: [] };
|
||||
|
||||
const p50Color = colord(CHART_COLORS[0]);
|
||||
const p75Color = colord(CHART_COLORS[1]);
|
||||
const p95Color = colord(CHART_COLORS[2]);
|
||||
|
||||
return {
|
||||
datasets: [
|
||||
{
|
||||
label: 'p50',
|
||||
data: generateTimeSeries(
|
||||
data.chart.map((d: any) => ({ x: d.t, y: Number(d.p50) })),
|
||||
startDate,
|
||||
endDate,
|
||||
unit,
|
||||
dateLocale,
|
||||
),
|
||||
type: 'line',
|
||||
borderColor: p50Color.alpha(0.8).toRgbString(),
|
||||
backgroundColor: p50Color.alpha(0.1).toRgbString(),
|
||||
borderWidth: 2,
|
||||
fill: false,
|
||||
tension: 0.3,
|
||||
pointRadius: 2,
|
||||
},
|
||||
{
|
||||
label: 'p75',
|
||||
data: generateTimeSeries(
|
||||
data.chart.map((d: any) => ({ x: d.t, y: Number(d.p75) })),
|
||||
startDate,
|
||||
endDate,
|
||||
unit,
|
||||
dateLocale,
|
||||
),
|
||||
type: 'line',
|
||||
borderColor: p75Color.alpha(0.8).toRgbString(),
|
||||
backgroundColor: p75Color.alpha(0.1).toRgbString(),
|
||||
borderWidth: 2,
|
||||
fill: false,
|
||||
tension: 0.3,
|
||||
pointRadius: 2,
|
||||
},
|
||||
{
|
||||
label: 'p95',
|
||||
data: generateTimeSeries(
|
||||
data.chart.map((d: any) => ({ x: d.t, y: Number(d.p95) })),
|
||||
startDate,
|
||||
endDate,
|
||||
unit,
|
||||
dateLocale,
|
||||
),
|
||||
type: 'line',
|
||||
borderColor: p95Color.alpha(0.8).toRgbString(),
|
||||
backgroundColor: p95Color.alpha(0.1).toRgbString(),
|
||||
borderWidth: 2,
|
||||
fill: false,
|
||||
tension: 0.3,
|
||||
pointRadius: 2,
|
||||
},
|
||||
],
|
||||
};
|
||||
}, [data, startDate, endDate, unit]);
|
||||
|
||||
const renderXLabel = useCallback(renderDateLabels(unit, locale), [unit, locale]);
|
||||
|
||||
const threshold = WEB_VITALS_THRESHOLDS[selectedMetric as keyof typeof WEB_VITALS_THRESHOLDS];
|
||||
|
||||
return (
|
||||
<Column gap>
|
||||
<LoadingPanel data={data} isLoading={isLoading} error={error}>
|
||||
{data && (
|
||||
<Column gap>
|
||||
<Grid columns={{ base: '1fr 1fr', lg: 'repeat(5, 1fr)' }} gap>
|
||||
{METRICS.map(metric => (
|
||||
<PerformanceCard
|
||||
key={metric}
|
||||
metric={metric}
|
||||
value={Number(data.summary?.[metric]?.p75 || 0)}
|
||||
label={t(labels[metric]) || metric.toUpperCase()}
|
||||
formatValue={(n: number) => formatMetricValue(metric, n)}
|
||||
onClick={() => setSelectedMetric(metric)}
|
||||
selected={selectedMetric === metric}
|
||||
/>
|
||||
))}
|
||||
</Grid>
|
||||
<Panel>
|
||||
<Column gap="4" padding="4">
|
||||
<Row justifyContent="space-between" alignItems="center">
|
||||
<Text weight="bold">{METRIC_LABELS[selectedMetric]}</Text>
|
||||
<Row gap="4">
|
||||
<Text size="sm" className={styles.sampleCount}>
|
||||
{t(labels.sampleSize)}: {formatLongNumber(data.summary?.count || 0)}
|
||||
</Text>
|
||||
</Row>
|
||||
</Row>
|
||||
<BarChart
|
||||
chartData={chartData}
|
||||
minDate={startDate}
|
||||
maxDate={endDate}
|
||||
unit={unit}
|
||||
renderXLabel={renderXLabel}
|
||||
renderYLabel={(label: string) => {
|
||||
const val = Number(label);
|
||||
if (selectedMetric === 'cls') return val.toFixed(2);
|
||||
return `${Math.round(val)} ms`;
|
||||
}}
|
||||
height="400px"
|
||||
/>
|
||||
</Column>
|
||||
</Panel>
|
||||
<Panel>
|
||||
<ListTable
|
||||
title={t(labels.pages)}
|
||||
metric={t(labels[selectedMetric]) || selectedMetric.toUpperCase()}
|
||||
data={data.pages?.map(
|
||||
({ urlPath, p75, count }: { urlPath: string; p75: number; count: number }) => ({
|
||||
label: urlPath,
|
||||
count: Number(p75),
|
||||
percent: 0,
|
||||
}),
|
||||
)}
|
||||
renderLabel={({ label }: { label: string }) => <Text>{label}</Text>}
|
||||
/>
|
||||
</Panel>
|
||||
</Column>
|
||||
)}
|
||||
</LoadingPanel>
|
||||
</Column>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,18 @@
|
||||
'use client';
|
||||
import { Column } from '@umami/react-zen';
|
||||
import { WebsiteControls } from '@/app/(main)/websites/[websiteId]/WebsiteControls';
|
||||
import { useDateRange } from '@/components/hooks';
|
||||
import { Performance } from './Performance';
|
||||
|
||||
export function PerformancePage({ websiteId }: { websiteId: string }) {
|
||||
const {
|
||||
dateRange: { startDate, endDate, unit },
|
||||
} = useDateRange();
|
||||
|
||||
return (
|
||||
<Column gap>
|
||||
<WebsiteControls websiteId={websiteId} />
|
||||
<Performance websiteId={websiteId} startDate={startDate} endDate={endDate} unit={unit} />
|
||||
</Column>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,12 @@
|
||||
import type { Metadata } from 'next';
|
||||
import { PerformancePage } from './PerformancePage';
|
||||
|
||||
export default async function ({ params }: { params: Promise<{ websiteId: string }> }) {
|
||||
const { websiteId } = await params;
|
||||
|
||||
return <PerformancePage websiteId={websiteId} />;
|
||||
}
|
||||
|
||||
export const metadata: Metadata = {
|
||||
title: 'Performance',
|
||||
};
|
||||
@@ -0,0 +1,26 @@
|
||||
import { getQueryFilters, parseRequest, setWebsiteDate } from '@/lib/request';
|
||||
import { json, unauthorized } from '@/lib/response';
|
||||
import { reportResultSchema } from '@/lib/schema';
|
||||
import { canViewWebsite } from '@/permissions';
|
||||
import { getPerformance, type PerformanceParameters } from '@/queries/sql/reports/getPerformance';
|
||||
|
||||
export async function POST(request: Request) {
|
||||
const { auth, body, error } = await parseRequest(request, reportResultSchema);
|
||||
|
||||
if (error) {
|
||||
return error();
|
||||
}
|
||||
|
||||
const { websiteId } = body;
|
||||
|
||||
if (!(await canViewWebsite(auth, websiteId))) {
|
||||
return unauthorized();
|
||||
}
|
||||
|
||||
const parameters = await setWebsiteDate(websiteId, body.parameters);
|
||||
const filters = await getQueryFilters(body.filters, websiteId);
|
||||
|
||||
const data = await getPerformance(websiteId, parameters as PerformanceParameters, filters);
|
||||
|
||||
return json(data);
|
||||
}
|
||||
@@ -12,7 +12,7 @@ import { parseRequest } from '@/lib/request';
|
||||
import { badRequest, forbidden, json, serverError } from '@/lib/response';
|
||||
import { anyObjectParam, urlOrPathParam } from '@/lib/schema';
|
||||
import { safeDecodeURI, safeDecodeURIComponent } from '@/lib/url';
|
||||
import { createSession, saveEvent, saveSessionData } from '@/queries/sql';
|
||||
import { createSession, saveEvent, savePerformance, saveSessionData } from '@/queries/sql';
|
||||
|
||||
interface Cache {
|
||||
websiteId: string;
|
||||
@@ -22,7 +22,7 @@ interface Cache {
|
||||
}
|
||||
|
||||
const schema = z.object({
|
||||
type: z.enum(['event', 'identify']),
|
||||
type: z.enum(['event', 'identify', 'performance']),
|
||||
payload: z
|
||||
.object({
|
||||
website: z.uuid().optional(),
|
||||
@@ -44,6 +44,11 @@ const schema = z.object({
|
||||
browser: z.string().optional(),
|
||||
os: z.string().optional(),
|
||||
device: z.string().optional(),
|
||||
lcp: z.number().nonnegative().max(60000).optional(),
|
||||
inp: z.number().nonnegative().max(60000).optional(),
|
||||
cls: z.number().nonnegative().max(100).optional(),
|
||||
fcp: z.number().nonnegative().max(60000).optional(),
|
||||
ttfb: z.number().nonnegative().max(60000).optional(),
|
||||
})
|
||||
.refine(
|
||||
data => {
|
||||
@@ -83,6 +88,11 @@ export async function POST(request: Request) {
|
||||
tag,
|
||||
timestamp,
|
||||
id,
|
||||
lcp,
|
||||
inp,
|
||||
cls,
|
||||
fcp,
|
||||
ttfb,
|
||||
} = payload;
|
||||
|
||||
const sourceId = websiteId || pixelId || linkId;
|
||||
@@ -269,6 +279,23 @@ export async function POST(request: Request) {
|
||||
createdAt,
|
||||
});
|
||||
}
|
||||
} else if (type === COLLECTION_TYPE.performance) {
|
||||
const base = hostname ? `https://${hostname}` : 'https://localhost';
|
||||
const currentUrl = new URL(url, base);
|
||||
const urlPath = currentUrl.pathname === '/undefined' ? '' : currentUrl.pathname;
|
||||
|
||||
await savePerformance({
|
||||
websiteId: sourceId,
|
||||
sessionId,
|
||||
visitId,
|
||||
urlPath,
|
||||
lcp,
|
||||
inp,
|
||||
cls,
|
||||
fcp,
|
||||
ttfb,
|
||||
createdAt,
|
||||
});
|
||||
}
|
||||
|
||||
const token = createToken({ websiteId, sessionId, visitId, iat }, secret());
|
||||
|
||||
@@ -0,0 +1,33 @@
|
||||
import { z } from 'zod';
|
||||
import { getQueryFilters, parseRequest } from '@/lib/request';
|
||||
import { json, unauthorized } from '@/lib/response';
|
||||
import { dateRangeParams } from '@/lib/schema';
|
||||
import { canViewWebsite } from '@/permissions';
|
||||
import { getPerformanceStats } from '@/queries/sql';
|
||||
|
||||
export async function GET(
|
||||
request: Request,
|
||||
{ params }: { params: Promise<{ websiteId: string }> },
|
||||
) {
|
||||
const schema = z.object({
|
||||
...dateRangeParams,
|
||||
});
|
||||
|
||||
const { auth, query, error } = await parseRequest(request, schema);
|
||||
|
||||
if (error) {
|
||||
return error();
|
||||
}
|
||||
|
||||
const { websiteId } = await params;
|
||||
|
||||
if (!(await canViewWebsite(auth, websiteId))) {
|
||||
return unauthorized();
|
||||
}
|
||||
|
||||
const filters = await getQueryFilters(query, websiteId);
|
||||
|
||||
const data = await getPerformanceStats(websiteId, filters);
|
||||
|
||||
return json(data);
|
||||
}
|
||||
Reference in new issue
Block a user