How to track inbound links with Plausible in Nextjs?
Tags: nextjs, react, analytics, privacy
Published: 2022-03-02 10:31:57

Plausible is an excellent privacy-oriented Google alternative. It is easy to set up in Nextjs, but tracking inbound links takes more effort.
 
In this article:

- [Why I choose Plausible?](#why-i-choose-plausible)
- [Set up Plausible in Nextjs](#how-to-set-up-plausible-in-nextjs)
- [Create a custom event in Plausible](#create-a-custom-event-in-plausible)
- [Create a link component that tracks inbound clicks](#create a-link-component-that-tracks-inbound-clicks)
- [Track component clicks](#track-component-clicks)

## Why I choose Plausible?
In my side projects, I take privacy seriously. So, in short, this is how I think about it.
- I want to gather usability feedback in an anonymized way.
- I don't want to collect all user data. 
- Instead, I want to track page visits and button clicks.
- I don't need a complex dashboard for this.
- I don't want to deal with accepting privacy cookies.
- Data collection should be GDPR compliant.
- It should be easy to implement.

Even though Google Analytics is one of the most popular tools, it scores 2.5 / 6 on the list above. In addition to this, the problem with Google is that their business model is not privacy first. To me, it feels like their priorities are elsewhere, so I decided to search for an alternative.

Say hello to [Plausible](https://plausible.io/)! 🤗

> Plausible is lightweight and open source web analytics. No cookies and fully compliant with GDPR, CCPA, and PECR. Made and hosted in the EU, powered by European-owned cloud infrastructure.

Why is Plausible better than Google? 🥊
- Privacy first business model
- Is a simple analytics tool
- Full data ownership
- Open-source (transparent)
- Compliant with GDPR, CCPA, and PERC
- No cookies means no popups
- Better page performance
- Avoids Ad Blocking
- Community-oriented

## How to set up Plausible in Nextjs?
Use [next-plausible](https://www.npmjs.com/package/next-plausible)

```bash
yarn add next-plausible
```

In `_app.js` add:

```jsx
import PlausibleProvider from 'next-plausible'

export default function MyApp({ Component, pageProps }) {
  return (
    <PlausibleProvider domain="yourwebsite.com">
      <Component {...pageProps} />
    </PlausibleProvider>
  )
} 
```

Proxy the analytics script to avoid being blocked by adblockers.

```js
const { withPlausibleProxy } = require('next-plausible')

module.exports = withPlausibleProxy()({
  // ...your next js config, if any
})
```

And "voila," you are done! 

PS: The reason why you have to proxy.

> We're blocked by some blocklist maintainers who have taken the stance that they want to block every tracking script and don't want to have the responsibility to judge what's good and what's bad.

## Create a custom event in Plausible
To start tracking inbound link clicks, you need to create a custom goal in Plausible. 

The custom goals can be configured here:
**plausible.io/[your-domain]/settings/goals**

Or follow this step-by-step instruction:
1. Go to **plausible.io/sites**
2. Hover over your website and click on the gear icon.
3. You should redirect to plausible.io/[your-domain]/settings/general
4. Click on `goals`
5. You should redirect to **plausible.io/[your-domain]/settings/goals**

Next, create a custom goal
1. Click on `+ Add goals` 
2. Click on `Custom Event`
3. Enter event name `Inbound Link: Click`
4. Click `Add goal →`

![Set Custom Goals Plausible](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/8si4otacy5xy8rccfljb.png)

### Create a link component that tracks inbound clicks
Let's wrap `next/link` in a Link component.

```jsx
import NextLink from 'next/link';

const Link = ({ href, children, ...props }) => {
  return (
    <NextLink href={href}>
      <a {...props} onClick={() => plausible('Inbound Link: Click')}>
        {children}
      </a>
    </NextLink>
  );
};

export default Link;
```

Import plausible and send onclick events to Plausible.

```jsx
import NextLink from 'next/link';
import { usePlausible } from 'next-plausible';

const Link = ({ href, children, ...props }) => {
  const plausible = usePlausible();

  return (
    <NextLink href={href}>
      <a {...props} onClick={() => plausible('Inbound Link: Click')}>
        {children}
      </a>
    </NextLink>
  );
};

export default Link;
```

When the user clicks on your Link component below:

```jsx
<Link href="/some-url">
  Some text
</Link>
```

The onclick handler will send your custom `Inbound Link: Click` event to Plausible. If you inspect your goal conversion dashboard, you should see it updated. 🙌

### Track component clicks
As a bonus, let's add extra custom props that we can use to check what components are clicked by the user. You will be able to see a component clicks breakdown under the goal conversion overview.

![Plausible Custom Goal Breakdown](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/56uyhyiwvhlfai16c53p.png)

As you can see in the image above, I have done this for one of my projects nicer.work, where freelancers can [compare freelance websites](https://www.nicer.work). 

Here I have added property `customProps` where I could define custom properties that I would like to send to Plausible.

```jsx
import Link from './Link';

const Header = () => {
  return (
    <Link href="/some-url" customProps={{ component: 'Header' }}>
      Some text
    </Link>
  );
};
```

The `Link` component looks like this:

```jsx
import NextLink from 'next/link';
import { usePlausible } from 'next-plausible';

const Link = ({ href, children, customProps = { component: 'Any' }, ...props }) => {
  const plausible = usePlausible();

  return (
    <NextLink href={href}>
      <a
        {...props}
        onClick={() => {
          plausible('Inbound Link: Click', {
            props: {
              ...customProps
            }
          });
        }}>
        {children}
      </a>
    </NextLink>
  );
};
```

You can always extend the `customProps`, with other properties to extend custom event breakdown.

## Wrap-up
Plausible got my back when it comes to taking care of user privacy. I hope that you will enjoy Plausible as much as I do.