乐闻世界logo
搜索文章和话题

NextJS 项目如何中使用谷歌分析?

7 个月前提问
3 个月前修改
浏览次数164

6个答案

1
2
3
4
5
6

在 Next.js 项目中集成 Google Analytics 主要有几个步骤,以下是一个系统性的方法来实现:

  1. 获取 Google Analytics 跟踪 ID: 要使用 Google Analytics,首先需要创建一个 Google Analytics 账户,并为你的网站创建一个属性。完成这些步骤后,Google Analytics 会提供一个跟踪 ID(通常是像 UA-000000-2 的格式)。

  2. 安装 Google Analytics 库: 通过 npm 或 yarn 安装 Google Analytics 库(例如,react-ga):

    sh
    npm install react-ga

    或者

    sh
    yarn add react-ga
  3. 初始化 Google Analytics: 创建一个 utility 文件(例如 analytics.js),用于配置和初始化 Google Analytics,代码可能如下所示:

    javascript
    // analytics.js import ReactGA from 'react-ga'; export const initGA = () => { console.log('GA init'); ReactGA.initialize('你的谷歌分析跟踪ID'); }; export const logPageView = () => { console.log(`Logging pageview for ${window.location.pathname}`); ReactGA.set({ page: window.location.pathname }); ReactGA.pageview(window.location.pathname); }; export const logEvent = (category = '', action = '') => { if (category && action) { ReactGA.event({ category, action }); } }; export const logException = (description = '', fatal = false) => { if (description) { ReactGA.exception({ description, fatal }); } };

    在这个文件中,我们定义了初始化函数、页面浏览日志函数以及其他用于记录事件和异常的函数。

  4. 在 Next.js 应用中应用 Google Analytics: 你可以在 _app.js 文件中初始化 Google Analytics,并记录页面视图,如下所示:

    javascript
    // pages/_app.js import App from 'next/app'; import { initGA, logPageView } from '../utils/analytics'; class MyApp extends App { componentDidMount() { if (!window.GA_INITIALIZED) { initGA(); window.GA_INITIALIZED = true; } logPageView(); } render() { const { Component, pageProps } = this.props; return <Component {...pageProps} />; } } export default MyApp;

    请注意,在生产环境中,你应该添加条件来避免在开发环境中加载和执行 Google Analytics 脚本。

  5. 监听路由改变: 在 Next.js 中,路由改变不会导致页面重新加载,因此你需要监听路由改变事件来记录新的页面访问。为此,可以修改 _app.js 文件来订阅路由更改事件,并在每次路由更改时记录页面视图:

    javascript
    // pages/_app.js import Router from 'next/router'; // ...其他导入 Router.events.on('routeChangeComplete', logPageView);

    这样,每当路由改变后,logPageView 函数就会被调用,从而向 Google Analytics 发送新的页面视图数据。

  6. 部署并测试: 部署你的 Next.js 应用到生产环境,并在 Google Analytics Dashboard 中检查数据是否正确记录。

这是一个基本的集成方式,它涵盖了从设置 Google Analytics 到在 Next.js 应用程序中记录页面视图和事件的过程。根据需求,还可以扩展功能来捕获更详细的用户交互数据。

2024年6月29日 12:07 回复

Next.js 自 v11 起建议使用他们的<Script>标签,添加它的正确位置是App组件

pages/_app.jsx

shell
import React from 'react'; import Script from 'next/script'; const App = ({ Component, pageProps }) => { return ( <> <Script src="https://www.googletagmanager.com/gtag/js?id=G-xxxxxxxxxx" strategy="afterInteractive" /> <Script id="google-analytics" strategy="afterInteractive"> {` window.dataLayer = window.dataLayer || []; function gtag(){window.dataLayer.push(arguments);} gtag('js', new Date()); gtag('config', 'G-xxxxxxxxxx'); `} </Script> <Component {...pageProps} /> </> ); }; export default App;

您可以看到此解决方案在Nestjs-starter中运行,我还从环境变量设置标签。

对于 v10 及更低版本,请<script>根据Google 指南使用常规标签。

请记住,Google Analytics 会自动进行页面跟踪,但这并不适用于所有用例。例如,不跟踪hash参数search更改。这可能会导致很多混乱。例如,当使用或锚链接时,导航将不会被跟踪。要完全控制页面视图跟踪,您可以禁用自动跟踪。详细解释请参见:The Ultimate Guide to Google Analytics (UA & GA4) on React (Or Anything Else)HashRouter

手动页面跟踪:https://stackoverflow.com/a/63249329/2771889

2024年6月29日 12:07 回复

使用 Typescript 通过 NextJS 设置 Google Analytics

我正在为我的个人网站(https://github.com/GorvGoyl/Personal-Site-Gourav.io)使用以下设置,它工作正常,没有任何 linting 错误。仅针对生产启用分析。

  • 创建一个Google 分析项目并获取Measurement 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 ( {/* 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, }); , }} /> </> )}

    ); } }

  • 创造/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;

更多信息: https: //gourav.io/blog/nextjs-cheatsheet

2024年6月29日 12:07 回复

在你的方法中_document.js你重写了该getInitialProps方法。您还可以重写该render方法。只需添加

shell
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"

2024年6月29日 12:07 回复

不要在这里使用最上面的答案:_禁止__使用本机<script>_标签,_它应该在<head>标签_之外定义。

这是在 NextJS 中包含脚本标签并配置 Google Analytics 的正确方法:

shell
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> </> ) }

欲了解更多信息:https://nextjs.org/docs/messages/next-script-for-ga

2024年6月29日 12:07 回复

这是next.js推荐的方法。

/components/GoogleAnalytics.jsx

shell
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

shell
import GoogleAnalytics from './../components/GoogleAnalytics' export default function App ({ Component, pageProps }) { return ( <> <Component {...pageProps} /> { process.env.NODE_ENV === 'production' && <GoogleAnalytics /> } </> ) }
2024年6月29日 12:07 回复

你的答案