Posts Learn Components Snippets Categories Tags Tools About
/

How to integrate Google Analytics 4 with Inertia Js

Learn the ways to integrate Google Analytics 4 with Inertia Js in 3 simple steps

Created on Jul 06, 2022

578 views

In this short snippet, you will learn the ways to integrate Google Analytics 4 in your Laravel Inertia website.

Step 1: Create Google Analytics and Copy Analytics Code


We assume that you have created Google Analytics 4 property and then have the code already prepared. It will look as follows.
<script async src="https://www.googletagmanager.com/gtag/js?id=G-XXX"></script>
<script>
    window.dataLayer = window.dataLayer || [];

    function gtag() {
        dataLayer.push(arguments);
    }

    gtag("js", new Date());
    gtag("config", "G-XXX");
</script>

Step 2: Update Laravel Blade Base Layout with Analytics Code


Next, you need to update the "views/app.blade.php" with the analytics base code so that it's referenced for all of the pages that extend it. For the full code example, it will be like the code below.
<!DOCTYPE html>
<html lang="{{ str_replace('_', '-', app()->getLocale()) }}" class="scroll-smooth">
<head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <title inertia>{{ config('app.name', 'Laravel Inertia GA 4') }}</title>
    <link rel="icon" type="image/png" href="{{ url('/favicon.png') }}">
    <link rel="preconnect" href="https://fonts.googleapis.com">
    <link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
    <link href="https://fonts.googleapis.com/css2?family=Roboto:[email protected];500;700&display=swap" rel="stylesheet">
    @vite(['resources/css/app.css', 'resources/js/app.js'])
    @inertiaHead
</head>
<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-XXX"></script>
    <script>
        window.dataLayer = window.dataLayer || [];

        function gtag() {
            dataLayer.push(arguments);
        }
    </script>
@endproduction
</body>
</html>

Step 3: Update app.js to Fire GA 4 Event


Now when the page navigates you will have to fire an event to allow Google Analytics 4 to collect the page views data. To do that you can listen to the "navigate" event on the "resources/js/app.js". 
/**
 * Track Page and Send to Google Analytic
 * */
if (process.env.NODE_ENV === "production") {
    Inertia.on("navigate", (event) => {
        gtag("js", new Date());
        gtag("config", "G-XXX");
    });
}
I hope this short snippet helps and cheers, happy coding! Do share it with your friends if you find it helpful.

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

new

PostSrc Code Components

Collection of Tailwind CSS components for everyone to use. Browse all of the components that are right for your project.

View Components

Sponsors 👑

+ Add Yours
)