Install analytics
and @analytics/mixpanel
with
npm install analytics @analytics/mixpanel
# Mixpanel project token (https://eu.mixpanel.com/project)
NEXT_PUBLIC_MIXPANEL_PROJECT_TOKEN=<your-mixpanel-token>
# Cookiebot id (https://admin.cookiebot.com/)
NEXT_PUBLIC_COOKIEBOT_ID=<your-cookiebot-token>
Also create a .env.example
file with the above tokens without the token and ensure that .env is not tracked - double check at next commit. This is useful for a fresh cloned repository.
If your using Netlify head to your config https://app.netlify.com/sites/<your-site>/configuration/env
and add the tokens, so they're available at the next deploy.
In your layout.tsx
or providers.tsx
(if you're using a provider component). Add the Hook and render the Consent script.
// ...other imports ...
import { useAnalytics } from '../utils/analytics' // see code from the Gist
export default function RootLayout({children}:{children: React.ReactNode}) {
const { ConsentComponent } = useAnalytics();
return (
<html>
<body>
<div>
{ /* ... other components ... */ }
{children}
</div>
<ConsentComponent />
</body>
</html>
)
}
UseAnalytics
is also returning analytics
object that could be used to pass to AppContext and used in your components.
Omitted in the example.
Docs for analytics
api can be found here.
Without it the global window.Cookiebot
was undefined as the script run before the cookiebot script is loaded. With the onload
it is delaying the consent check until the Cookiebot
global is available and the check is working as expected.
Go to https://admin.cookiebot.com/domain-groups/
and add your production domain. e.g. ydecide.app
I haven't tested to add localhost and also wildcards are unfortunately not supported.
- On first load you should see the consent modal
- Consent everything and open network tab of your browser - look for xhr requests with track for Mixpanel tracking
- Disable consent & reload page
Very first page is not tracked because the consent mechanism is only working on page load.
Could be improved by adding an event listener CookiebotOnAccept
with window.addEventListener('CookiebotOnAccept', function (e) {})
.
This would also require to add useState
for the consent
state.
Maybe I'll add this later.
Hi. I'm wondering how this exactly worked for you, since there does not seem to be any types for the
@analytics/mixpanel
package.