Giter Site home page Giter Site logo

nuxt-matomo's Introduction

Matomo analytics for Nuxt.js

Build Status npm npm (scoped with tag)

Add Matomo analytics to your nuxt.js application. This plugin automatically sends first page and route change events to matomo

Setup

nuxt-matomo is not enabled in dev mode unless you set the debug option

  • Install with
npm install --save nuxt-matomo
// or
yarn add nuxt-matomo
  • Add nuxt-matomo to modules section of nuxt.config.js
  modules: [
    ['nuxt-matomo', { matomoUrl: '//matomo.example.com/', siteId: 1 }],
  ]

Usage

By default route.fullPath and the document title are tracked. You can add additional tracking info by adding a route.meta.matomo object in a middleware or by adding a matomo function or object to your page components.

The matomo javascript tracker is also injected as $matomo in the Nuxt.js context. Use this to e.g. manually track a page view. See the injected and manually tracked pages in the test fixture for an example

📘 See the official Matomo JavaScript Tracking client docs for a full overview of available methods

Middleware example

export default function ({ route, store }) {
  route.meta.matomo = {
    documentTitle: ['setDocumentTitle', 'Some other title'],
    userId: ['setUserId', store.state.userId],
    someVar: ['setCustomVariable', 1, 'VisitorType', 'Member']
  }
}

Page component example

<template>
  <div>
    <h1 v-if="expVarId === 1">New Content</h1>
    <h1 v-else>Original Content</h1>
  </div>
</template>

<script>
  export default {
    // the matomo function is bound to the Matomo tracker
    // (this function is called before the page component is initialized)
    matomo(from, to, store) {
      this.setCustomVariable(1, 'VisitorType', 'Special Member')
    },
    // return false if you want to manually track here
    matomo(from, to, store) {
      this.setDocumentTitle('my title')
      this.trackPageView()
      return false
    },
    // or let the function return an object
    matomo(from, to, store) {
      // this object is merged with the object returned by a global middleware,
      // use the object key to override properties from the middleware
      return {
        someVar: ['setCustomVariable', 1, 'VisitorType', 'Special Member']
      }
    },
    // or simply set an object
    matomo: {
      someVar: ['setCustomVariable', 1, 'VisitorType', 'Special Member']
    },
    [...]
  }
</script>
Track manually with vue-router beforeRouterEnter guard

This is overly complicated, you probably shouldnt use this

<template>
  <div>
    <h1>manually tracked</h1>
  </div>
</template>

<script>
export default {
  matomo: false,
  head() {
    return {
      title: this.title
    }
  },
  data() {
    return {
      title: 'manually tracked'
    }
  },
  beforeRouteEnter(to, from, next) {
    next((vm) => {
      vm.$matomo.setDocumentTitle(vm.title)
      vm.$matomo.trackPageView()
    })
  }
}
</script>

Consent

The plugin extends the matomo tracker with a setConsent(<consentGiven>) convenience method.

When setConsent() is called, the plugin will automatically call rememberConsentGiven when the module option consentExpires has been set. To forget consent you can pass false to this method.

See the basic fixture for an example how to use this method in combination with a Vuex store.

Module Options

siteId (required)

The matomo siteId

matomoUrl

  • Default: Url to matomo installation

trackerUrl

  • Default: matomoUrl + 'piwik.php' Url to piwik.php

scriptUrl

  • Default: matomoUrl + 'piwik.js' Url to piwik.js

onMetaChange

  • Default: false If true, page views will be tracked on the first vue-meta update after navigation occured. See caveats below for more information

blockLoading

  • Default: false

If true, loading of the page is blocked until window.Piwik becomes available. If false, a proxy implementation is used to delay tracker calls until Piwik is available.

addNoProxyWorkaround

  • Default: true

When blockLoading: false we have to wait until window.Piwik becomes available, if a browser supports a Proxy then we use this. Older browsers like IE9/10 dont support this, for these browsers a manual list of api methods to proxy is added when addNoProxyWorkaround: true. See the list here

⚠️ If you set this to false and still need to support IE9/10 you need to include a ProxyPolyfill manually as Babel doesnt provide one

cookies

  • Default: true If false, Matomo will not create a tracking cookie

