All Projects → MauricioRobayo → nextjs-google-analytics

MauricioRobayo / nextjs-google-analytics

Licence: MIT license
Google Analytics for Next.js

Programming Languages

typescript
32286 projects
javascript
184084 projects - #8 most used programming language

Projects that are alternatives of or similar to nextjs-google-analytics

blazor-analytics
Blazor extensions for Analytics: Google Analytics, GTAG, ...
Stars: ✭ 101 (-58.26%)
Mutual labels:  google-analytics, gtag
shopify-gtm-ga
Enhances Google Analytics and integrates Google Tag Manager for Shopify.
Stars: ✭ 44 (-81.82%)
Mutual labels:  google-analytics, google-tag-manager
unified-analytics
ready-to-deploy custom web analytics collection & reporting for government
Stars: ✭ 20 (-91.74%)
Mutual labels:  google-analytics, google-tag-manager
tag-manager
Website analytics, JavaScript error tracking + analytics, tag manager, data ingest endpoint creation (tracking pixels). GDPR + CCPA compliant.
Stars: ✭ 279 (+15.29%)
Mutual labels:  google-analytics, google-tag-manager
stat-counters
The library, which provides statistics counters, e.g. Google analytics, Yandex metrica, etc
Stars: ✭ 16 (-93.39%)
Mutual labels:  google-analytics, google-tag-manager
Komito
🔖 Komito Analytics is a free, open-source enhancement for the most popular web analytics software.
Stars: ✭ 148 (-38.84%)
Mutual labels:  google-analytics
Magento2 Google Tag Manager
Google Tag Manager is a user-friendly, yet powerful and cost-effective solution that is a must-have integration for every Magento store. It simplifies the process of adding and managing third-party JavaScript tags. With dozens of custom events and hundreds of data points our extensions the #1 GTM solution for Magento.
Stars: ✭ 208 (-14.05%)
Mutual labels:  google-analytics
Vue Ga
Google Analytics for Vue.js
Stars: ✭ 141 (-41.74%)
Mutual labels:  google-analytics
Cloudflare Workers Async Google Analytics
☁️ The Cloudflare Workers implementation of an async Google Analytics
Stars: ✭ 135 (-44.21%)
Mutual labels:  google-analytics
yii2-stat
Yii2 Multi Web Statistic Module (yametrika, google-analytic, own db-counter)
Stars: ✭ 18 (-92.56%)
Mutual labels:  google-analytics
Next Ga
Next.js HOC to integrate Google Analytics on every page change
Stars: ✭ 228 (-5.79%)
Mutual labels:  google-analytics
React Tracker
React specific tracking library, Track user interaction with minimal API!
Stars: ✭ 191 (-21.07%)
Mutual labels:  google-analytics
Save Analytics From Content Blockers
A proxy back end for Google Tag Manager & Google Analytics
Stars: ✭ 159 (-34.3%)
Mutual labels:  google-analytics
Analytics
UNMAINTAINED! - Complete Google Analytics, Mixpanel, KISSmetrics (and more) integration for Meteor
Stars: ✭ 211 (-12.81%)
Mutual labels:  google-analytics
Vue Analytics
Google Analytics plugin for Vue
Stars: ✭ 1,780 (+635.54%)
Mutual labels:  google-analytics
Example Airflow Dags
Example DAGs using hooks and operators from Airflow Plugins
Stars: ✭ 243 (+0.41%)
Mutual labels:  google-analytics
Laravel Analytics Event Tracking
Laravel package to easily send events to Google Analytics
Stars: ✭ 137 (-43.39%)
Mutual labels:  google-analytics
Goaccess
GoAccess is a real-time web log analyzer and interactive viewer that runs in a terminal in *nix systems or through your browser.
Stars: ✭ 14,096 (+5724.79%)
Mutual labels:  google-analytics
Ackee
Self-hosted, Node.js based analytics tool for those who care about privacy.
Stars: ✭ 3,140 (+1197.52%)
Mutual labels:  google-analytics
Wagalytics
A Google Analytics dashboard in your Wagtail admin
Stars: ✭ 176 (-27.27%)
Mutual labels:  google-analytics

Nextjs Google Analytics

npm version codecov CodeFactor

Google Analytics for Next.js

This package optimizes script loading using Next.js Script tag, which means that it will only work on apps using Next.js >= 11.0.0.

Installation

npm install --save nextjs-google-analytics

TL;DR

Add the GoogleAnalytics component with the trackPageViews prop set to true to your custom App file:

// pages/_app.js
import { GoogleAnalytics } from "nextjs-google-analytics";

const App = ({ Component, pageProps }) => {
  return (
    <>
      <GoogleAnalytics trackPageViews />
      <Component {...pageProps} />
    </>
  );
};

export default App;

You can pass your Google Analytics measurement id by setting it on the NEXT_PUBLIC_GA_MEASUREMENT_ID environment variable or using the gaMeasurementId prop on the GoogleAnalytics component. The environment variable will override the prop if both are set.

Usage

Your Google Analytics measurement id is read from NEXT_PUBLIC_GA_MEASUREMENT_ID environment variable, so make sure it is set in your production environment:

If the variable is not set or is empty, nothing will be loaded, making it safe to work in development.

To load it and test it on development, add:

NEXT_PUBLIC_GA_MEASUREMENT_ID="G-XXXXXXXXXX"

to your .env.local file.

As an alternative, you can use the gaMeasurementId param to pass your Google Analytics measurement id.

The NEXT_PUBLIC_GA_MEASUREMENT_ID environment variable will take precedence over the gaMeasurementId param, so if both are set with different values, the environment variable will override the param.

Scripts

