Upgrade to the next generation of Google Analytics in Gatsby project
Tags: gatsby, react, seo, webmaster
Published: 2020-10-25 20:32:10

<small>Cover image produced by [Google](https://storage.googleapis.com/gweb-uniblog-publish-prod/images/E02584187-Google-GMP-Future-of-Analytics-B.max-1000x1000.png)</small>

## Background

Did you know that Google has released [new Google Analytics](https://blog.google/products/marketingplatform/analytics/new_google_analytics/) a couple of weeks ago?

It's perfectly OK if you didn't. Until a few hours ago, I myself didn't know about it. Although I use Google Analytics everyday for my website([카지노사이트](https://casinohouse.link)) SEO. Somehow Google Analytics haven't shown me any update alerts or messages. I heard about it from some of my colleagues.

### What's new in updated version?

- Google Analytics can now detect device switching (like when a user changes from mobile to desktop) and will show you unified and integrated web & app reporting.

- And [much more](https://www.socialmediatoday.com/news/google-launches-updated-google-analytics-including-improved-reporting-and/587052/) that I don't understand right now

- Most importantly: [It is now default experience for all Google Analytics properties and where Google is investing for future improvements.](https://support.google.com/analytics/answer/10089681#start)

## Problem

As I wrote in the follwing DEV post

{% link https://dev.to/jessica000/how-i-got-perfect-google-lighthouse-score-with-gatsby-5coj %}

my website([카지노사이트](https://casinohouse.link)) is built with Gatsby.

In Gatsby.js, you install legacy (well, not yet but if you know what I mean) Google Analytics with [gatsby-plugin-google-analytics](https://www.gatsbyjs.com/plugins/gatsby-plugin-google-analytics/). Like this way:

**gatsby-config.js**
```javascript
plugins: [
    {
      resolve: 'gatsby-plugin-google-analytics',
      options: {
        trackingId: 'UA-1*******0-2',
        head: true,
        defer: true,
      },
    },
    ...
]
```

The problem is, you cannot install newer version of Google Analytics in this way. And as far as I know, there is not a gatsby plugin for newer version yet. :(

## Goal

For updated version, you need to add measurement ID that looks like `G-**********` and need to

> Copy and paste this code as the first item into the <head> of every webpage you want to measure.
```html
<!-- Global site tag (gtag.js) - Google Analytics -->
<script async src="https://www.googletagmanager.com/gtag/js?id=G-**********"></script>
<script>
  window.dataLayer = window.dataLayer || [];
  function gtag(){dataLayer.push(arguments);}
  gtag('js', new Date());

  gtag('config', 'G-**********');
</script>
```

## How to

### 1\. Get GA4 stream measurement ID

#### First, log in to your [Google Analytics](https://analytics.google.com/) account and click "Admin" button.

![GA4 upgrade step1](https://dev-to-uploads.s3.amazonaws.com/i/ign8dqizhrgweknv39cx.png)

#### Next, click "Create Property" button. 

Just ignore "Upgrade to GA4" here. It will take you to create property screen anyway.

![GA4 upgrade step2](https://dev-to-uploads.s3.amazonaws.com/i/n4zedi3ae40xf6z6fpsx.png)

Configure your property. Do as you like.

#### Then, select created property and click "Data Stream" tab, then click "Add stream" -> Web.

If you already have a Web stream, just click to see its details.

![GA4 upgrade step3](https://dev-to-uploads.s3.amazonaws.com/i/n953jcc8rcq1y4m5tw5b.png)

#### In detail page, you can get your measurement ID and gtag script:

![GA4 upgrade step4](https://dev-to-uploads.s3.amazonaws.com/i/7fkiofx0aroclkedsahn.png)

### 2\. Install acquired gtag in Gatsby project

My approach is a workaround but it will do its work before gatsby plugin update. I customized `html.js` as described in this [article](https://www.gatsbyjs.com/docs/custom-html/). FYI, `html.js` is what Gatsby uses to server render `head` tag and other components that React cannot touch.


#### First, copy `.cache/default-html.js` to `html.js`. 

If you already have `html.js`, you can skip this step.


```shell
$ cp .cache/default-html.js src/html.js
```

`html.js` will look like the following:

```jsx
 <html {...props.htmlAttributes}>
    <head>
        <meta charSet="utf-8" />
        <meta httpEquiv="x-ua-compatible" content="ie=edge" />
        <meta
          name="viewport"
          content="width=device-width, initial-scale=1, shrink-to-fit=no"
        />
        {props.headComponents}
    </head>
    <body {...props.bodyAttributes}>
...
```

#### Edit `head` tag like the following:

```jsx
<head>
    <script
        async
        src="https://www.googletagmanager.com/gtag/js?id=G-**********"
    />
    <script
        dangerouslySetInnerHTML={{
            __html: `
            window.dataLayer = window.dataLayer || [];
            function gtag(){dataLayer.push(arguments);}
            gtag('js', new Date());
            gtag('config', 'G-**********');
        `,
        }}
    />
    <meta charSet="utf-8" />
    <meta httpEquiv="x-ua-compatible" content="ie=edge" />
    <meta
        name="viewport"
        content="width=device-width, initial-scale=1, shrink-to-fit=no"
    />
        {props.headComponents}
</head>
```

#### Deploy your project.

#### Go to your Google Analytics and check if it works.

![카지노사이트 바카라사이트 https://casinohouse.link](https://dev-to-uploads.s3.amazonaws.com/i/3r40udylm6jw4yq28h3f.png)

You can uninstall legacy tracking code and gatsby plugin after successful upgrade.

### Conclusion

That's all folks!

If you find anything wrong in my post or have a better idea, please leave a comment to let me know.

If you're good at Gatsby.js, please come visit my [website](https://casinohouse.link) and share your idea. Any suggestion is welcome!