Analytics

Guide: Analytics

In this tutorial we will cover 2 analytics providers:

  • Plausible
  • Google Analytics

Plausible

Plausible is a lightweight and open-source web analytics tool. It has a 30 days free trial and then it's $9/month. It's a great alternative to Google because it's RGPD compliant and doesn't use cookies.

  • Go to Plausible and create an account.
  • Create a new Website and add your domain name.
  • Then inside app/layout.tsx, add the Plausible script:
    app/layout.tsx
    import Script from 'next/script';
    //...
    <html lang="en" data-theme="dark">
      <Script
        async
        defer
        // If you want to track local dev env, replace script src with `https://plausible.io/js/script.local.js`
        src='https://plausible.io/js/script.js'
        data-domain='yourdomain.com'
      />
      <body className={outfit.className}>
        {children}
      </body>
    </html>
  • (recommended) It is likely that plausible events will be blocked by adblockers when deployed to production. To avoid this, you can use NextJS redirects feature.
    next.config.ts
    rewrites: async () => [
      {
        source: '/js/script.local.js',
        destination: 'https://plausible.io/js/script.local.js',
      },
      {
        source: '/api/event',
        destination: 'https://plausible.io/api/event',
      },
    ],
    And replace plausible source script with /js/script.local.js
  • That's it! You can now go to your Plausible dashboard and see your stats instantly.

If you want a more advanced integration see this repo

Google Analytics

Google Analytics is a free analytics tool from Google. It's the most popular analytics tool but it's not RGPD compliant and it uses cookies.

  • Go to Google Analytics and create an account.
  • Then you need to setup a new property. Fill the requried details and choose Web platform at the end.
  • Set up a data stream by entering your website url and giving a name to the stream.
  • Copy your measurement ID and add the following scripts to app/layout.tsx.
    app/layout.tsx
    import Script from 'next/script';
    //...
    <html lang="en" data-theme="dark">
      <Script
        strategy="afterInteractive"
        src="https://www.googletagmanager.com/gtag/js?id=G-XXXXXXXXXX"
      />
      <Script
        id="ga-script"
        dangerouslySetInnerHTML={{
          __html: `
            window.dataLayer = window.dataLayer || [];
            function gtag(){dataLayer.push(arguments);}
            gtag('js', new Date());
     
            gtag('config', 'G-XXXXXXXXXX', {
              page_path: window.location.pathname,
            });
          `,
        }}
      />
      <body className={outfit.className}>
        {children}
      </body>
    </html>
  • You should start seeing data in your Google Analytics dashboard under the Reports > Realtime section
NextTutorial: Dark mode