Use the GoogleAnalytics component to load the gtag scripts. You can add it to a custom App component and this will take care of including the necessary scripts for every page (or you could add it on a per page basis if you need more control):

// pages/_app.js
import { GoogleAnalytics } from "nextjs-google-analytics";

const App = ({ Component, pageProps }) => {
  return (
    <>
      <GoogleAnalytics />
      <Component {...pageProps} />
    </>
  );
};

export default App;

By default, scripts are loaded using the afterInteractive strategy, which means they are injected on the client-side and will run after hydration.

If you need more control, the component exposes the strategy prop to control how the scripts are loaded:

// pages/_app.js
import { GoogleAnalytics } from "nextjs-google-analytics";

const App = ({ Component, pageProps }) => {
  return (
    <>
      <GoogleAnalytics strategy="lazyOnload" />
      <Component {...pageProps} />
    </>
  );
};

export default App;

also, you can use alternative to default path for googletagmanager script by

<GoogleAnalytics gtagUrl="/gtag.js" />

Page views

To track page views set the trackPageViews prop of the GoogleAnalytics component to true.

// pages/_app.js
import { GoogleAnalytics } from "nextjs-google-analytics";

const App = ({ Component, pageProps }) => {
  return (
    <>
      <GoogleAnalytics trackPageViews />
      <Component {...pageProps} />
    </>
  );
};

export default App;

By default it will be trigger on hash changes if trackPageViews is enabled, but you can ignore hash changes by providing an object to the trackPageViews prop:

// pages/_app.js
import { GoogleAnalytics } from "nextjs-google-analytics";

const App = ({ Component, pageProps }) => {
  return (
    <>
      <GoogleAnalytics trackPageViews={{ ignoreHashChange: true }} />
      <Component {...pageProps} />
    </>
  );
};

export default App;

As an alternative, you can directly call the usePageViews hook inside a custom App component, do not set trackPageViews prop on the GoogleAnalytics component or set it to false (default):

// pages/_app.js
import { GoogleAnalytics, usePageViews } from "nextjs-google-analytics";

const App = ({ Component, pageProps }) => {
  usePageViews(); // IgnoreHashChange defaults to false
  // usePageViews({ ignoreHashChange: true });

  return (
    <>
      <GoogleAnalytics /> {/* or <GoogleAnalytics trackPageViews={false} /> */}
      <Component {...pageProps} />
    </>
  );
};

export default App;

The module also exports a pageView function that you can use if you need more control.

Custom event

You can use the event function to track a custom event:

import { useState } from "react";
import Page from "../components/Page";
import { event } from "nextjs-google-analytics";

export function Contact() {
  const [message, setMessage] = useState("");

  const handleInput = (e) => {
    setMessage(e.target.value);
  };

  const handleSubmit = (e) => {
    e.preventDefault();

    event("submit_form", {
      category: "Contact",
      label: message,
    });

    setState("");
  };

  return (
    <Page>
      <h1>This is the Contact page</h1>
      <form onSubmit={handleSubmit}>
        <label>
          <span>Message:</span>
          <textarea onChange={handleInput} value={message} />
        </label>
        <button type="submit">submit</button>
      </form>
    </Page>
  );
}

Web Vitals

To send Next.js web vitals to Google Analytics you can use a custom event on the reportWebVitals function inside a custom App component:

// pages/_app.js
import { GoogleAnalytics, event } from "nextjs-google-analytics";

export function reportWebVitals({ id, name, label, value }) {
  event(name, {
    category: label === "web-vital" ? "Web Vitals" : "Next.js custom metric",
    value: Math.round(name === "CLS" ? value * 1000 : value), // values must be integers
    label: id, // id unique to current page load
    nonInteraction: true, // avoids affecting bounce rate.
  });
}

const App = ({ Component, pageProps }) => {
  return (
    <>
      <GoogleAnalytics />
      <Component {...pageProps} />
    </>
  );
};

export default App;

If you are using TypeScript, you can import NextWebVitalsMetric from next/app:

import type { NextWebVitalsMetric } from "next/app";

export function reportWebVitals(metric: NextWebVitalsMetric) {
  // ...
}

Using the gaMeasurementId param

All exported components, hooks, and functions, accept an optional gaMeasurementId param that can be used in case no environment variable is provided:

// pages/_app.js
import { GoogleAnalytics, event } from "nextjs-google-analytics";
import { gaMeasurementId } from "./lib/gtag";

export function reportWebVitals({
  id,
  name,
  label,
  value,
}: NextWebVitalsMetric) {
  event(
    name,
    {
      category: label === "web-vital" ? "Web Vitals" : "Next.js custom metric",
      value: Math.round(name === "CLS" ? value * 1000 : value), // values must be integers
      label: id, // id unique to current page load
      nonInteraction: true, // avoids affecting bounce rate.
    },
    gaMeasurementId
  );
}
const App = ({ Component, pageProps }) => {
  usePageViews({ gaMeasurementId });

  return (
    <>
      <GoogleAnalytics gaMeasurementId={gaMeasurementId} />
      <Component {...pageProps} />
    </>
  );
};

export default App;

Debugging you Google Analytics

  1. Install the Google Analytics Debugger.

  2. Turn it on by clicking its icon to the right of the address bar.

  3. Open the Chrome Javascript console to see the messages.

    On Windows and Linux, press Control-Shift-J.

    On Mac, press Command-Option-J.

  4. Refresh the page you are on.

TypeScript

The module is written in TypeScript and type definitions are included.

Contributing

Contributions, issues and feature requests are welcome!

Show your support

Give a ⭐️ if you like this project!

LICENSE

MIT

Note that the project description data, including the texts, logos, images, and/or trademarks, for each open source project belongs to its rightful owner. If you wish to add or remove any projects, please contact us at [email protected].