How to setup Plausible Analytics with Rails 7 Importmaps

423 views Asked by At

Plausible Analytics is an alternative to Google Analytics for tracking page views. I am trying to integrate plausible with importmaps in rails 7 but its not working.

Plausible provides instructions to include this script tag below as the only thing needed:

<script defer data-domain="yourdomain.com" src="https://plausible.io/js/script.js"></script>

In attempting to do this the "Rails 7 Way", I have tried to do things the importmap way by doing the following below:

bin/importmap pin plausible-tracker --download

In my layout I've added:

<%= javascript_import_module_tag 'plausible-tracker', "data-turbo-track": "reload", defer: true, "data-domain": "amorc.org.au" %>

(This was based on my interpretation of Plausible's suggested script tag above).

I can see this code reflected in the head when I inspect the desired page, but no tracking is going back to plausible, so its obviously not correctly setup yet.

(I've so far added nothing in application.js)

How do I do this correctly?

EDIT 1: So my layout currently has these three javascript related tags, which ones do I need to keep?

1. <%= javascript_include_tag "application", "data-turbo-track": "reload", defer: true %>

2. <%= javascript_importmap_tags %>

3. <%= javascript_import_module_tag 'plausible-tracker', "data-turbo-track": "reload", defer: true, "data-domain": "amorc.org.au" %>
1

There are 1 answers

0
posixpascal On

You are halfway there.

If you installed plausible-tracker, you have the npm packsge which slightly differs from the cdn version.

You need to import the script in your application.js file, this is where import-map will take care of loading/bundling the script.

import Plausible from 'plausible-tracker'

const plausible = Plausible({
    domain: 'YOURDOMAIN'
});
console.log(plausible);

Make sure the application.js is loaded in your view:

<%= javascript_include_tag "application", "data-turbo-track": "reload", defer: true %>

You should see the plausible object logged into your browser console.