ShipFa.st with Google Analytics

Replacing Plausible with Google Analytics

Step-by-step guide for replacing ShipFa.st default analytics integration with Google Analytics

ShipFa.st (by Marc Lou) has become my go-to boilerplate for any new web project I’m working on. Plausible is the default analytics integration for the ShipFa.st template, and I’m sure they are a terrific product.

Why change?

When I create a micro-site, such as Binge Waste, I’d rather avoid the $9/m price tag that comes with Plausible (I might revisit that decision in the future, as some of my projects gain traction). So I prefer using good old Google Analytics.

This step-by-step guide will help you replace Plausible with Google Analytics

Extending the configuration

We’ll start by updating the ConfigProps type within /types/config.ts, and add a measurementId property:

export interface ConfigProps {
  ...
  googleAnalytics: {
    measurementId: string;
  }
}

Next, we’ll go ahead and update our project’s configuration in the config.ts file in our root folder:

const config = {
  ...
  googleAnalytics: {
    measurementId: "G-XXXXXXXXXX"
  }
} as ConfigProps;

Adding a Google Analytics component

Once we’re done with the configuration, it’s time to add a component that will import the Google Analytics scripts into our page. Let’s add a GoogleAnalytics.tsx file within the /components folder, and add the following code:

import React, { Fragment } from 'react';
import Script from 'next/script';
import config from "@/config";

const GoogleAnalytics = () => {
  return <>
    {config.googleAnalytics.measurementId &&
        React.createElement(Fragment, null, 
          [
            React.createElement(Script, { key: "next-googletagmanager-script", async: true, src: `https://www.googletagmanager.com/gtag/js?id=${config.googleAnalytics.measurementId}`, strategy: "afterInteractive"}),
            React.createElement(Script, { key: "next-googletagmanager-init", dangerouslySetInnerHTML: {
                __html: `
            window.dataLayer = window.dataLayer || [];
            function gtag() {
              dataLayer.push(arguments);
            }          
            gtag('js', new Date());
            gtag('config', '${config.googleAnalytics.measurementId}');`
          }})
          ]
        )
    }
  </>
};

export default GoogleAnalytics;

Adding Google Analytics to our pages

Lastly, we need to embed our component to the <head> element of our pages. Let’s update our layout.tsx file, so we’ll have analytics across the site:

import GoogleAnalytics from '@/components/GoogleAnalytics';

...

    <head>
        ...
        <GoogleAnalytics />
    </head>

Conclusion

With these easy steps, we can easily start gathering analytics from our product.