
If you’re building a modern Rails 8 application that uses Turbo for fast navigation and Stimulus for reactive behavior, integrating Google Analytics 4 (GA4) requires a few extra steps to ensure accurate pageview tracking.
Unlike traditional full-page loads, Turbo drives navigation via AJAX, so the default GA4 setup won’t automatically register pageviews after the initial load. This article guides you through integrating GA4 into your Rails 8 app with proper support for Turbo and Stimulus.
1. Add the GA4 gtag.js Snippet to Your Layout
First, include the base Google Analytics snippet in your application layout file.
app/views/layouts/application.html.erb
Replace G-XXXXXXXXXX with your actual GA4 Measurement ID.
This will ensure the first page load is tracked correctly.
2. Track Turbo Page Visits
Turbo doesn’t reload the page on navigation, which means Google Analytics won’t see the route change unless we tell it manually.
The simplest way is to use an inline script to listen for turbo:load
events and send a page view to GA:
This works immediately and is sufficient for basic GA integration.