筆記
您可能不需要此包。請先檢查第三方圖書館。
Google分析Next.js
此軟件包使用next.js Script標籤優化腳本加載,這意味著它將僅使用Next.js> = 11.0.0在應用程序上使用。
npm install --save nextjs-google-analytics
將GoogleAnalytics組件添加到trackPageViews Prop設置為true自定義應用程序文件:
// pages/_app.js
import { GoogleAnalytics } from "nextjs-google-analytics" ;
const App = ( { Component , pageProps } ) => {
return (
< >
< GoogleAnalytics trackPageViews />
< Component { ... pageProps } />
</ >
) ;
} ;
export default App ;您可以通過在NEXT_PUBLIC_GA_MEASUREMENT_ID環境變量或使用gaMeasurementId Prop上的GoogleAnalytics組件上設置Google Analytics(分析)測量ID 。如果設置兩個,則環境變量將覆蓋道具。
您的Google Analytics(分析)測量ID是從NEXT_PUBLIC_GA_MEASUREMENT_ID環境變量讀取的,因此請確保將其設置在您的生產環境中:
如果該變量未設置或空為空,則不會加載任何內容,從而可以安全地開發工作。
要加載並在開發中測試它,請補充:
NEXT_PUBLIC_GA_MEASUREMENT_ID="G-XXXXXXXXXX"
到您的.env.local文件。
作為替代方案,您可以使用gaMeasurementId參數通過Google Analytics(分析)測量ID 。
NEXT_PUBLIC_GA_MEASUREMENT_ID環境變量將優先於gaMeasurementId param,因此,如果兩個都設置為具有不同的值,則環境變量將覆蓋參數。
使用GoogleAnalytics組件加載GTAG腳本。您可以將其添加到自定義應用程序組件中,這將負責包含每個頁面的必要腳本(或者,如果需要更多控制,則可以按每個頁面添加):
// pages/_app.js
import { GoogleAnalytics } from "nextjs-google-analytics" ;
const App = ( { Component , pageProps } ) => {
return (
< >
< GoogleAnalytics />
< Component { ... pageProps } />
</ >
) ;
} ;
export default App ;默認情況下,使用afterInteractive策略加載腳本,這意味著它們被注入客戶端,並將在水合後運行。
如果您需要更多的控制權,則該組件將公開策略道具以控制腳本的加載方式:
// pages/_app.js
import { GoogleAnalytics } from "nextjs-google-analytics" ;
const App = ( { Component , pageProps } ) => {
return (
< >
< GoogleAnalytics strategy = "lazyOnload" />
< Component { ... pageProps } />
</ >
) ;
} ;
export default App ;另外,您可以通過使用替代方案來通過
< GoogleAnalytics gtagUrl = "/gtag.js" /> 要跟踪頁面視圖,將GoogleAnalytics組件的trackPageViews Prop設置為true。
// pages/_app.js
import { GoogleAnalytics } from "nextjs-google-analytics" ;
const App = ( { Component , pageProps } ) => {
return (
< >
< GoogleAnalytics trackPageViews />
< Component { ... pageProps } />
</ >
) ;
} ;
export default App ;默認情況下,如果啟用trackPageViews ,它將在哈希更改上觸發,但是您可以通過向trackPageViews提供對象來忽略哈希的更改:
// pages/_app.js
import { GoogleAnalytics } from "nextjs-google-analytics" ;
const App = ( { Component , pageProps } ) => {
return (
< >
< GoogleAnalytics trackPageViews = { { ignoreHashChange : true } } />
< Component { ... pageProps } />
</ >
) ;
} ;
export default App ;作為替代方案,您可以直接調用自定義應用程序組件中的usePageViews掛鉤,請勿在GoogleAnalytics組件上設置trackPageViews Prop或將其設置為false(默認):
// pages/_app.js
import { GoogleAnalytics , usePageViews } from "nextjs-google-analytics" ;
const App = ( { Component , pageProps } ) => {
usePageViews ( ) ; // IgnoreHashChange defaults to false
// usePageViews({ ignoreHashChange: true });
return (
< >
< GoogleAnalytics /> { /* or <GoogleAnalytics trackPageViews={false} /> */ }
< Component { ... pageProps } />
</ >
) ;
} ;
export default App ;該模塊還導出一個pageView函數,如果您需要更多的控件,則可以使用該功能。
您可以使用event功能跟踪自定義事件:
import { useState } from "react" ;
import Page from "../components/Page" ;
import { event } from "nextjs-google-analytics" ;
export function Contact ( ) {
const [ message , setMessage ] = useState ( "" ) ;
const handleInput = ( e ) => {
setMessage ( e . target . value ) ;
} ;
const handleSubmit = ( e ) => {
e . preventDefault ( ) ;
event ( "submit_form" , {
category : "Contact" ,
label : message ,
} ) ;
setState ( "" ) ;
} ;
return (
< Page >
< h1 > This is the Contact page </ h1 >
< form onSubmit = { handleSubmit } >
< label >
< span > Message: </ span >
< textarea onChange = { handleInput } value = { message } />
</ label >
< button type = "submit" > submit </ button >
</ form >
</ Page >
) ;
}有關event中可以指定的可能參數,請參閱Google標籤API參考中的event命令。
您可以使用consent功能來更新用戶的cookie首選項(GDPR)。
const consentValue : 'denied' | 'granted' = getUserCookiePreferenceFromLocalStorage ( ) ; // 'denied' or 'granted'
consent ( {
arg : 'update' ,
params : {
ad_storage : consentValue ,
analytics_storage : consentValue ,
ad_user_data : consentValue ,
ad_personalization : consentValue
} ,
} ) ;有關arg和params中可以指定的可能值,請參閱Google標籤API參考中的consent命令。
要將Next.js Web Vitals發送到Google Analytics(分析)您可以在自定義應用程序組件中的reportWebVitals函數上使用自定義事件:
// pages/_app.js
import { GoogleAnalytics , event } from "nextjs-google-analytics" ;
export function reportWebVitals ( { id , name , label , value } ) {
event ( name , {
category : label === "web-vital" ? "Web Vitals" : "Next.js custom metric" ,
value : Math . round ( name === "CLS" ? value * 1000 : value ) , // values must be integers
label : id , // id unique to current page load
nonInteraction : true , // avoids affecting bounce rate.
} ) ;
}
const App = ( { Component , pageProps } ) => {
return (
< >
< GoogleAnalytics />
< Component { ... pageProps } />
</ >
) ;
} ;
export default App ;如果您使用的是Typescript,則可以從next/app中導入NextWebVitalsMetric :
import type { NextWebVitalsMetric } from "next/app" ;
export function reportWebVitals ( metric : NextWebVitalsMetric ) {
// ...
} gaMeasurementId參數所有導出的組件,鉤子和功能,都接受可選的gaMeasurementId參數,以防萬一沒有提供環境變量:
// pages/_app.js
import { GoogleAnalytics , event } from "nextjs-google-analytics" ;
import { gaMeasurementId } from "./lib/gtag" ;
export function reportWebVitals ( {
id ,
name ,
label ,
value ,
} : NextWebVitalsMetric ) {
event (
name ,
{
category : label === "web-vital" ? "Web Vitals" : "Next.js custom metric" ,
value : Math . round ( name === "CLS" ? value * 1000 : value ) , // values must be integers
label : id , // id unique to current page load
nonInteraction : true , // avoids affecting bounce rate.
} ,
gaMeasurementId
) ;
}
const App = ( { Component , pageProps } ) => {
usePageViews ( { gaMeasurementId } ) ;
return (
< >
< GoogleAnalytics gaMeasurementId = { gaMeasurementId } />
< Component { ... pageProps } />
</ >
) ;
} ;
export default App ; 安裝Google Analytics(分析)調試器。
通過單擊地址欄右側的圖標來打開它。
打開Chrome JavaScript控制台以查看消息。
在Windows和Linux上,按Control-Shift-J。
在Mac上,按Command-Option-J。
刷新您所在的頁面。
該模塊用打字稿編寫,並包括類型定義。
歡迎貢獻,問題和功能請求!
如果您喜歡這個項目,請給!
麻省理工學院