fix: 修复 Vercel 统计函数传递导致的预渲染错误

This commit is contained in:
2026-02-24 08:45:13 +08:00
parent 67bba0c207
commit 4e30ddefc5
2 changed files with 26 additions and 22 deletions
+24
View File
@@ -0,0 +1,24 @@
"use client"
import { Analytics } from "@vercel/analytics/next"
import { SpeedInsights } from "@vercel/speed-insights/next"
const isTrackablePath = (url: string): boolean => {
try {
const pathname = new URL(url).pathname
// Only keep user-facing locale pages to control usage on the Hobby plan.
return pathname === "/zh" || pathname === "/en" || pathname.startsWith("/zh/") || pathname.startsWith("/en/")
} catch {
return false
}
}
export function VercelMetrics() {
return (
<>
<Analytics mode="production" beforeSend={(event) => (isTrackablePath(event.url) ? event : null)} />
<SpeedInsights sampleRate={0.2} beforeSend={(data) => (isTrackablePath(data.url) ? data : null)} />
</>
)
}
+2 -22
View File
@@ -1,6 +1,5 @@
import type { Metadata } from "next"
import { Analytics } from "@vercel/analytics/next"
import { SpeedInsights } from "@vercel/speed-insights/next"
import { VercelMetrics } from "./VercelMetrics"
import "./globals.css"
export const metadata: Metadata = {
@@ -10,17 +9,6 @@ export const metadata: Metadata = {
const isVercelProduction = process.env.VERCEL_ENV === "production"
const isTrackablePath = (url: string): boolean => {
try {
const pathname = new URL(url).pathname
// Only keep user-facing locale pages to control usage on the Hobby plan.
return pathname === "/zh" || pathname === "/en" || pathname.startsWith("/zh/") || pathname.startsWith("/en/")
} catch {
return false
}
}
export default function RootLayout({
children,
}: Readonly<{
@@ -30,15 +18,7 @@ export default function RootLayout({
<html lang="zh" suppressHydrationWarning>
<body className="font-sans antialiased">
{children}
{isVercelProduction ? (
<>
<Analytics mode="production" beforeSend={(event) => (isTrackablePath(event.url) ? event : null)} />
<SpeedInsights
sampleRate={0.2}
beforeSend={(data) => (isTrackablePath(data.url) ? data : null)}
/>
</>
) : null}
{isVercelProduction ? <VercelMetrics /> : null}
</body>
</html>
)