Skip to content

Set up Google Analytics #110

Open
Open
@rgbkrk

Description

@rgbkrk

Here's all the bits we need, though you'll probably have to change _document.js

gtag.js

// @flow
// nteract.io's GA Tracking ID (I just set this up)
export const GA_TRACKING_ID = "UA-129108362-1";

/**
 * pages/_document.js will load the google analytics adapter and use
 * nteract.io's tracking ID above.
 *
 * The following functions are helpers for submitting events and page views
 *
 * Usage:
 *   gtag.event({
 *      action: 'clone',
 *      category: 'workflow',
 *      label: 'test'
 *   })
 *
 */

// https://developers.google.com/analytics/devguides/collection/gtagjs/pages
export const pageview = url => {
  window.gtag("config", GA_TRACKING_ID, {
    page_location: url
  });
};

// https://developers.google.com/analytics/devguides/collection/gtagjs/events
export const event = ({ action, category, label, value }) => {
  window.gtag("event", action, {
    event_category: category,
    event_label: label,
    value: value
  });
};

pages/_app.js:

import * as React from "react";

import App, { Container } from "next/app";
import * as gtag from "../gtag";

import Router from "next/router";

Router.events.on("routeChangeComplete", url => gtag.pageview(url));

// This is the default setup, only placing it here to make the container nicer
// to work with
export default class MyApp extends App {
  static async getInitialProps({ Component, router, ctx }) {
    let pageProps = {};

    if (Component.getInitialProps) {
      pageProps = await Component.getInitialProps(ctx);
    }

    return { pageProps };
  }

  render() {
    const { Component, pageProps } = this.props;

    return (
      <Container>
        <Component {...pageProps} />
      </Container>
    );
  }
}

_document.js

import React from 'react'
import Document, { Head, Main, NextScript } from 'next/document'
import flush from 'styled-jsx/server'

import { GA_TRACKING_ID } from '../lib/gtag'

export default class extends Document {
  static getInitialProps ({ renderPage }) {
    const { html, head, errorHtml, chunks } = renderPage()
    const styles = flush()
    return { html, head, errorHtml, chunks, styles }
  }

  render () {
    return (
      <html>
        <Head>
          {/* Global Site Tag (gtag.js) - Google Analytics */}
          <script
            async
            src={`https://www.googletagmanager.com/gtag/js?id=${GA_TRACKING_ID}`}
          />
          <script
            dangerouslySetInnerHTML={{
              __html: `
            window.dataLayer = window.dataLayer || [];
            function gtag(){dataLayer.push(arguments);}
            gtag('js', new Date());
            gtag('config', '${GA_TRACKING_ID}');
          `}}
          />
        </Head>
        <body>
          <Main />
          <NextScript />
        </body>
      </html>
    )
  }
}

Activity

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

Type

No type

Projects

No projects

Milestone

No milestone

Relationships

None yet

Development

No branches or pull requests

Issue actions