如果需要在你的NextJS项目里接入一些谷歌的一些三方,那么可以使用NextJS官方库:
包含Google Tag Manager、Google Analytics、Google Maps Embed、YouTube Embed
基本上SaaS应用常用的一些三方库都有,官方也在不断的扩展中,但是在集成中有一些需要注意的点:
1.服务器端代码植入gtm:
如果您使用服务器端标签管理器并从标记服务器提供
gtm.js
脚本,则可以使用 gtmScriptUrl
选项指定脚本的 URL。2.服务端发送Google Analytics Event:
你可以在前端非常便捷的集成GA4:
import { GoogleAnalytics } from '@next/third-parties/google' export default function RootLayout({ children, }: { children: React.ReactNode }) { return ( <html lang="en"> <body>{children}</body> <GoogleAnalytics gaId="G-XYZ" /> </html> ) }
但是这样只能在前端发送事件,如果你想在服务端发送事件就不可以这样使用了,以下是正确的方法:
// 服务端 GA4 事件发送 export const sendGA4ServerEvent = async ( eventName: EventName, eventData: Record<string, any>, userId?: string, sessionId?: string, clientIdOverride?: string ) => { const measurementId = process.env.NEXT_PUBLIC_GOOGLE_ANALYTICS_ID const apiSecret = process.env.GOOGLE_ANALYTICS_API_SCRIPT if (!measurementId || !apiSecret) { console.warn('GA4 Measurement ID or API Secret not configured') return } try { const url = `https://www.google-analytics.com/mp/collect?measurement_id=${measurementId}&api_secret=${apiSecret}` // 优先顺序:显式传入 > cookie(ga_client_id) > 回退生成 let clientId = clientIdOverride if (!clientId) { clientId = await getGAClientId() } if (!clientId) { clientId = `server_${Date.now()}_${Math.random().toString(36).slice(2, 11)}` } const payload = { client_id: clientId, user_id: userId, events: [ { name: eventName, params: { ...eventData, session_id: sessionId, timestamp_micros: Date.now() * 1000, server_side: true, }, }, ], } const response = await fetch(url, { method: 'POST', headers: { 'Content-Type': 'application/json', }, body: JSON.stringify(payload), }) if (!response.ok) { console.warn( `GA4 server event failed: ${response.status} ${response.statusText}` ) } else { console.log(`GA4 server event sent: ${eventName}`) } } catch (error) { console.warn('Failed to send GA4 server event:', error) } }