Web vitals: prefer external RUM
This commit is contained in:
@@ -1,6 +1,7 @@
|
||||
"use client";
|
||||
|
||||
import { memo, useEffect, useState } from "react";
|
||||
import { useMessages } from "../../../contexts/MessagesContext";
|
||||
import { logger } from "../../../../lib/logger";
|
||||
import WebVitalsDashboardView from "./WebVitalsDashboard.view";
|
||||
import type { Metrics, Vitals, VitalData } from "./WebVitalsDashboard.types";
|
||||
@@ -18,17 +19,55 @@ const createInitialVitals = (): Vitals => ({
|
||||
ttfb: createInitialVital(),
|
||||
});
|
||||
|
||||
function reportWebVitalToApi(
|
||||
metric: keyof Vitals,
|
||||
value: number,
|
||||
rating: VitalData["rating"],
|
||||
): void {
|
||||
if (typeof window === "undefined") return;
|
||||
if (rating === "unknown") return;
|
||||
|
||||
const body = {
|
||||
metric,
|
||||
data: { value, rating },
|
||||
url: window.location.href,
|
||||
userAgent: navigator.userAgent,
|
||||
timestamp: new Date().toISOString(),
|
||||
};
|
||||
|
||||
void fetch("/api/web-vitals", {
|
||||
method: "POST",
|
||||
headers: { "Content-Type": "application/json" },
|
||||
body: JSON.stringify(body),
|
||||
}).catch((err: unknown) => {
|
||||
logger.error("Web vitals ingest failed:", err);
|
||||
});
|
||||
}
|
||||
|
||||
const WebVitalsDashboardContainer = memo(() => {
|
||||
const m = useMessages();
|
||||
const copy = m.webVitalsDashboard;
|
||||
const [vitals, setVitals] = useState<Vitals>(createInitialVitals);
|
||||
const [metrics, setMetrics] = useState<Metrics>({});
|
||||
const [loading, setLoading] = useState(true);
|
||||
const [storage, setStorage] = useState<"external" | "local">("local");
|
||||
|
||||
const rumDashboardUrl =
|
||||
typeof process.env.NEXT_PUBLIC_RUM_DASHBOARD_URL === "string" &&
|
||||
process.env.NEXT_PUBLIC_RUM_DASHBOARD_URL.trim() !== ""
|
||||
? process.env.NEXT_PUBLIC_RUM_DASHBOARD_URL.trim()
|
||||
: null;
|
||||
|
||||
useEffect(() => {
|
||||
const fetchVitals = async () => {
|
||||
try {
|
||||
const response = await fetch("/api/web-vitals");
|
||||
const data = (await response.json()) as { metrics?: Metrics };
|
||||
const data = (await response.json()) as {
|
||||
metrics?: Metrics;
|
||||
storage?: "external" | "local";
|
||||
};
|
||||
setMetrics(data.metrics || {});
|
||||
setStorage(data.storage === "external" ? "external" : "local");
|
||||
} catch (error) {
|
||||
logger.error("Error fetching web vitals:", error);
|
||||
} finally {
|
||||
@@ -39,77 +78,71 @@ const WebVitalsDashboardContainer = memo(() => {
|
||||
fetchVitals();
|
||||
|
||||
if (typeof window !== "undefined") {
|
||||
import("web-vitals").then((webVitals) => {
|
||||
// web-vitals v4 typings don't expose legacy get* names the same way; runtime bundle still provides them for this dashboard.
|
||||
const { getCLS, getFID, getFCP, getLCP, getTTFB } =
|
||||
webVitals as unknown as {
|
||||
getCLS: (
|
||||
_fn: (_m: { value: number; rating: string }) => void,
|
||||
) => void;
|
||||
getFID: (
|
||||
_fn: (_m: { value: number; rating: string }) => void,
|
||||
) => void;
|
||||
getFCP: (
|
||||
_fn: (_m: { value: number; rating: string }) => void,
|
||||
) => void;
|
||||
getLCP: (
|
||||
_fn: (_m: { value: number; rating: string }) => void,
|
||||
) => void;
|
||||
getTTFB: (
|
||||
_fn: (_m: { value: number; rating: string }) => void,
|
||||
) => void;
|
||||
};
|
||||
// web-vitals v4+ exposes onLCP / onCLS / … — legacy getLCP was removed.
|
||||
import("web-vitals").then(
|
||||
({ onCLS, onFID, onFCP, onLCP, onTTFB }) => {
|
||||
onLCP((metric) => {
|
||||
const rating = metric.rating as VitalData["rating"];
|
||||
setVitals((prev) => ({
|
||||
...prev,
|
||||
lcp: {
|
||||
value: Math.round(metric.value),
|
||||
rating,
|
||||
},
|
||||
}));
|
||||
reportWebVitalToApi("lcp", Math.round(metric.value), rating);
|
||||
});
|
||||
|
||||
getLCP((metric: { value: number; rating: VitalData["rating"] }) => {
|
||||
setVitals((prev) => ({
|
||||
...prev,
|
||||
lcp: {
|
||||
value: Math.round(metric.value),
|
||||
rating: metric.rating,
|
||||
},
|
||||
}));
|
||||
});
|
||||
onFID((metric) => {
|
||||
const rating = metric.rating as VitalData["rating"];
|
||||
setVitals((prev) => ({
|
||||
...prev,
|
||||
fid: {
|
||||
value: Math.round(metric.value),
|
||||
rating,
|
||||
},
|
||||
}));
|
||||
reportWebVitalToApi("fid", Math.round(metric.value), rating);
|
||||
});
|
||||
|
||||
getFID((metric: { value: number; rating: VitalData["rating"] }) => {
|
||||
setVitals((prev) => ({
|
||||
...prev,
|
||||
fid: {
|
||||
value: Math.round(metric.value),
|
||||
rating: metric.rating,
|
||||
},
|
||||
}));
|
||||
});
|
||||
onCLS((metric) => {
|
||||
const rounded = Math.round(metric.value * 1000) / 1000;
|
||||
const rating = metric.rating as VitalData["rating"];
|
||||
setVitals((prev) => ({
|
||||
...prev,
|
||||
cls: {
|
||||
value: rounded,
|
||||
rating,
|
||||
},
|
||||
}));
|
||||
reportWebVitalToApi("cls", rounded, rating);
|
||||
});
|
||||
|
||||
getCLS((metric: { value: number; rating: VitalData["rating"] }) => {
|
||||
setVitals((prev) => ({
|
||||
...prev,
|
||||
cls: {
|
||||
value: Math.round(metric.value * 1000) / 1000,
|
||||
rating: metric.rating,
|
||||
},
|
||||
}));
|
||||
});
|
||||
onFCP((metric) => {
|
||||
const rating = metric.rating as VitalData["rating"];
|
||||
setVitals((prev) => ({
|
||||
...prev,
|
||||
fcp: {
|
||||
value: Math.round(metric.value),
|
||||
rating,
|
||||
},
|
||||
}));
|
||||
reportWebVitalToApi("fcp", Math.round(metric.value), rating);
|
||||
});
|
||||
|
||||
getFCP((metric: { value: number; rating: VitalData["rating"] }) => {
|
||||
setVitals((prev) => ({
|
||||
...prev,
|
||||
fcp: {
|
||||
value: Math.round(metric.value),
|
||||
rating: metric.rating,
|
||||
},
|
||||
}));
|
||||
});
|
||||
|
||||
getTTFB((metric: { value: number; rating: VitalData["rating"] }) => {
|
||||
setVitals((prev) => ({
|
||||
...prev,
|
||||
ttfb: {
|
||||
value: Math.round(metric.value),
|
||||
rating: metric.rating,
|
||||
},
|
||||
}));
|
||||
});
|
||||
});
|
||||
onTTFB((metric) => {
|
||||
const rating = metric.rating as VitalData["rating"];
|
||||
setVitals((prev) => ({
|
||||
...prev,
|
||||
ttfb: {
|
||||
value: Math.round(metric.value),
|
||||
rating,
|
||||
},
|
||||
}));
|
||||
reportWebVitalToApi("ttfb", Math.round(metric.value), rating);
|
||||
});
|
||||
},
|
||||
);
|
||||
}
|
||||
}, []);
|
||||
|
||||
@@ -118,6 +151,9 @@ const WebVitalsDashboardContainer = memo(() => {
|
||||
vitals={vitals}
|
||||
metrics={metrics}
|
||||
loading={loading}
|
||||
storage={storage}
|
||||
copy={copy}
|
||||
rumDashboardUrl={rumDashboardUrl}
|
||||
/>
|
||||
);
|
||||
});
|
||||
|
||||
@@ -1,3 +1,5 @@
|
||||
import type messages from "../../../../messages/en/index";
|
||||
|
||||
export interface VitalData {
|
||||
value: number;
|
||||
rating: "good" | "needs-improvement" | "poor" | "unknown";
|
||||
@@ -26,8 +28,13 @@ export interface Metrics {
|
||||
[key: string]: MetricData;
|
||||
}
|
||||
|
||||
export type WebVitalsDashboardCopy = typeof messages.webVitalsDashboard;
|
||||
|
||||
export interface WebVitalsDashboardViewProps {
|
||||
vitals: Vitals;
|
||||
metrics: Metrics;
|
||||
loading: boolean;
|
||||
storage: "external" | "local";
|
||||
copy: WebVitalsDashboardCopy;
|
||||
rumDashboardUrl: string | null;
|
||||
}
|
||||
|
||||
@@ -26,17 +26,20 @@ const getRatingIcon = (rating: string): string => {
|
||||
}
|
||||
};
|
||||
|
||||
const formatValue = (metric: string, value: number): string => {
|
||||
function formatValue(metric: string, value: number): string {
|
||||
if (metric === "cls") {
|
||||
return value.toFixed(3);
|
||||
}
|
||||
return `${value}ms`;
|
||||
};
|
||||
}
|
||||
|
||||
function WebVitalsDashboardView({
|
||||
vitals,
|
||||
metrics,
|
||||
loading,
|
||||
storage,
|
||||
copy,
|
||||
rumDashboardUrl,
|
||||
}: WebVitalsDashboardViewProps) {
|
||||
if (loading) {
|
||||
return (
|
||||
@@ -59,9 +62,31 @@ function WebVitalsDashboardView({
|
||||
return (
|
||||
<div className="p-6 bg-white rounded-lg shadow-lg">
|
||||
<h2 className="text-2xl font-bold mb-6 text-[var(--color-content-default-primary)]">
|
||||
Web Vitals Dashboard
|
||||
{copy.title}
|
||||
</h2>
|
||||
|
||||
{storage === "external" && (
|
||||
<div
|
||||
className="mb-6 p-4 rounded-lg border border-[var(--color-border-default-primary)] bg-[var(--color-surface-default-secondary)] text-[var(--font-size-body-medium)] text-[var(--color-content-default-secondary)]"
|
||||
role="status"
|
||||
>
|
||||
<p className="font-semibold text-[var(--color-content-default-primary)] mb-2">
|
||||
{copy.externalNoticeTitle}
|
||||
</p>
|
||||
<p className="mb-3">{copy.externalNoticeBody}</p>
|
||||
{rumDashboardUrl ? (
|
||||
<a
|
||||
href={rumDashboardUrl}
|
||||
target="_blank"
|
||||
rel="noopener noreferrer"
|
||||
className="text-[var(--color-content-default-primary)] underline font-medium"
|
||||
>
|
||||
{copy.externalDashboardLinkLabel}
|
||||
</a>
|
||||
) : null}
|
||||
</div>
|
||||
)}
|
||||
|
||||
<div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-4 mb-6">
|
||||
{Object.entries(vitals).map(([metric, data]) => (
|
||||
<div
|
||||
@@ -74,21 +99,20 @@ function WebVitalsDashboardView({
|
||||
</div>
|
||||
<div className="text-sm">
|
||||
<div className="font-medium">
|
||||
Value: {formatValue(metric, data.value)}
|
||||
{copy.valueLabel}: {formatValue(metric, data.value)}
|
||||
</div>
|
||||
<div className="capitalize">
|
||||
Rating: {data.rating.replace("-", " ")}
|
||||
{copy.ratingLabel}: {data.rating.replace("-", " ")}
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
|
||||
{/* Historical Metrics */}
|
||||
{Object.keys(metrics).length > 0 && (
|
||||
<div className="mb-6">
|
||||
<h3 className="text-lg font-semibold mb-4 text-[var(--color-content-default-primary)]">
|
||||
Historical Metrics
|
||||
{copy.historicalMetricsTitle}
|
||||
</h3>
|
||||
<div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-4">
|
||||
{Object.entries(metrics).map(([metric, data]) => (
|
||||
@@ -98,20 +122,26 @@ function WebVitalsDashboardView({
|
||||
>
|
||||
<h4 className="font-semibold mb-2">{metric.toUpperCase()}</h4>
|
||||
<div className="text-sm space-y-1">
|
||||
<div>Count: {data.count}</div>
|
||||
<div>Average: {formatValue(metric, data.average)}</div>
|
||||
<div>
|
||||
Range: {formatValue(metric, data.min)} -{" "}
|
||||
{copy.countLabel}: {data.count}
|
||||
</div>
|
||||
<div>
|
||||
{copy.averageLabel}: {formatValue(metric, data.average)}
|
||||
</div>
|
||||
<div>
|
||||
{copy.rangeLabel}: {formatValue(metric, data.min)} -{" "}
|
||||
{formatValue(metric, data.max)}
|
||||
</div>
|
||||
<div className="flex gap-2 text-xs">
|
||||
<span className="text-green-600">
|
||||
Good: {data.goodCount}
|
||||
{copy.goodLabel}: {data.goodCount}
|
||||
</span>
|
||||
<span className="text-yellow-600">
|
||||
Needs Improvement: {data.needsImprovementCount}
|
||||
{copy.needsImprovementLabel}: {data.needsImprovementCount}
|
||||
</span>
|
||||
<span className="text-red-600">
|
||||
{copy.poorLabel}: {data.poorCount}
|
||||
</span>
|
||||
<span className="text-red-600">Poor: {data.poorCount}</span>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
@@ -120,32 +150,16 @@ function WebVitalsDashboardView({
|
||||
</div>
|
||||
)}
|
||||
|
||||
{/* Performance Guidelines */}
|
||||
<div className="p-4 bg-[var(--color-surface-default-secondary)] rounded-lg">
|
||||
<h3 className="font-semibold mb-2 text-[var(--color-content-default-primary)]">
|
||||
Performance Guidelines
|
||||
{copy.performanceGuidelinesTitle}
|
||||
</h3>
|
||||
<ul className="text-sm space-y-1 text-[var(--color-content-default-secondary)]">
|
||||
<li>
|
||||
• <strong>LCP:</strong> Good < 2.5s, Needs Improvement 2.5-4s,
|
||||
Poor > 4s
|
||||
</li>
|
||||
<li>
|
||||
• <strong>FID:</strong> Good < 100ms, Needs Improvement
|
||||
100-300ms, Poor > 300ms
|
||||
</li>
|
||||
<li>
|
||||
• <strong>CLS:</strong> Good < 0.1, Needs Improvement 0.1-0.25,
|
||||
Poor > 0.25
|
||||
</li>
|
||||
<li>
|
||||
• <strong>FCP:</strong> Good < 1.8s, Needs Improvement 1.8-3s,
|
||||
Poor > 3s
|
||||
</li>
|
||||
<li>
|
||||
• <strong>TTFB:</strong> Good < 800ms, Needs Improvement
|
||||
800-1800ms, Poor > 1800ms
|
||||
</li>
|
||||
<li>• {copy.guidelines.lcp}</li>
|
||||
<li>• {copy.guidelines.fid}</li>
|
||||
<li>• {copy.guidelines.cls}</li>
|
||||
<li>• {copy.guidelines.fcp}</li>
|
||||
<li>• {copy.guidelines.ttfb}</li>
|
||||
</ul>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
Reference in New Issue
Block a user