DEV Community

Marvin
Marvin

Posted on • Originally published at marvinschopf.com

How to integrate Plausible into a Next.js project

Plausible is a new and privacy-friendly analytics service that is an attractive alternative to Google Analytics. It only stores data that enables a simple analysis of visits to your website. In doing so, Plausible does not track the user across multiple websites (does not store cross-site cookies).

In this article, I assume that you already have a functioning Next.js project running.

Installation

To include plausible in Next, we use the package next-plausible.

So we install this first. Either with yarn:

yarn add next-plausible
Enter fullscreen mode Exit fullscreen mode

Or using npm:

npm install next-plausible
Enter fullscreen mode Exit fullscreen mode

Add Plausible to _app.js

Next, we extend the _pages/app.js file (please read this article first if you do not already have this file).

We wrap the existing _app.js code with the PlausibleProvider, which embeds the analysis script and makes it available to the rest of your project.

Our code should now look like this:

import "../styles/globals.css";
import PlausibleProvider from "next-plausible";

function MyApp({ Component, pageProps }) {
  return (
    <PlausibleProvider domain="YOUR-DOMAIN-HERE">
      <Component {...pageProps} />
    </PlausibleProvider>
  );
}

export default MyApp;
Enter fullscreen mode Exit fullscreen mode

Please replace YOUR-DOMAIN-HERE in the domain parameter with the domain of your application.

Done! The visits to your application are now tracked by Plausible.

Tracking goals

Goals can also be tracked with next-plausible, for which a hook is provided. This can be used as follows:

import { usePlausible } from "next-plausible";

export default function Home() {
  const plausible = usePlausible();

  return (
    <div>
      <button onClick={() => plausible("Button")}>Button</button>
    </div>
  );
}
Enter fullscreen mode Exit fullscreen mode

As soon as the button is pressed, an event is tracked at Plausible.

That's it! Your Next.js application now tracks statistics and also goals with Plausible.

Conclusion

Plausible is a great alternative to Google Analytics, which actually respects user privacy and only tracks what is necessary to provide you with simple analyses of user behaviour on your website. With next-plausible there is also a great solution to use Plausible with Next.js.

You can learn more about next-plausible in the related docs.

Top comments (0)