Home / Snippets / How to integrate Google Analytics 4 with Inertia Js
How to integrate Google Analytics 4 with Inertia Js cover

How to integrate Google Analytics 4 with Inertia Js

2.6K

2 years ago

0 comments

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:wght@400;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.
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