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 year ago


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">

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

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

Ahmad Aziz

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






Support Us

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

Post Tutorials

Learn trending tutorials for ReactJs, React Native, VueJS, NextJs, Laravel, Tailwind CSS, and Flutter development.
View Tutorials

Code Components

Collection of Tailwind CSS components for everyone to use. Browse all of the components that's right for your web projects
View Components

Welcome to PostSrc V3

PostSrc Dark Logo

You have to login to favorite this