Skip to content

Analytics Magic

A resource for Google Analytics 4

  • Home
  • Setting up GA4 in Mithril

Setting up GA4 in Mithril

Setting up Google Analytics 4 (GA4) in a Mithril.js project is straightforward, though it doesn’t have a specific library or component like in some other frameworks.

First like every example we do you have to create a GA4 Property, here is the walkthrough on doing this.

Once this is done, you need to do is add the GA4 script to your HTML. Open your index.html file and add the following code inside the <head> tag:

<!-- Global site tag (gtag.js) - Google Analytics -->
<script async src="https://www.googletagmanager.com/gtag/js?id=G-XXXXXXXXXX"></script>
<script>
  window.dataLayer = window.dataLayer || [];
  function gtag(){dataLayer.push(arguments);}
  gtag('js', new Date());
  gtag('config', 'G-XXXXXXXXXX');
</script>

Remember to replace “G-XXXXXXXXXX” with your GA4 Measurement ID.

To track page views in a single page application like one you might build with Mithril, you need to send a page view hit whenever the route changes. This can be done by using Mithril’s route change event.
You can use the onmatch or onupdate lifecycle methods in Mithril to track page views. Here’s an example:

m.route(document.body, "/", {
  "/": {
    onmatch: function() {
      gtag('config', 'G-XXXXXXXXXX', {'page_path': '/'});
    },
    render: function() {
      return m(Layout, m(Home));
    }
  },
  "/about": {
    onmatch: function() {
      gtag('config', 'G-XXXXXXXXXX', {'page_path': '/about'});
    },
    render: function() {
      return m(Layout, m(About));
    }
  },
  // ...other routes
})

In this example, a page view is sent to Google Analytics whenever the route changes. If you want to track custom events, like button clicks or form submissions, you can do so by calling gtag in your event handlers. Here’s an example:

m("button", {onclick: () => {
  gtag('event', 'click', {
    'event_category': 'button',
    'event_label': 'my-button',
    'value': 'my-value'
  });
}}, "Click me")

This will send an event to GA4 every time the button is clicked.

This is a basic implementation and might need to be adjusted based on your app’s requirements and structure. For more complex analytics, consider using Google Tag Manager or a dedicated JavaScript library.

Copyright © 2026 Analytics Magic.

Theme: Oceanly News Dark by ScriptsTown