SocialGouv / matomo-next

Matomo for Next.js applications
Apache License 2.0
155 stars 22 forks source link

Documentation for next.js 13 app directory? #112

Open philippkeller opened 1 year ago

philippkeller commented 1 year ago

The docs only cover the pages directory (using _app.jsx). I want to use it with the new app directory, but I'm lost.

The best I could find was this howto which covers PostHog.

Could anyone help out here?

eivindml commented 1 year ago

@philippkeller Did you figure this out?

julian-leahy commented 11 months ago

Also looking for this solution

revolunet commented 11 months ago

does this issue help ? https://github.com/SocialGouv/matomo-next/issues/104

This one also https://github.com/SocialGouv/matomo-next/issues/99

rihards-simanovics commented 11 months ago

need a solution as well 😕

philippkeller commented 10 months ago

@revolunet yes the code snippet in #104 looks good - where do I add it though? into src/app/layout.jsx ?

philippkeller commented 10 months ago

I got something working, but it's probably far from perfect:

In layout.jsx:

import Matomo from '@/utils/matomo'

then, above the tag add <Matomo />

In /utils.matomo.js:

import Script from "next/script";

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

export default function Matomo() {
    return (
        <Script
            id="matomo"
            strategy="afterInteractive"
            dangerouslySetInnerHTML={{
                __html: `
                var _paq = window._paq = window._paq || [];
  /* tracker methods like "setCustomDimension" should be called before "trackPageView" */
  _paq.push(['trackPageView']);
  _paq.push(['enableLinkTracking']);
  (function() {
    var u="//${MATOMO_URL}/";
    _paq.push(['setTrackerUrl', u+'matomo.php']);
    _paq.push(['setSiteId', '${MATOMO_SITE_ID}']);
    var d=document, g=d.createElement('script'), s=d.getElementsByTagName('script')[0];
    g.async=true; g.src=u+'matomo.js'; s.parentNode.insertBefore(g,s);
  })();
            `,
            }}
        />
    )
}

And in your .env file:

NEXT_PUBLIC_MATOMO_URL=matomo.mydomain.com
NEXT_PUBLIC_MATOMO_SITE_ID=1
wscourge commented 9 months ago

@philippkeller FYI you don't need dangerouslySetInnerHTML={{ __html: ""}} syntax to use the next/script tag.

<Script id="matomo" strategy="afterInteractive">
{`
    var _paq = window._paq = window._paq || [];
    /* tracker methods like "setCustomDimension" should be called before "trackPageView" */
    _paq.push(['trackPageView']);
    _paq.push(['enableLinkTracking']);
    (function() {
    var u="//${MATOMO_URL}/";
    _paq.push(['setTrackerUrl', u+'matomo.php']);
    _paq.push(['setSiteId', '${MATOMO_SITE_ID}']);
    var d=document, g=d.createElement('script'), s=d.getElementsByTagName('script')[0];
    g.async=true; g.src=u+'matomo.js'; s.parentNode.insertBefore(g,s);
    })();
`}
</Script>

Reference