consentRequired

  • Default: false If true, Matomo will not start tracking until the user has given consent

consentExpires

  • Default: 0 If greater than 0 and when the tracker.setConsent method is called then we call rememberConsentGiven(<consentExpires>) instead of setConsentGiven. See above for more information

doNotTrack

  • Default: false If true, dont track users who have set Mozilla's (proposed) Do Not Track setting

debug

  • Default: false If true, the plugin will log debug information to the console.

The plugin also logs debug information when Nuxt's debug option is set

verbose

  • Default: false If true, the plugin will log every tracker function call to the console

Caveats

document.title

Nuxt.js uses vue-meta to asynchronously update the document.title, this means by default we dont know when the document.title is changed. Therefore the default behaviour for this plugin is to set the route.path as document title.

If you set the module option onMetaChange: true, then this plugin will track page views on the first time some meta data is updated by vue-meta (after navigation). This makes sure the document.title is available and updated, but if you have multiple pages without any meta data then those page views could not be tracked

vue-meta's changed event is only triggered when any meta data changed, make sure all your routes have a head option.

When debug is true, this plugin will show warnings in the console when

  • it detects pages without a title
  • when no vue-meta changed event is triggered within 500ms after navigation (tracking could still occur, the timeout only shows a warning)

You can also use a combination of manual tracking and a vuex store to keep track of the document.title

nuxt-matomo's People

Contributors

decentm avatar pimlie avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar

nuxt-matomo's Issues

Matomo Tracking and/or Matomo Tag Manager?

Hello,

is this package just to add matomo tracking to an nuxt application or is it also possible to use the matomo tag manager with it?

Thanks for an short answer!

Best regards,

Timo

Updating the visitor cookie timeout

Hello,

I would need to add a custom function (paq.push()) in order to update the cookie timeout, following this implementation guideline: https://www.cnil.fr/sites/default/files/typo/document/Configuration_piwik.pdf

I'm quite new to Matomo and Nuxt, some I'm kind of lost to get how to do that...

Here is the code reference to update the original Matomo in-page script:

_paq.push([function() {
var self = this;
function getOriginalVisitorCookieTimeout() {
 var now = new Date(),
 nowTs = Math.round(now.getTime() / 1000),
 visitorInfo = self.getVisitorInfo();
 var createTs = parseInt(visitorInfo[2]);
 var cookieTimeout = 33696000; // 13 months  in seconds
 var originalTimeout = createTs + cookieTimeout - nowTs;
 return originalTimeout;
}
this.setVisitorCookieTimeout( getOriginalVisitorCookieTimeout() );
}]);

I guess I should update the visitor cookie timeout in the middleware:

export default function ({ route }) {
  route.meta.matomo = {
    visitorCookieTimeOut: ['setVisitorCookieTimeout', getOriginalVisitorCookieTimeout()]
  }
}

Would this be the right approach?

consentRequired should not set any cookie until users action

Hello,
when I set consentRequired in the nuxt.config.js it will set a cookie (mtm_consent_removed) when user first time arrive to the page. Even before user does any action.

Is it possible to change this behavior? So that when a user Opt-in it set the regular cookies, and when user Opt-Out it set this mtm_consent_removed cookie?

Not seeing any POST requests

Following the installation instructions, I am not seeing any POST requests go out for the tracker.
I do see the GET but it has no response.

here is the nuxt.config.js

  /*
   ** Nuxt.js modules
   */
  modules: [
    [
      'nuxt-matomo',
      {
        matomoUrl: '//www.mysite.org/',
        siteId: 10,
        debug: true,
        consentRequired: false
      }
    ]
  ],

and here is the modules/matomo.js

export default ({ route }) => {
  console.log('Matomo Middleware\n\n\n\n\n\n\n\n***********')
  if (route.name && !['index', 'injected'].includes(route.name)) {
    console.log('yep')
    route.meta.matomo = {
      someVar1: ['setCustomVariable', 1, 'VisitorType', 'A', 'page'],
      someVar2: ['setCustomVariable', 2, 'OtherType', true, 'page']
    }
    console.log(route.meta.matomo)
  }
}

I feel like I am missing a basic step that I am just not seeing.

this.$matomo is not available in the context using TypeScript

