Inertia.js: Track Google Analytics

Published 04 November 2020 15:51 (2-minute read)

Since Inertia.js is working on the client-side and making "inertia"-request it doesn't trigger a new page load. That's why Jonathan, the creator of Inertia.js, made the event system.

With the event system, it's possible to hook into the Inertia events and manually trigger an event. You can use this in the front-end to trigger for example a Google Analytics page view event.

Examples

In this post, I show examples of how you can trigger custom events.

Note: to use the Inertia event system you have to use at least version 0.3 ("@inertiajs/[email protected]^0.3").

Google Analytics (gtag)

import { Inertia } from '@inertiajs/inertia'

Inertia.on('navigate', (event) => {
  gtag('event', 'page_view', {
   'page_location': event.detail.page.url
  });
})

Note: the function "gtag" is using the dataLayer array in the background to push the details too. That means that you could use the dataLayer method.

Google Analytics (analytics.js)

import { Inertia } from '@inertiajs/inertia'

Inertia.on('navigate', (event) => {
  ga('send', 'pageview');
})

Google Analytics (dataLayer)

import { Inertia } from '@inertiajs/inertia'

Inertia.on('navigate', (event) => {
  dataLayer.push({
    'url': event.detail.page.url,
    'event': 'pageview'
  });
})

Relevant sources

Robin Dirksen
Robin Dirksen

Follow me on Twitter, there I post web-related content, tips/tricks, and other interesting things.

On my blog, you can find articles that I've found useful or wanted to share with anyone else.

If you want to know more about this article or just want to talk to me, don't hesitate to reach out.

Legal