Home / Snippets / How To Add Google Analytics 4 to Inertia JS Laravel
How To Add Google Analytics 4 to Inertia JS Laravel cover

How To Add Google Analytics 4 to Inertia JS Laravel

1.2K

2 years ago

0 comments

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.
notion avatar

Alaz

Week-end developer currently experimenting with web, mobile, and all things programming.

Topics:

Frontend

Resource

Average

Average

Support Us

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

Welcome to PostSrc V3

PostSrc Dark Logo

You have to login to favorite this