To integrate Google Analytics (GA) with Laravel Inertia SSR using Vue 3, the steps you've taken are mostly correct, but there are a few adjustments and additional steps you might need to ensure proper tracking. Here's a more comprehensive solution:
-
Add the GA script to
app.blade.php:Ensure that the GA script is correctly added to your
app.blade.phpfile. This script should initialize GA and set up thegtagfunction.<body class="antialiased"> @inertia <script async src="https://www.googletagmanager.com/gtag/js?id=AW-xxxxxxxxx"></script> <script> window.dataLayer = window.dataLayer || []; function gtag() { window.dataLayer.push(arguments); } gtag('js', new Date()); gtag('config', 'AW-xxxxxxxxx'); </script> </body> -
Track page views in
resources/js/app.js:Since you're using Inertia.js, you need to track page views on route changes. You can do this by listening to Inertia's
navigateevent.import { createApp, h } from 'vue'; import { createInertiaApp } from '@inertiajs/inertia-vue3'; import { InertiaProgress } from '@inertiajs/progress'; import { Inertia } from '@inertiajs/inertia'; createInertiaApp({ resolve: name => require(`./Pages/${name}`), setup({ el, app, props, plugin }) { createApp({ render: () => h(app, props) }) .use(plugin) .mount(el); }, }); InertiaProgress.init(); if (import.meta.env.VITE_APP_ENV === "production") { Inertia.on('navigate', (event) => { gtag('config', 'AW-xxxxxxxxx', { page_path: event.detail.page.url, }); }); } -
Ensure environment variables are set correctly:
Make sure your environment variables are correctly set in your
.envfile and that Vite is configured to use them.VITE_APP_ENV="${APP_ENV}" -
Verify GA setup:
After setting up the above steps, you should verify that GA is correctly tracking your application. You can do this by checking the Real-Time reports in your Google Analytics dashboard.
By following these steps, you should have a proper integration of Google Analytics with your Laravel Inertia SSR application using Vue 3. This setup ensures that page views are tracked correctly on route changes.