How to use Google Analytics 4 with Gatsby

How to use Google Analytics 4 with Gatsby

Google introduced version 4 of Analytics back in October 2020 and it was just recently that I noticed that my go-to plugin does not work anymore... In this small post I will show you how to get Google Analytics 4 working in your Gatsby project.

Problem

When creating Gatsby projects in the past and when using Gatsby starters the most common Google Analytics plugin seems to be gatsby-plugin-google-analytics. But it was just recently that I discovered that this does not work with the new version of Google Analytics.

Soloution

Replace the gatsby-plugin-google-analytics plugin in your gatsby-config.js file with gatsby-plugin-google-gtag. Here is the bare minimum configuration required in order for analytics to work:

{
    resolve: `gatsby-plugin-google-gtag`,
    options: {
        trackingIds: ["YOUR_ID"],
    }
}

Google Analytics should now work just like before and you should see your data being reported!