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

How to use google analytics with next js app

3个答案

1
2
3

Integrating Google Analytics into a Next.js project involves several key steps. Here is a systematic approach to implementation:

  1. Obtain your Google Analytics tracking ID: To use Google Analytics, you first need to create a Google Analytics account and set up a property for your website. After completing these steps, Google Analytics will provide a tracking ID, typically in the format UA-000000-2.

  2. Install the Google Analytics library: Install the Google Analytics library (e.g., react-ga) using npm or yarn:

    sh
    npm install react-ga

    or

    sh
    yarn add react-ga
  3. Initialize Google Analytics: Create a utility file (e.g., analytics.js) for configuring and initializing Google Analytics. The code may look like this:

    javascript
    // analytics.js import ReactGA from 'react-ga'; export const initGA = () => { console.log('GA init'); ReactGA.initialize('your Google Analytics tracking 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 }); } };

    In this file, we define functions for initializing Google Analytics, logging page views, and recording events and exceptions.

  4. Integrate Google Analytics into your Next.js application: Initialize Google Analytics and log page views in the _app.js file as follows:

    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;

    Note: In production environments, add conditions to avoid loading and executing Google Analytics scripts during development.

  5. Listen for route changes: In Next.js, route changes do not trigger page reloads, so you must listen for route change events to log new page visits. Modify the _app.js file to subscribe to route change events and log page views on each change:

    javascript
    // pages/_app.js import Router from 'next/router'; // ... other imports Router.events.on('routeChangeComplete', logPageView);

    This ensures that the logPageView function is called whenever the route changes, sending new page view data to Google Analytics.

  6. Deploy and test: Deploy your Next.js application to the production environment and verify that data is correctly recorded in the Google Analytics Dashboard.

This is a basic integration approach covering setup, page view logging, and event tracking in a Next.js application. Depending on your requirements, you can extend functionality to capture more detailed user interaction data.

2024年6月29日 12:07 回复

In your _document.js file, you have rewritten the getInitialProps method. You can also rewrite the render method. Simply add the following code:

javascript
render() { return ( <Html lang={this.props.lang || "en"}> <Head> <script dangerouslySetInnerHTML={{ __html: `[google analytics tracking code here]` }} /> </Head> <body> <Main /> <NextScript /> </body> </Html> ); }

Ensure you import the required components: import Document, { Html, Head, Main, NextScript } from 'next/document';

2024年6月29日 12:07 回复

Using TypeScript to Set Up Google Analytics with NextJS

I have configured the following setup for my personal website (https://github.com/GorvGoyl/Personal-Site-Gourav.io), which operates smoothly without any linting errors. Analytics is enabled exclusively in production.

  • Create a Google Analytics project and obtain the Measurement ID.

  • In your NextJS project, create the /lib/gtag.ts file and add your 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, }); };

  • Also, install the gtag types:

    npm i -D @types/gtag.js

  • Create /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, }); , }} /> </> )}

    ); } };

  • Create /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;

For more information: https://gourav.io/blog/nextjs-cheatsheet

2024年6月29日 12:07 回复

你的答案