Giter Site home page Giter Site logo

matomo-next's Introduction

Matomo Next

Matomo analytics for Next.js applications

Github Master CI Build Status License: Apache-2.0 GitHub release (latest SemVer) Npm version codecov





  • Basic SPA Matomo setup
  • Will track next/router route changes routeChangeComplete event
  • ⚠️ Notes for Next.js app router

Usage

Add the init call in your _app.js :

import React, { useEffect } from "react";
import App from "next/app";

import { init } from "@socialgouv/matomo-next";

const MATOMO_URL = process.env.NEXT_PUBLIC_MATOMO_URL;
const MATOMO_SITE_ID = process.env.NEXT_PUBLIC_MATOMO_SITE_ID;

function MyApp({ Component, pageProps }) {
  useEffect(() => {
    init({ url: MATOMO_URL, siteId: MATOMO_SITE_ID });
  }, []);

  return <Component {...pageProps} />;
}

export default MyApp;

Will track routes changes by default.

Exclude tracking some routes :

This wont track /login.php or any url containing ?token=.

init({
  url: MATOMO_URL,
  siteId: MATOMO_SITE_ID,
  excludeUrlsPatterns: [/^\/login.php/, /\?token=.+/],
});

Disable cookies :

To disable cookies (for better GDPR compliance) set the disableCookies flag to true.

init({
  url: MATOMO_URL,
  siteId: MATOMO_SITE_ID,
  disableCookies: true,
});

Track additional events :

import { push } from "@socialgouv/matomo-next";

// track some events
push(["trackEvent", "contact", "click phone"]);

Content-Security-Policy

If you use a Content-Security-Policy header with a nonce attribute, you can pass it to the init function to allow the script to be executed.

init({
  url: MATOMO_URL,
  siteId: MATOMO_SITE_ID,
  nonce: "123456789",
})

As the matomo-next injects a matomo script, if you use strict Trusted Types, you need to allow the script tag to be created by adding our policy name to your trusted types directive.

Content-Security-Policy: require-trusted-types-for 'script'; trusted-types matomo-next;

You can set a custom policy name by passing it to the init function.

init({
  url: MATOMO_URL,
  siteId: MATOMO_SITE_ID,
  trustedPolicyName: "your-custom-policy-name",
})

Extensibility

The function has three optional callback properties that allow for custom behavior to be added:

  • onRouteChangeStart(path: string) => void: This callback is triggered when the route is about to change with Next Router event routeChangeStart. It receives the new path as a parameter.

  • onRouteChangeComplete: This callback is triggered when the route change is complete with Next Router event routeChangeComplete. It receives the new path as a parameter.

  • onInitialization: This callback is triggered when the function is first initialized. It does not receive any parameters. It could be useful to use it if you want to add parameter to Matomo when the page is render the first time.

  • onScriptLoadingError: This callback is triggered when the script does not load. It does not receive any parameters. useful to detect ad-blockers.

Tests

init
  ✓ should create a js tag and initialize (7 ms)
  ✓ should NOT create events when url is not provided (9 ms)
push
  ✓ should append data to window._paq (1 ms)
  ✓ should append dimensions data to window._paq (1 ms)
onInitialization
  ✓ should work if the surcharge of the operator (1 ms)
router.routeChangeStart event
  ✓ should setReferrerUrl and setCustomUrl on route change start (1 ms)
  ✓ should use previousPath as referer on consecutive route change (1 ms)
  ✓ should work if the surcharge of the operator (3 ms)
router.routeChangeComplete event
  ✓ should trackPageView with correct title on route change (3 ms)
  ✓ should use previousPath as referer on consecutive route change (2 ms)
  ✓ should track route as search in /recherche (1 ms)
  ✓ should track route as search in /search (2 ms)
  ✓ should work if the surcharge of the operator (2 ms)
excludeUrlsPatterns
  ✓ should excluded login.php and token variables (2 ms)
  ✓ should exclude initial page tracking (3 ms)
  ✓ should track initial page if not excluded (2 ms)
disableCookies
  ✓ should NOT append disableCookies to window._paq by default (1 ms)
  ✓ should append disableCookies to window._paq (1 ms)

matomo-next's People

Contributors

alizadeh-m avatar carolinebda avatar christian1984 avatar douglasduteil avatar jdeniau avatar lsagetlethias avatar maxgfr avatar rap2hpoutre avatar renovate-bot avatar renovate[bot] avatar revolunet avatar socialgroovybot avatar totakoko avatar wackerow 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  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar

matomo-next's Issues

Unique User Visits

Right now we are seeing the same user and session for multiple users with a pretty basic implementation of this package. Is there a way to initialize a new user for unique visits?

