如何在 next.js 应用程序中使用 google 分析?
How to use google analytics with next.js app?
我将样式化组件与 next.js 一起使用,因此我的样式需要在服务器端呈现,因此如何向我的网站添加 google 分析?
我检查了 next.js google analytics example 但正如我所说,我的 _document 文件因使用样式化组件而不同。
// _document.js
import React from 'react'
import Document from 'next/document'
import { ServerStyleSheet } from 'styled-components'
class MyDocument extends Document {
static async getInitialProps(ctx) {
const sheet = new ServerStyleSheet()
const originalRenderPage = ctx.renderPage
try {
ctx.renderPage = () => originalRenderPage({
enhanceApp: (App) => (props) => sheet.collectStyles(<App {...props} />),
})
const initialProps = await Document.getInitialProps(ctx)
return {
...initialProps,
styles: (
<>
{initialProps.styles}
{sheet.getStyleElement()}
</>
),
}
} finally {
sheet.seal()
}
}
}
export default MyDocument
在您的 _document.js
中,您覆盖了 getInitialProps
方法。您还可以覆盖 render
方法。只需添加
render() {
return (
<Html lang={this.props.lang || "en"}>
<Head>
<script
dangerouslySetInnerHTML={{
__html: `[google analytics tracking code here]`
}}
/>
</Head>
<body>
<Main />
<NextScript />
</body>
</Html>
);
}
确保导入所需的组件:
import Document, { Html, Head, Main, NextScript } from "next/document"
要正确初始化 gtag
,请在 _document.js
或您定义 Head
的任何地方执行以下操作:
import { Head } from 'next/document';
export default class MyDocument extends Document {
render() {
return (
// ...
<Head>
<script
async
src="https://www.googletagmanager.com/gtag/js?id=[Tracking ID]"
/>
<script
dangerouslySetInnerHTML={{
__html: `
window.dataLayer = window.dataLayer || [];
function gtag(){dataLayer.push(arguments);}
gtag('js', new Date());
gtag('config', '[Tracking ID]', { page_path: window.location.pathname });
`,
}}
/>
</Head>
);
}
}
以上将跟踪页面加载时的页面浏览量。要跟踪导航,请将以下内容添加到 _app.js
:
import { useRouter } from 'next/router';
import { useEffect } from "react";
export default const App = () => {
const router = useRouter();
const handleRouteChange = (url) => {
window.gtag('config', '[Tracking ID]', {
page_path: url,
});
};
useEffect(() => {
router.events.on('routeChangeComplete', handleRouteChange);
return () => {
router.events.off('routeChangeComplete', handleRouteChange);
};
}, [router.events]);
return (
// ...
);
};
另请参阅:
另一种在没有 dangerouslySetInnerHTML
的情况下对我很有效的方法:
- 在 public 文件夹中创建一个新的 js 文件,其中包含
dangerouslySetInnerHTML
中的内容。
- 将创建的 js 文件添加到
_document.js
文件。
我的 _document.js
返回的示例:
<Html>
<Head>
<script async src="https://www.googletagmanager.com/gtag/js?id=UA-xxx-x"></script>
<script src="/ga.js" async></script>
{/*other scripts*/}
</Head>
<body>
<Main />
<NextScript />
</body>
</Html>
使用 Typescript
通过 NextJS 设置 Google 分析
我正在为我的个人网站 (https://github.com/GorvGoyl/Personal-Site-Gourav.io) 使用以下设置,它工作正常,没有任何 linting 错误。仅为生产启用分析。
- 创建 Google analytics project 并获取测量 ID。
- 在您的 NextJS 项目中,创建
/lib/gtag.ts
文件并添加您的 Google 测量 ID:
export const GA_TRACKING_ID = "<INSERT_TAG_ID>";
// https://developers.google.com/analytics/devguides/collection/gtagjs/pages
export const pageview = (url: URL): void => {
window.gtag("config", GA_TRACKING_ID, {
page_path: url,
});
};
type GTagEvent = {
action: string;
category: string;
label: string;
value: number;
};
// https://developers.google.com/analytics/devguides/collection/gtagjs/events
export const event = ({ action, category, label, value }: GTagEvent): void => {
window.gtag("event", action, {
event_category: category,
event_label: label,
value,
});
};
- 同时安装 gtag
types
:
npm i -D @types/gtag.js
- 创建
/pages/_document.tsx
:
import Document, { Html, Head, Main, NextScript } from "next/document";
import { GA_TRACKING_ID } from "../lib/gtag";
const isProduction = process.env.NODE_ENV === "production";
export default class MyDocument extends Document {
render(): JSX.Element {
return (
<Html>
<Head>
{/* enable analytics script only for production */}
{isProduction && (
<>
<script
async
src={`https://www.googletagmanager.com/gtag/js?id=${GA_TRACKING_ID}`}
/>
<script
// eslint-disable-next-line react/no-danger
dangerouslySetInnerHTML={{
__html: `
window.dataLayer = window.dataLayer || [];
function gtag(){dataLayer.push(arguments);}
gtag('js', new Date());
gtag('config', '${GA_TRACKING_ID}', {
page_path: window.location.pathname,
});
`,
}}
/>
</>
)}
</Head>
<body>
<Main />
<NextScript />
</body>
</Html>
);
}
}
- 创建
/pages/_app.tsx
:
import { AppProps } from "next/app";
import { useRouter } from "next/router";
import { useEffect } from "react";
import * as gtag from "../lib/gtag";
const isProduction = process.env.NODE_ENV === "production";
const App = ({ Component, pageProps }: AppProps): JSX.Element => {
const router = useRouter();
useEffect(() => {
const handleRouteChange = (url: URL) => {
/* invoke analytics function only for production */
if (isProduction) gtag.pageview(url);
};
router.events.on("routeChangeComplete", handleRouteChange);
return () => {
router.events.off("routeChangeComplete", handleRouteChange);
};
}, [router.events]);
// eslint-disable-next-line react/jsx-props-no-spreading
return <Component {...pageProps} />;
};
export default App;
More info: https://gourav.io/blog/nextjs-cheatsheet
所选答案仅在浏览器每次完全刷新时触发一次。它不会为使用 Link from "next/link"
的后续内部路由更改而触发。例如:
- 用户在他的浏览器中输入
www.yourdomain.com/page_1
并按下回车键(或者他可能在 Google 上点击了您的网站结果)。
- 该代码将触发并发送
/page_1
的页面视图
- 用户现在单击
"next/link"
中的内部 <Link>
以导航到另一个页面,/page_2
- 该代码 不会 在
/page_2
之前触发。它只会在完全刷新时重新触发,例如当您按 F5 刷新浏览器时。
在某些情况下这可能没问题。但我认为大多数人都希望它在每次页面更改时触发一次。
这是我在每次 pathname
更改时触发的内容。
_app.tsx
const App: React.FC<CustomAppProps> = ({ Component, pageProps }) => {
useLogPageView();
return (
<>
<Layout> // Layout includes Header Main and Footer for my pages
<Component {...pageProps}/> // Component is rendered inside Main
</Layout>
</>
);
};
export default App;
useLogPageView.ts
import { useEffect } from "react";
import { useRouter } from "next/router";
export const useLogPageView = () : void => {
const router = useRouter();
const { pathname, asPath } = router;
// IF YOU ARE USING DYNAMIC ROUTES LIKE /posts/[slug]
// THEN YOU SHOULD USE asPath INSTEAD OF pathname
// THIS EFFECT WILL RUN ON EVERY asPath CHANGE
useEffect(() => {
gtag('config', '${GA_TRACKING_ID}', { // DON'T ADD THIS TO _document.tsx
page_path: window.location.pathname, // OTHERWISE YOU'LL GET DUPLICATE HITS
}); // ON FIRST PAGE LOAD
},[asPath]);
};
结帐https://nextjs.org/docs/api-reference/next/router#router-object
这是一个小差异问题,但我在此页面上找到了快速简便的解决方案:https://www.learnbestcoding.com/post/9/easiest-way-to-integrate-google-analytics-with-react-js-and-next-js。您可以使用 App 组件而不是自定义文档。您需要做的就是安装 react-gtm-module,然后将 useEffect 添加到您的 App 组件中。最终页面可能如下所示:
import '../styles/globals.css';
import Layout from "../components/Layout";
import Head from "next/head";
import {useEffect} from "react";
import TagManager from "react-gtm-module";
function MyApp({ Component, pageProps }) {
useEffect(() => {
TagManager.initialize({ gtmId: 'GTM-XXXXX' });
}, []);
return(
<Layout>
<Head>
...
</Head>
<Component {...pageProps} />
</Layout>
)
}
export default MyApp
在 GTM-XXXXX 中将是您从 Google 跟踪代码管理器生成的 ID。使用完 GTM 后,只需将它与带有标签的 Google 分析连接起来即可。
您首先需要通过 google 获取您的 google 分析 ID
然后在 pages 文件夹中创建 _document.js 如果尚未创建并复制此代码
_document.js
import Document, { Html, Head, Main, NextScript } from "next/document";
import { G_TAG } from "../lib/constants";
export default class MyDocument extends Document {
render() {
const url = "https://www.googletagmanager.com/gtag/js?id=" + `${G_TAG}`;
return (
<Html lang="en">
<Head>
<script async src={`${url}`}></script>
<script
dangerouslySetInnerHTML={{
__html: `
window.dataLayer = window.dataLayer || [];
function gtag(){dataLayer.push(arguments);}
gtag('js', new Date());
gtag('config', '${G_TAG}', {
page_path: window.location.pathname,
});
`,
}}
/>
</Head>
<body>
<Main />
<NextScript />
</body>
</Html>
);
}
}
然后您需要根据这样的环境定义您的 G_TAG:
constants.js
export const G_TAG = {
development: "dev-mode",
production: "YOUR-MEASUREMENT-ID-FROM-GANALYTICS",
}[process.env.NODE_ENV];
you can check step by step how to create your google analytics ID and set it up with Next.js in: https://learnjsx.com/category/4/posts/nextjs-ganalytics
参考此文档:https://nextjs.org/docs/api-reference/next/script
.
在你的 pages/_app.js
:
import Script from 'next/script'
...
function MyApp({Component, pageProps}) {
return (
<div>
...
<Script
id="google-analytics"
src="https://www.googletagmanager.com/gtag/js?id=YOUR-ID"
onLoad={() => {
window.dataLayer = window.dataLayer || [];
function gtag(){dataLayer.push(arguments);}
gtag('js', new Date());
gtag('config', 'YOUR-ID');
}}
/>
</div>
)
}
这是next.js推荐的方法。
/components/GoogleAnalytics.jsx
import Script from 'next/script'
import { useEffect } from 'react'
import { useRouter } from 'next/router'
const GA_TRACKING_ID = '...'
export default () => {
const router = useRouter()
useEffect(() => {
const handleRouteChange = url => {
window.gtag('config', GA_TRACKING_ID, { page_path: url })
}
router.events.on('routeChangeComplete', handleRouteChange)
return () => {
router.events.off('routeChangeComplete', handleRouteChange)
}
}, [router.events])
return (
<>
<Script
strategy='afterInteractive'
src={`https://www.googletagmanager.com/gtag/js?id=${GA_TRACKING_ID}`}
/>
<Script
id='gtag-init'
strategy='afterInteractive'
dangerouslySetInnerHTML={{
__html: `
window.dataLayer = window.dataLayer || [];
function gtag(){dataLayer.push(arguments);}
gtag('js', new Date());
gtag('config', '${GA_TRACKING_ID}', {
page_path: window.location.pathname,
});
`
}}
/>
</>
)
}
/pages/_app.jsx
import GoogleAnalytics from './../components/GoogleAnalytics'
export default function App ({ Component, pageProps }) {
return (
<>
<Component {...pageProps} />
{
process.env.NODE_ENV === 'production' &&
<GoogleAnalytics />
}
</>
)
}
请勿在此处使用最佳答案:禁止使用原生 <script>
标签 和 它应该在 <head>
标签之外定义 .
这是包含脚本标记并在 NextJS 中配置 Google Analytics 的正确方法:
import Script from 'next/script'
import Head from 'next/head'
export default function Index() {
return (
<>
<Head>
<title>Next.js</title>
</Head>
<Script
src="https://www.googletagmanager.com/gtag/js?id=GA_MEASUREMENT_ID"
strategy="afterInteractive"
/>
<Script id="google-analytics" strategy="afterInteractive">
{`
window.dataLayer = window.dataLayer || [];
function gtag(){window.dataLayer.push(arguments);}
gtag('js', new Date());
gtag('config', 'GA_MEASUREMENT_ID');
`}
</Script>
</>
)
}
来自 GitHub 问题的 Answer 帮助了我
使用 React 钩子:
_app.js
import { useEffect } from 'react'
import { useRouter } from 'next/router'
import ReactGA from 'react-ga'
import Layout from '../components/Layout'
function MyApp ({ Component, pageProps }) {
const router = useRouter()
useEffect(() => {
const handleRouteChange = (url, { shallow }) => {
ReactGA.set({ page: url })
ReactGA.pageview(url)
}
ReactGA.initialize('XX-XXXXXXXXX-X', { debug: false })
ReactGA.set({ page: router.pathname })
ReactGA.pageview(router.pathname)
router.events.on('routeChangeComplete', handleRouteChange)
return () => {
router.events.off('routeChangeComplete', handleRouteChange)
}
}, [])
return (
<Layout>
<Component {...pageProps} />
</Layout>
)
}
export default MyApp
感谢@RiusmaX。干杯!!
我将样式化组件与 next.js 一起使用,因此我的样式需要在服务器端呈现,因此如何向我的网站添加 google 分析?
我检查了 next.js google analytics example 但正如我所说,我的 _document 文件因使用样式化组件而不同。
// _document.js
import React from 'react'
import Document from 'next/document'
import { ServerStyleSheet } from 'styled-components'
class MyDocument extends Document {
static async getInitialProps(ctx) {
const sheet = new ServerStyleSheet()
const originalRenderPage = ctx.renderPage
try {
ctx.renderPage = () => originalRenderPage({
enhanceApp: (App) => (props) => sheet.collectStyles(<App {...props} />),
})
const initialProps = await Document.getInitialProps(ctx)
return {
...initialProps,
styles: (
<>
{initialProps.styles}
{sheet.getStyleElement()}
</>
),
}
} finally {
sheet.seal()
}
}
}
export default MyDocument
在您的 _document.js
中,您覆盖了 getInitialProps
方法。您还可以覆盖 render
方法。只需添加
render() {
return (
<Html lang={this.props.lang || "en"}>
<Head>
<script
dangerouslySetInnerHTML={{
__html: `[google analytics tracking code here]`
}}
/>
</Head>
<body>
<Main />
<NextScript />
</body>
</Html>
);
}
确保导入所需的组件:
import Document, { Html, Head, Main, NextScript } from "next/document"
要正确初始化 gtag
,请在 _document.js
或您定义 Head
的任何地方执行以下操作:
import { Head } from 'next/document';
export default class MyDocument extends Document {
render() {
return (
// ...
<Head>
<script
async
src="https://www.googletagmanager.com/gtag/js?id=[Tracking ID]"
/>
<script
dangerouslySetInnerHTML={{
__html: `
window.dataLayer = window.dataLayer || [];
function gtag(){dataLayer.push(arguments);}
gtag('js', new Date());
gtag('config', '[Tracking ID]', { page_path: window.location.pathname });
`,
}}
/>
</Head>
);
}
}
以上将跟踪页面加载时的页面浏览量。要跟踪导航,请将以下内容添加到 _app.js
:
import { useRouter } from 'next/router';
import { useEffect } from "react";
export default const App = () => {
const router = useRouter();
const handleRouteChange = (url) => {
window.gtag('config', '[Tracking ID]', {
page_path: url,
});
};
useEffect(() => {
router.events.on('routeChangeComplete', handleRouteChange);
return () => {
router.events.off('routeChangeComplete', handleRouteChange);
};
}, [router.events]);
return (
// ...
);
};
另请参阅:
另一种在没有 dangerouslySetInnerHTML
的情况下对我很有效的方法:
- 在 public 文件夹中创建一个新的 js 文件,其中包含
dangerouslySetInnerHTML
中的内容。 - 将创建的 js 文件添加到
_document.js
文件。
我的 _document.js
返回的示例:
<Html>
<Head>
<script async src="https://www.googletagmanager.com/gtag/js?id=UA-xxx-x"></script>
<script src="/ga.js" async></script>
{/*other scripts*/}
</Head>
<body>
<Main />
<NextScript />
</body>
</Html>
使用 Typescript
通过 NextJS 设置 Google 分析我正在为我的个人网站 (https://github.com/GorvGoyl/Personal-Site-Gourav.io) 使用以下设置,它工作正常,没有任何 linting 错误。仅为生产启用分析。
- 创建 Google analytics project 并获取测量 ID。
- 在您的 NextJS 项目中,创建
/lib/gtag.ts
文件并添加您的 Google 测量 ID:
export const GA_TRACKING_ID = "<INSERT_TAG_ID>";
// https://developers.google.com/analytics/devguides/collection/gtagjs/pages
export const pageview = (url: URL): void => {
window.gtag("config", GA_TRACKING_ID, {
page_path: url,
});
};
type GTagEvent = {
action: string;
category: string;
label: string;
value: number;
};
// https://developers.google.com/analytics/devguides/collection/gtagjs/events
export const event = ({ action, category, label, value }: GTagEvent): void => {
window.gtag("event", action, {
event_category: category,
event_label: label,
value,
});
};
- 同时安装 gtag
types
:
npm i -D @types/gtag.js
- 创建
/pages/_document.tsx
:
import Document, { Html, Head, Main, NextScript } from "next/document";
import { GA_TRACKING_ID } from "../lib/gtag";
const isProduction = process.env.NODE_ENV === "production";
export default class MyDocument extends Document {
render(): JSX.Element {
return (
<Html>
<Head>
{/* enable analytics script only for production */}
{isProduction && (
<>
<script
async
src={`https://www.googletagmanager.com/gtag/js?id=${GA_TRACKING_ID}`}
/>
<script
// eslint-disable-next-line react/no-danger
dangerouslySetInnerHTML={{
__html: `
window.dataLayer = window.dataLayer || [];
function gtag(){dataLayer.push(arguments);}
gtag('js', new Date());
gtag('config', '${GA_TRACKING_ID}', {
page_path: window.location.pathname,
});
`,
}}
/>
</>
)}
</Head>
<body>
<Main />
<NextScript />
</body>
</Html>
);
}
}
- 创建
/pages/_app.tsx
:
import { AppProps } from "next/app";
import { useRouter } from "next/router";
import { useEffect } from "react";
import * as gtag from "../lib/gtag";
const isProduction = process.env.NODE_ENV === "production";
const App = ({ Component, pageProps }: AppProps): JSX.Element => {
const router = useRouter();
useEffect(() => {
const handleRouteChange = (url: URL) => {
/* invoke analytics function only for production */
if (isProduction) gtag.pageview(url);
};
router.events.on("routeChangeComplete", handleRouteChange);
return () => {
router.events.off("routeChangeComplete", handleRouteChange);
};
}, [router.events]);
// eslint-disable-next-line react/jsx-props-no-spreading
return <Component {...pageProps} />;
};
export default App;
More info: https://gourav.io/blog/nextjs-cheatsheet
所选答案仅在浏览器每次完全刷新时触发一次。它不会为使用 Link from "next/link"
的后续内部路由更改而触发。例如:
- 用户在他的浏览器中输入
www.yourdomain.com/page_1
并按下回车键(或者他可能在 Google 上点击了您的网站结果)。 - 该代码将触发并发送
/page_1
的页面视图
- 用户现在单击
"next/link"
中的内部<Link>
以导航到另一个页面,/page_2
- 该代码 不会 在
/page_2
之前触发。它只会在完全刷新时重新触发,例如当您按 F5 刷新浏览器时。
在某些情况下这可能没问题。但我认为大多数人都希望它在每次页面更改时触发一次。
这是我在每次 pathname
更改时触发的内容。
_app.tsx
const App: React.FC<CustomAppProps> = ({ Component, pageProps }) => {
useLogPageView();
return (
<>
<Layout> // Layout includes Header Main and Footer for my pages
<Component {...pageProps}/> // Component is rendered inside Main
</Layout>
</>
);
};
export default App;
useLogPageView.ts
import { useEffect } from "react";
import { useRouter } from "next/router";
export const useLogPageView = () : void => {
const router = useRouter();
const { pathname, asPath } = router;
// IF YOU ARE USING DYNAMIC ROUTES LIKE /posts/[slug]
// THEN YOU SHOULD USE asPath INSTEAD OF pathname
// THIS EFFECT WILL RUN ON EVERY asPath CHANGE
useEffect(() => {
gtag('config', '${GA_TRACKING_ID}', { // DON'T ADD THIS TO _document.tsx
page_path: window.location.pathname, // OTHERWISE YOU'LL GET DUPLICATE HITS
}); // ON FIRST PAGE LOAD
},[asPath]);
};
结帐https://nextjs.org/docs/api-reference/next/router#router-object
这是一个小差异问题,但我在此页面上找到了快速简便的解决方案:https://www.learnbestcoding.com/post/9/easiest-way-to-integrate-google-analytics-with-react-js-and-next-js。您可以使用 App 组件而不是自定义文档。您需要做的就是安装 react-gtm-module,然后将 useEffect 添加到您的 App 组件中。最终页面可能如下所示:
import '../styles/globals.css';
import Layout from "../components/Layout";
import Head from "next/head";
import {useEffect} from "react";
import TagManager from "react-gtm-module";
function MyApp({ Component, pageProps }) {
useEffect(() => {
TagManager.initialize({ gtmId: 'GTM-XXXXX' });
}, []);
return(
<Layout>
<Head>
...
</Head>
<Component {...pageProps} />
</Layout>
)
}
export default MyApp
在 GTM-XXXXX 中将是您从 Google 跟踪代码管理器生成的 ID。使用完 GTM 后,只需将它与带有标签的 Google 分析连接起来即可。
您首先需要通过 google 获取您的 google 分析 ID 然后在 pages 文件夹中创建 _document.js 如果尚未创建并复制此代码
_document.js
import Document, { Html, Head, Main, NextScript } from "next/document";
import { G_TAG } from "../lib/constants";
export default class MyDocument extends Document {
render() {
const url = "https://www.googletagmanager.com/gtag/js?id=" + `${G_TAG}`;
return (
<Html lang="en">
<Head>
<script async src={`${url}`}></script>
<script
dangerouslySetInnerHTML={{
__html: `
window.dataLayer = window.dataLayer || [];
function gtag(){dataLayer.push(arguments);}
gtag('js', new Date());
gtag('config', '${G_TAG}', {
page_path: window.location.pathname,
});
`,
}}
/>
</Head>
<body>
<Main />
<NextScript />
</body>
</Html>
);
}
}
然后您需要根据这样的环境定义您的 G_TAG:
constants.js
you can check step by step how to create your google analytics ID and set it up with Next.js in: https://learnjsx.com/category/4/posts/nextjs-ganalyticsexport const G_TAG = { development: "dev-mode", production: "YOUR-MEASUREMENT-ID-FROM-GANALYTICS", }[process.env.NODE_ENV];
参考此文档:https://nextjs.org/docs/api-reference/next/script
.
在你的 pages/_app.js
:
import Script from 'next/script'
...
function MyApp({Component, pageProps}) {
return (
<div>
...
<Script
id="google-analytics"
src="https://www.googletagmanager.com/gtag/js?id=YOUR-ID"
onLoad={() => {
window.dataLayer = window.dataLayer || [];
function gtag(){dataLayer.push(arguments);}
gtag('js', new Date());
gtag('config', 'YOUR-ID');
}}
/>
</div>
)
}
这是next.js推荐的方法。
/components/GoogleAnalytics.jsx
import Script from 'next/script'
import { useEffect } from 'react'
import { useRouter } from 'next/router'
const GA_TRACKING_ID = '...'
export default () => {
const router = useRouter()
useEffect(() => {
const handleRouteChange = url => {
window.gtag('config', GA_TRACKING_ID, { page_path: url })
}
router.events.on('routeChangeComplete', handleRouteChange)
return () => {
router.events.off('routeChangeComplete', handleRouteChange)
}
}, [router.events])
return (
<>
<Script
strategy='afterInteractive'
src={`https://www.googletagmanager.com/gtag/js?id=${GA_TRACKING_ID}`}
/>
<Script
id='gtag-init'
strategy='afterInteractive'
dangerouslySetInnerHTML={{
__html: `
window.dataLayer = window.dataLayer || [];
function gtag(){dataLayer.push(arguments);}
gtag('js', new Date());
gtag('config', '${GA_TRACKING_ID}', {
page_path: window.location.pathname,
});
`
}}
/>
</>
)
}
/pages/_app.jsx
import GoogleAnalytics from './../components/GoogleAnalytics'
export default function App ({ Component, pageProps }) {
return (
<>
<Component {...pageProps} />
{
process.env.NODE_ENV === 'production' &&
<GoogleAnalytics />
}
</>
)
}
请勿在此处使用最佳答案:禁止使用原生 <script>
标签 和 它应该在 <head>
标签之外定义 .
这是包含脚本标记并在 NextJS 中配置 Google Analytics 的正确方法:
import Script from 'next/script'
import Head from 'next/head'
export default function Index() {
return (
<>
<Head>
<title>Next.js</title>
</Head>
<Script
src="https://www.googletagmanager.com/gtag/js?id=GA_MEASUREMENT_ID"
strategy="afterInteractive"
/>
<Script id="google-analytics" strategy="afterInteractive">
{`
window.dataLayer = window.dataLayer || [];
function gtag(){window.dataLayer.push(arguments);}
gtag('js', new Date());
gtag('config', 'GA_MEASUREMENT_ID');
`}
</Script>
</>
)
}
来自 GitHub 问题的 Answer 帮助了我
使用 React 钩子:
_app.js
import { useEffect } from 'react'
import { useRouter } from 'next/router'
import ReactGA from 'react-ga'
import Layout from '../components/Layout'
function MyApp ({ Component, pageProps }) {
const router = useRouter()
useEffect(() => {
const handleRouteChange = (url, { shallow }) => {
ReactGA.set({ page: url })
ReactGA.pageview(url)
}
ReactGA.initialize('XX-XXXXXXXXX-X', { debug: false })
ReactGA.set({ page: router.pathname })
ReactGA.pageview(router.pathname)
router.events.on('routeChangeComplete', handleRouteChange)
return () => {
router.events.off('routeChangeComplete', handleRouteChange)
}
}, [])
return (
<Layout>
<Component {...pageProps} />
</Layout>
)
}
export default MyApp
感谢@RiusmaX。干杯!!