如何在 next.js 应用程序中使用谷歌分析?

新手上路,请多包涵

我在 next.js 中使用样式化组件,所以我的样式需要在服务器端呈现,因此如何将谷歌分析添加到我的网站?

我检查了 next.js 谷歌分析示例,但正如我所说,我的 _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

原文由 0xsh 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 1.3k
2 个回答

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

pages/_app.jsx

 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 中工作,我也在其中设置来自 env var 的标签。

这也会自动记录导航的综合浏览量。如果这不适合您,可以使用手动发送页面浏览事件的 官方示例 或使用 React Router 执行此操作的 线程

要发送自定义事件,您可以使用 window.gtag 。它甚至支持 TypeScript: @types/gtag.js

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

原文由 thisismydesign 发布,翻译遵循 CC BY-SA 4.0 许可协议

使用 Typescript 使用 NextJS 设置 Google Analytics

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

  • 创建一个 Google 分析项目 并获取测量 ID。
  • 在您的 NextJS 项目中,创建 /lib/gtag.ts 文件并添加您的 Google Measurement 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;

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

原文由 GorvGoyl 发布,翻译遵循 CC BY-SA 4.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题