How can I add a self-built cookie notice?

I would like to show a cookie banner on the first page visit, and only let Matomo track the user if "Accept" is clicked to comply with GDPR. How can I achieve that?

Setting up Matomo's Tag Manager

I am trying to set up matomo's tag manager. Emitting events and tracking in general was working correctly using the call:

init({ url: MATOMO_URL, siteId});

However, I am unsure as to where I should place the tag manager call. I have tried to add the container's js into the init call (replacing the original one) because the container JS file just extends the matomo.js one as far as I can tell. It does not seem to work.

init({ url: MATOMO_URL, siteId, jsTrackerFile: 'js/container_lXXXXX.js' });

Am I missing something? Do I need to initialize both things? How can I debug this?

New visitor profile is created after call push(["setUserId", userData.email]);

I have an ecommerce platform written in nextjs, and everything seems fine when using it, visitor profile is created as usual. However, after the user is logged in to the website, a new visitor profile is created (different visitor profile ID) and the old visitor profile record is not merge together. The number of visit count is lost.

I didnt set the enable_userid_overwrites_visitorid = 0 config (meaning my current config is set to 1), so everything is in default mode, I enabled archive cronjob and disabled web trigger archive.

Using Matomo-next with ecommerce

Hello,
I am using saleor ecommerce solution which is headless solution. The frontend is build with nextjs and I wonder how this integration could help ?

It seems that you are not targetting ecommerce site but setup a general website ?
If not would it be easier with this package, compared to using <Script>, for custom event ?

  • product click
  • view of a specific product (dynamic page)
  • add to cart
  • checkout
  • ...

Regards,

setGenerationTimeMs and Matomo 4

The method setGenerationTimeMs has been removed in Matomo 4. I get a warning on the console saying: setGenerationTimeMs is no longer supported since Matomo 4. The call will be ignored. There is currently no replacement yet.

Please remove the call to this method or make it configurable. Thanks.

Avoid Total Blocking Time increase

The integration of Matomo into our Next.js site unfortunately increases the Total Blocking Time (TBT) in http://pagespeed.web.dev (mobile) to 300 to 500ms.

We were thinking of two ideas of how to reduce the impact:

  1. Instead of loading matomo.js as a file, integrate its component directly into Next.js as this may avoid redundant code
  2. Reduce the load for the main thread by utilising a web worker as next/script has now (experimental) support for it

Any thoughts on the above?

Update to Next.js 10

It would be great if the library would also work with Next.js 10, which was released a few months ago already. I don't think that the Next.js API has changed very much so updating the peerDependencies in the package.json is probably enough.

Duplicate Page View Tracking in SPA

Hello,

I am currently working on a Single Page Application (SPA) and facing an issue with tracking query strings during page navigation. My goal is to accurately track page views, including the full URL with query strings, whenever the user navigates from one page to another.

I have implemented the following code in my _app file to integrate Matomo tracking:

I've added this in my _app :

const appConfig = useAppConfig()
  useEffect(() => {
    if (appConfig?.matomoUrl && appConfig?.matomoSiteId) {
      init({
        url: appConfig?.matomoUrl,
        siteId: appConfig?.matomoSiteId,
        onRouteChangeComplete: (path) => {
          const fullUrl = window.location.origin + path
          window._paq.push(['setCustomUrl', fullUrl])
          window._paq.push(['trackPageView'])
        },
      })
    }
  }, [appConfig?.matomoUrl, appConfig?.matomoSiteId])

This setup successfully tracks the full URL, including query strings, as intended. However, I have encountered an issue where each page view is being tracked twice.

I am reaching out to see what adjustments in my setup I need to do to ensure that page views are only tracked once per navigation event.

Thank you.

The method enableLinkTracking is registered more than once

instrument.js:110 The method enableLinkTracking is registered more than once in "_paq" variable. Only the last call has an effect. Please have a look at the multiple Piwik trackers documentation

Thanks for matomo-next we're utilizing in production.

Can obviously see this warning thrown in the console is due to two instances of push(["enableLinkTracking"]); here and above - should this error be a no-op?

