Nextjs Google Analytics
Google Analytics for Next.js, based on the official next.js example with-google-analytics.
Your Google Analytics measurement id is read from NEXT_PUBLIC_GA_MEASUREMENT_ID
, 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 .env.local
.
Installation
npm install --save nextjs-google-analytics
Usage
Add the GoogleAnalytics
components to the Head
component in a custom document, this will take care of including the necessary scripts:
import Document, { Html, Head, Main, NextScript } from "next/document";
import { GoogleAnalytics } from "nextjs-google-analytics";
export default class MyDocument extends Document {
render() {
return (
<Html>
<Head>
<GoogleAnalytics />
</Head>
<body>
<Main />
<NextScript />
</body>
</Html>
);
}
}
Page views
Call the usePageView
hook inside _app.js
:
import { useEffect } from "react";
import { useRouter } from "next/router";
import { usePageView } from "nextjs-google-analytics";
const App = ({ Component, pageProps }) => {
const router = useRouter();
usePageView();
return <Component {...pageProps} />;
};
export default App;
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>
);
}
TypeScript
The module is written in TypeScript and type definitions are included.
LICENSE
MIT