Quick tweaks to improve your Ahoy analytics data
Ahoy is a popular gem that makes it easy to track visits and event analytics in your Rails 8 app.
The gem is well-documented, so I’m not going to walk through the setup here. But since analytics is only as good as the data – garbage in, garbage out – there a few small changes I make on projects to try and keep the data clean and usable.
Events
Event names
It’s important to follow a consistent naming system for events. This makes your dashboards and reports more intuitive, and avoids a mess of duplicates (cart_created, CartCreated, created_cart).
I like to follow the object–action framework: Project Created, User Invited, Article Updated, and so on. The naming convention you choose doesn’t need to be clever, it just needs to be consistent and predictable.
Visits
Ahoy creates a visit
when someone lands on your site. By default, visits are generated server-side, which can cause a few problems.
Controller actions
Some controller actions shouldn’t be recorded as visits at all. You can skip visit tracking in specific controllers by adding:
skip_before_action :track_ahoy_visit
Bot requests, disabled cookies
Server-side visit tracking can also lead to bot requests recorded as visits, or multiple visits recorded for users with cookies disabled.
You can avoid this by setting server_side_visits
to :when_needed
, which defers visit tracking to JavaScript and only create visits server-side when they are needed by events.
# Add to your Ahoy inializer
Ahoy.server_side_visits = :when_needed
Active Storage hits
Serving images or files with Active Storage can also trigger Ahoy visits. You can prevent this by stripping cookies from these requests with the rack-strip-cookies gem:
Add to your Gemfile:
gem 'rack-strip-cookies', '~> 2.0.0'
Then in application.rb:
# prevent ahoy from tracking visits on Active Storage calls
config.middleware.insert_before(
ActionDispatch::Cookies,
Rack::StripCookies,
paths: %w[
/rails/active_storage/representations/proxy
/rails/active_storage/blobs/proxy
]
)
These small tweaks only take a few minutes to implement, but they can save you hours of time cleaning up messy data further down the line.
