How to add Google Analytics to Next.js?

by rusty.rosenbaum , in category: SEO Tools , 2 months ago

1 answer

Member

by virginie , a month ago

@rusty.rosenbaum 

To add Google Analytics to a Next.js application, you can follow these steps:

  1. Sign up for a Google Analytics account and create a new property for your Next.js application. This will give you a tracking ID that you will use to set up the tracking code in your application.
  2. Install the react-ga library using npm:
1
npm install react-ga


  1. Create a file in your Next.js application to initialize and configure react-ga. For example, you might create a file called ga.js in the root of your project with the following code:
1
2
3
4
5
6
7
import ReactGA from 'react-ga';

ReactGA.initialize('YOUR_TRACKING_ID');

export default (page) => {
  ReactGA.pageview(page);
};


  1. In the pages/_app.js file, import the ga.js file and call the function that it exports on each page change. This will send a pageview event to Google Analytics every time the user navigates to a new page in your application:
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
import App from 'next/app';
import React from 'react';
import * as gtag from '../ga';

class MyApp extends App {
  componentDidMount() {
    gtag.pageview(window.location.pathname);
  }

  componentDidUpdate() {
    gtag.pageview(window.location.pathname);
  }

  render() {
    const { Component, pageProps } = this.props;
    return <Component {...pageProps} />;
  }
}

export default MyApp;


That's it! You should now be able to see pageviews and other analytics data for your Next.js application in your Google Analytics account.