Posts Learn Components Snippets Categories Tags Tools About
/

How To Add Google Analytics 4 to Inertia JS Laravel

Learn the ways to setup Google Analytics 4 for your Inertia JS project the easy way in Laravel

Created on Jun 26, 2022

515 views

In this short snippet, you will learn how to set up Google Analytics 4 in your Inertia project with Laravel backend. Let's get started!

Step 1: Reference your Google Analytics link in Layout Page


The first step you need to reference your Google Analytics code and it's as follows. Do note that the location of this file is "views/app.blade.php". The head and footer part and other styling are committed for the code readability.
<body class="font-sans antialiased bg-slate-50 dark:bg-slate-800">
    @inertia

    @production
        <script async src="https://www.googletagmanager.com/gtag/js?id=G-XXXX"></script>
        <script>
            window.dataLayer = window.dataLayer || [];
            function gtag(){dataLayer.push(arguments);}
        </script>
    @endproduction
</body>

Make sure to update the tracking tag with your tracker G-XXXX. and once you have done that, let's move on to setting up the analytics binding.

Step 2: Setup Inertia JS Google Analytics Binding


The next step is to define the analytic code on the app.js file. This code will be called & executed whenever we navigate to different pages.
/**
 * Track Page and Send to Google Analytic
 * */
if (process.env.NODE_ENV === 'production') {
    Inertia.on('navigate', (event) => {
        gtag('js', new Date());
        gtag('config', 'G-XXXX');
    })
}
The code is also wrapped with "process.env.NODE_ENV === 'production'" to ensure that it's only on production. I hope this helps, cheers.

If you like our tutorial, do make sure to support us by being our Patreon or buy us some coffee ☕️

)