npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2024 – Pkg Stats / Ryan Hefner

nextjs-google-analytics-gtm

v1.1.12

Published

Google Analytics for Next.js with support for GTM server container

Downloads

369

Readme

Nextjs Google Analytics

npm version codecov CodeFactor

Google Analytics for Next.js

Installation

npm install --save nextjs-google-analytics-gtm

Usage

Note:

This is a fork which allows users to use the original package by Mauricio Robayo, but with a custom GTM server-side container.

To do this you MUST define the following environment variable:

NEXT_PUBLIC_GTM_DOMAIN="www.yourdomain.com" 

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.

Scripts

Use the GoogleAnalytics component to load the gtag scripts. You can add it to a custom Document 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/document.tsx
import Document, {
  DocumentContext,
  Html,
  Head,
  Main,
  NextScript,
} from "next/document";
import { GoogleAnalytics } from "nextjs-google-analytics-gtm";

class MyDocument extends Document {
  static async getInitialProps(ctx: DocumentContext) {
    const initialProps = await Document.getInitialProps(ctx);

    return initialProps;
  }
  render() {
    return (
      <Html>
        <Head>
          <GoogleAnalytics />
        </Head>
        <body>
          <Main />
          <NextScript />
        </body>
      </Html>
    );
  }
}

export default MyDocument;

Page views

To track all pages views, call the usePagesViews hook inside a custom App component, make sure to include the necessary gtag scripts with the GoogleAnalytics component:

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

const App = ({ Component, pageProps }) => {
  usePagesViews();

  return (
    <>
      <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 { 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 (
    <>
      <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) {
  // ...
}

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