Hi,

I installed the plugin this way:

    [
      "nuxt-matomo",
      {
        matomoUrl: "//matomo.my.domain/",
        siteId: 1,
        cookies: false,
      },
    ],

However during yarn generate I get the following error:

ERROR in components/ExportAs.vue:52:10
TS2339: Property '$matomo' does not exist on type 'ExportAs'.
    50 |
    51 |   foo() {
  > 52 |     this.$matomo.trackGoal(1)
       |          ^^^^^^^
    53 |   }
    54 |

As a result, I can't build my website.

FYI, I'm using JetBrains IDE, and they have rich autocomplete for such kind of injections, e.g nuxt-i18n:
image

Unfortunately, there's no for matomo:
image

Do you have any ideas how to resolve it, or at least bypass?

Unexpected token import error

Getting below error when running 'npm run generate' on my project. I'm a novice at Nuxt and running a tutorial site trying to incorporate Matomo into it. Looks like maybe ES6/Node issue on the syntax perhaps?

> nuxt generate --spa

  nuxt:generate Generating... +0ms
  nuxt: Call error hooks (1) +0ms

 ERROR  Nuxt error

  Error: /home/matt/functions-first-serverless-web-application/www/node_modules/nuxt-matomo/lib/module.js:1
  (function (exports, require, module, __filename, __dirname) { import { resolve } from 'path'
                                                                ^  ^^^^^
  SyntaxError: Unexpected token import

  - vm.js:80 createScript
    vm.js:80:10

  - vm.js:139 Object.runInThisContext
    vm.js:139:10

  - module.js:607 Module._compile
    module.js:607:28

  - module.js:654 Object.Module._extensions..js
    module.js:654:10

  - module.js:556 Module.load
    module.js:556:32

  - module.js:499 tryModuleLoad
    module.js:499:12

  - module.js:491 Function.Module._load
    module.js:491:3

  - module.js:587 Module.require
    module.js:587:17

  - module.js:11 require
    internal/module.js:11:18

  - module.js:121 ModuleContainer.addModule
    [www]/[nuxt]/lib/core/module.js:121:17

  - utils.js:96 promise.then
    [www]/[nuxt]/lib/common/utils.js:96:43


  - next_tick.js:188 process._tickCallback
    internal/process/next_tick.js:188:7

  - module.js:686 Function.Module.runMain
    module.js:686:11

  - bootstrap_node.js:187 startup
    bootstrap_node.js:187:16

  - bootstrap_node.js:608
    bootstrap_node.js:608:3
'''

Use A/B-Testing with nuxt-matomo

Hello,

is there a way to use the matomo a/b-testing feature (https://developer.matomo.org/guides/ab-tests/browser) with nuxt-matomo?

I tried to use something like

const _paq = (window._paq = window._paq || []);
_paq.push([
  'AbTesting::create',
  {

but it ends in an error like this:

_paq.push() was used but Matomo tracker was not initialized before the matomo.js file was loaded. Make sure to configure the tracker via _paq.push before loading matomo.js. Alternatively, you can create a tracker via Matomo.addTracker() manually and then use _paq.push but it may not fully work as tracker methods may not be executed in the correct order.

Any ideas how to create an a/b-test with matomo in nuxt?

Best regards,

Timo

Only tracking first page

It seems that this is only tracking my first page, if I navigate to any other page it does not get tracked. I've followed the instructions listed in the readme, do I need to add a middleware or something?

setting route.meta.matomo has no effect with SSR

When running a universal app, setting route.meta.matomo in a middleware has no effect when the page renders first on the server.

Obviously, matomo is unlikely to work on the server, but is there a way to have this module apply route.meta.matomo when the page is evaluated on the client?

setReferrerUrl(String) not populating dashboard

I am wanting to override the referrer url, with a specific value for tracking purposes.

I am doing the following:

const entryPoint = 'Unicorns Poop Sparkles'
this.$matomo.setReferrerUrl(entryPoint)

When sniffing the network traffic, I see the query parameter being set for urlref with the override I set:
urlref "Unicorns Poop Sparkles"

What I can not find, is where this value should show up for me in the dashboard… I assumed that I would be seeing the value in the “acquisition/All Channel” panel, but I do not see anything populated other than Direct Entry

I know that my code works since I use this: this.$matomo.setCustomVariable(2, 'Role', provider.occupation, 'visit'), and I DO see the custom variable I set Role being populated in the dashboard and according to the docs, both methods are for modifying the tracking object.

So is this a bug or just a lack of Matomo understanding on my part?

Setting configuration at runtime using middleware is ignored

Using a working setup of nuxt-matomo (remote Matomo instance is receiving proper tracking information), setting additional Matomo configuration using a Nuxt middleware does not work.

Setup:

  • nuxt: 2.3.4
  • nuxt-matomo: 0.5.1
  • nuxt.config.js:
modules: [
  ...
  [ 'nuxt-matomo', { matomoUrl: '//matomo.docker.me/', siteId: 1 } ],
  ...
],

router: {
  ...
  middleware: ['my-middleware']
}
  • middleware/my-middleware.js:
export default function ({ route, store }) {
  route.meta.matomo = {
    documentTitle: ['setDocumentTitle', 'Some other title'],
    someVar: ['setCustomVariable', 1, 'VisitorType', 'Member']
  }
}

Investigating the issue shows that:

  • The Nuxt router middleware is properly executed for route changes
  • The nuxt-matomo plugin is also properly executed for route changes
  • The middleware is executed before nuxt-matomo for route changes
  • The route.meta.matomo attribute is undefined when reaching the nuxt-matomo plugin, thus ignoring the custom configuration

Am I missing something?

Do not hesitate to ask for some more information.
Thanks!

Erroring when in Dev Mode

I am currently developing a site using this, and noticed that if I reference the following:

this.$matomo.trackPageView()

I get an error because this.$matomo is not initialized (due to the bail out in module.js). Instead of doing this wouldn't it make sense for the application to just return a dummy proxy that does nothing instead? That way your code is able to run if you reference it without any errors.

Does not track outlink?

Hi & thanks a lot for this great plugin!

It is working great for my nuxt site in general, however, I recently noticed that - at least for my setup - clicks on external links seem not to get tracked
E.g. something like the following:
<a href="https://some.external.domain" target="_blank">Link Text</a>
The same applies to link generate e.g via Vuetify buttons when used as links.

From what I understand Matomo should track those clicks "out of the box", if nothing blocks it from doing so.
See: https://matomo.org/faq/troubleshooting/faq_96/

So, I wonder is this something specific to my setup and should be working or is this a current limitation of the plugin?

Thanks & best regards,
Michael

this.$matomo.setConsent() doesn't remember the consent state

im trying to call .setConsent() after user logs in.

but if the user already loggedin and opened any other page not through the login page the consent is not remembered

is this suppose to happen?

cuz based on my reading of the documentation its said it will be remembered but its not in my case

the only way for it to work if I put it in a layout that is always loaded on each page but I'm not sure if this is the best approach

so any help would be appreciated

thanks

Cookie is set although set to false

Hey here,

I'm on the latest version (1.2.4) and noticed, that the Matomo id cookie (_pk_id.X.XXX) gets set, even though the configuration is set to cookies: false.

The cookie`s payload is empty, therefore I'm pretty sure that cookie-based tracking is correctly disabled. However, from my experience I know that Matomo's plain tracking code doesn't set any cookies when cookies are disabled, which I definitely prefer.

Here's an excerpt of my config:

  ...
  modules: [
    '@nuxtjs/sitemap',
    '@nuxtjs/robots',
    ['nuxt-matomo', { 
      matomoUrl: '//XXXXX/',
      siteId: 1,
      cookies: false,
      debug: false,
    }],
  ],
  ...

Any ideas what could cause that issue?

nuxt-matomo ignores `router.base` variable

I've configured my nuxt setup to live under a subdirectory on the root, by setting

  // router
  router: {
    base: '/subdirectory/'
  },

in the nuxt.config.js.

When using nuxt-matomo it will ignore this setting. So if i'm visiting (for example) http://localhost/subdirectory/page/ nuxt-matomo will send http://localhost/page/ to matomo. The solution that I've come up with is to put the following on all my pages:

  matomo(from, to, store) {
    this.enableHeartBeatTimer(10)
    this.setDoNotTrack()
    this.setCustomUrl(`/subdirectory${to.fullPath}`)
    this.trackPageView()
    return false // return false if you want to manually track here
  }

Is there a better solution for this on my end, or is a fix for nuxt-matomo needed?

[FEAT] Use a config setting to either strip or add trailing slashes

Right now urls with a trailing slash and others without are tracked separately. For example:

/team/about-us/
will not appear in the same entry as
/team/about-us

Matomo support pointed to setCustomUrl, where nuxt-atomo should either verify trailing slashes or strip them, depending on a setting, for example.

In the code of this repo, that would probably have to be added here:

tracker.setCustomUrl(baseUrl + to.fullPath)

Here is also a screenshot with some examples from the matomo dashboard:
image

That would be great to have this feature.
Cheers

How to enable the media tracking

Hi, I'm building a video component in NUXT, which runs fine so far. When I want to enable tracking for the video media usage of the media extension of Matomo (I use the cloud installation), we need to call the function "MediaAnalytics::scanForMedia" as described in the Matomo SDK

Here is my component:

<template>
  <div v-if="video.title">
    <video
      id="player"
      :title="video.title"
      :data-matomo-title="video.title"
      class="cld-video-player cld-video-player-skin-dark"
    >
    </video>
  </div>
</template>

<script>
export default {
  probs: {
    video: {
      type: Object,
      required: true
    }
  },
  mounted() {
    if (this.video.title) {
      const cld = cloudinary.Cloudinary.new({
        cloud_name: '<my-cloudinary-space>',
        secure: true
      })
      const player = cld.videoPlayer('player', {
          "fluid": true,
          "controls": true,
          "hideContextMenu": true,
          "posterOptions": {
              "transformation": {
                  "startOffset": this.video.poster_seconds
              }
          }
      })
      const public_id = this.video.video_id.filename
      const start = public_id.indexOf('/videos/') + 1
      const end = public_id.indexOf('.mp4')
      player.source(public_id.substring(start, end), {
          "info": {
              "title": this.video.title,
              "subtitle": this.video.subtitle
          }
      })
      if (this.$matomo) {
        this.$matomo['MediaAnalytics::scanForMedia']()
      }
    }
  }
}
</script>

When enable debug information for [nuxt-matomo], I got the information:

[nuxt-matomo] Delaying call to tracker: MediaAnalytics::scanForMedia

But never the delayed calling as I would expect:

[nuxt-matomo] Calling tracker MediaAnalytics::scanForMedia with args []

Any ideas, what I'm doing wrong?

matomo() not called for layouts/error.vue

I followed https://nuxtjs.org/guide/async-data#handling-errors and https://nuxtjs.org/guide/views#error-page. In a page component pages/Page.vue I have:

  async asyncData({ route, store, error }) {
    // ...
    error({ statusCode: 404, message: 'Not found' })
  },

And in layouts/error.vue:

  matomo(from, to, store) {
    console.log('Am I ever called?')
    // Source: https://matomo.org/faq/how-to/faq_60/
    this.setDocumentTitle(
      `${this.error.statusCode}/URL = ${encodeURIComponent(to.fullPath)}/From = ${encodeURIComponent(from.path)}`
    )
    this.trackPageView()
    return false
  }

It seems that matomo() is not being called for error.vue. How can I achieve this?

Matomo timeout issue

Hi,
I installed the last version and configure it in nuxt.config.js in modules[] section.
No request is done from matomo when I go on my website.

I enabled the debug mode and I see the following:

[nuxt-matomo] Delaying call to tracker: setDocumentTitle utils.js:3
[nuxt-matomo] Delaying call to tracker: setCustomUrl utils.js:3
[nuxt-matomo] Tell matomo to track pageview / utils.js:3
[nuxt-matomo] Delaying call to tracker: trackPageView
...
[nuxt-matomo] window.Piwik was not set within timeout

Can anyone help me? I have no idea what could lead to this timeout.
Thank you

How to use trackEvent() method?

Hello, I'm able to use nuxt-matomo to track and customize page views, but I'm struggling to figure out how to use matomo's trackEvent() method, specifically when interacting with ui elements on the page--not route changes. Any tips or examples here?

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.