Reading matomo's error explanation article - we're not looking to record the 2nd log (it's the same in our case here)

How to Tag Manager ?

I don't see anything to implement Tag Manager with matomo-next. Thank you for your help.

workbox caching

When using a workbox for PWA production, a full request is added to the app cache which creates extensive memory usage.

https://mw-pwa-58440ydcn.vercel.app/ (Version with Matomo-next)
Go to dev tools Application Clear Storage and hit update a few times. The cache will be increasing with every hit, my application reached 1gb in the cache usage while the full app size is 50 MB

https://mw-pwa-4vle6e6j6.vercel.app/ (Version without Matomo-next)
Go to dev tools Application Clear Storage and hit update a few times. As soon as the app fully cached (26 MB or so), it will not increase with reloading

image

Adding a callback to know when the script can't load

Hey 👋

I would like to know when the Matomo script cannot be loaded and may be ad-blocked.
My use case is that I do AB tests using the Matomo plugin and I need to detect when to use a fallback if the script does not load.
Of course I don't want to run a setTimeout manually and would like to rely on events instead. 😁
I already use the matomoAbTestingAsyncInit callback to know when I can use Matomo but I have nothing yet to be notified when It was blocked.

I did a POC by adding an onerror listener on the scriptElement to be inserted. It seems to be working as I expect. May I open a PR?

Dependency Dashboard

This issue lists Renovate updates and detected dependencies. Read the Dependency Dashboard docs to learn more.

Open

These updates have all been created already. Click a checkbox below to force a retry/rebase of any.

Detected dependencies

github-actions
.github/workflows/ci.yml
  • actions/checkout v4
  • actions/setup-node v4
  • codecov/codecov-action v3
  • actions/upload-artifact v1
  • actions/setup-node v4
  • actions/checkout v4
  • actions/download-artifact v1
  • cycjimmy/semantic-release-action v3
npm
package.json
  • @socialgouv/eslint-config-react 1.131.0
  • @socialgouv/eslint-config-typescript ^1.97.3
  • @types/jest 26.0.24
  • @types/trusted-types ^2.0.4
  • eslint 7.32.0
  • eslint-config-prettier ^9.1.0
  • eslint-config-typescript ^3.0.0
  • jest 26.6.3
  • next 11.1.3
  • prettier 3.1.1
  • react 16.14.0
  • react-dom 16.14.0
  • ts-jest 26.5.6
  • typescript 3.9.10
  • next >= 9.5.5

  • Check this box to trigger a request for Renovate to run again on this repository

Missing repo license

Hi!

I'm looking to rely on and contribute to this project but the lack of a proper license makes this hard. Could you add license so that we know how we can use the code?

Run on localhost

Maybe not really an issue but I want to run this locally to test the Matomo intergration, but I can't get passed the setup of the tracking code within Matamo.

Some context:
I've Matomo running locally with docker on port 8080, and my nextJs frontend on port 3000,
I've picked the "install with JavaScript code" option in matamo, is this the correct one for this NextJs intergration or should I do this differently?

Since when i press the button "Test Installation" this will fail, the correct page (localhost:3000) will open and close after 10 second but Matomo gives an error.

Allow setting custom data-attributes for script-tag

Hi,

some cookie-managment tools like f.e. cookiefirst.com require you to setup a data-attribute so the script only gets loaded when cookies have been accepted, f.e. <script type="text/plain" data-cookiefirst-category="advertising">Your script here</script>.

Would be nice to have to option to add custom data-attributes.

Regards

The automated release is failing 🚨

🚨 The automated release from the master branch failed. 🚨

I recommend you give this issue a high priority, so other packages depending on you could benefit from your bug fixes and new features.

You can find below the list of errors reported by semantic-release. Each one of them has to be resolved in order to automatically publish your package. I’m sure you can resolve this 💪.

Errors are usually caused by a misconfiguration or an authentication problem. With each error reported below you will find explanation and guidance to help you to resolve it.

Once all the errors are resolved, semantic-release will release your package the next time you push a commit to the master branch. You can also manually restart the failed CI job that runs semantic-release.

If you are not sure how to resolve this, here is some links that can help you:

If those don’t help, or if this issue is reporting something you think isn’t right, you can always ask the humans behind semantic-release.


No npm token specified.

An npm token must be created and set in the NPM_TOKEN environment variable on your CI environment.

Please make sure to create an npm token and to set it in the NPM_TOKEN environment variable on your CI environment. The token must allow to publish to the registry https://registry.npmjs.org/.


Good luck with your project ✨

Your semantic-release bot 📦🚀

Feature: Pass additional parameters on init

It might be nice to have one more optional init param to take an array of push() parameters that's injected into the initialization script. This would be helpful where matomo configs call for additional settings outside the defaults (eg, setting cookie policy for subdomains).

I imagine something along the lines of ...

init(
    ...,
    additionalPushParameters: [
        ['foo', 'bar'],
        ['baz', 'boop']
    ]
);

...to build:

<!-- Matomo config -->
...
push(['foo', 'bar']);
push(['barz', 'boop']);
...
<!-- end Matomo config -->

Custom events

Hi all

Possible to send some custom events? i.E. if we use a Commerce or WebVitals?

Thank you for helping

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.