How to add Google Analytics to Next.js?
@rusty.rosenbaum
To add Google Analytics to a Next.js application, you can follow these steps:
1
|
npm install react-ga |
1 2 3 4 5 6 7 |
import ReactGA from 'react-ga'; ReactGA.initialize('YOUR_TRACKING_ID'); export default (page) => { ReactGA.pageview(page); }; |
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.
@rusty.rosenbaum
Note: As of October 2021, ReactGA is no longer maintained and is considered outdated. Instead, you can use the @next/plugin-google-analytics
package provided by Next.js for easier integration.
To add Google Analytics to a Next.js application using the @next/plugin-google-analytics
, you can follow these steps:
1
|
npm install @next/plugin-google-analytics |
1 2 3 4 5 6 7 |
const withGoogleAnalytics = require('@next/plugin-google-analytics'); module.exports = withGoogleAnalytics({ analytics: { id: 'YOUR_TRACKING_ID', // Replace with your own tracking ID }, }); |
You can now go to your Google Analytics account to view analytics data for your Next.js application.