Plausible is a lightweight, open-source web analytics tool designed as a privacy-friendly alternative to Google Analytics. Unlike traditional tracking solutions, Plausible doesn’t use cookies or collect personally identifiable information, making it fully compliant with GDPR, CCPA, and other privacy regulations.

For developers looking to integrate analytics seamlessly into their projects, Plausible offers an npm module that allows for easy installation and setup within JavaScript-based applications. In this guide, we’ll walk you through the process of installing and configuring Plausible as an npm module, helping you gain valuable insights while respecting user privacy.

geometric shape digital wallpaper
Photo by fabio / Unsplash

Step 1: Plausible tracker implementation

Start by creating a new file called plausible.ts inside lib directory as follow and make sure you are entering your production domain.

import Plausible from 'plausible-tracker';

// Initialize Plausible with your domain
export const plausible = Plausible({
  domain: 'yourdomain.com',
  trackLocalhost: process.env.NODE_ENV === 'development', // Only track localhost in development
  apiHost: 'https://plausible.io'
});

// Get the functions we need
export const { trackEvent, trackPageview, enableAutoPageviews, enableAutoOutboundTracking } = plausible;

// Export a function to enable both auto page views and outbound tracking
export const enablePlausibleTracking = () => {
  // Set up automatic page view tracking
  const cleanupPageviews = enableAutoPageviews();
  
  // Set up automatic outbound link click tracking
  const cleanupOutbound = enableAutoOutboundTracking();
  
  // Return a cleanup function that will clean up both
  return () => {
    cleanupPageviews();
    cleanupOutbound();
  };
};

export default plausible; 

Step 2: Create the PlausibleTracking component

Then, a new component is needed to actually implement the tracker and it will initialized plausible analytics.

'use client';

import { useEffect } from 'react';
import { enablePlausibleTracking } from '@/lib/plausible';

export default function PlausibleTracking() {
  useEffect(() => {
    // Initialize tracking and get the cleanup function
    const cleanup = enablePlausibleTracking();
    
    // Log initialization in development
    if (process.env.NODE_ENV === 'development') {
      console.log('✅ Plausible analytics initialized');
    }
    
    // Clean up event listeners when the component unmounts
    return cleanup;
  }, []);

  // This component doesn't render anything
  return null;
} 

Step 3: Create the ExampleTracking component to use trackEvent

This part is important in order to use trackEvent with Plausible and test that everything is working as expected.

"use client";

import { Button } from '@mui/material';
import { trackEvent } from '@/lib/plausible';

export default function ExampleTracking() {
  const handleButtonClick = () => {
    // Track a custom event when button is clicked
    trackEvent('Button Click', { 
      props: {
        buttonName: 'Example Button',
        location: 'ExampleTracking Component'
      }
    });
    
    // Actual functionality here
    console.log('Button clicked and tracked!');
  };
  
  return (
    <div>
      <h2>Example Analytics Tracking</h2>
      <Button 
        variant="contained" 
        color="primary" 
        onClick={handleButtonClick}
      >
        Click to Track
      </Button>
      <p>When you click this button, a custom event will be sent to Plausible Analytics.</p>
    </div>
  );
} 

Step 4: Create a simple test page to verify the integration

Then, it will be important to update the page.tsx with a test page to verify the integration.

'use client';

import { useEffect } from 'react';
import { trackEvent, trackPageview } from '@/lib/plausible';
import { Button, Box, Typography, Container, Paper, Link } from '@mui/material';
import ExampleTracking from '@/components/ExampleTracking';

export default function PlausibleTestPage() {
  useEffect(() => {
    // Force a manual page view (in addition to automatic tracking)
    trackPageview({
      url: window.location.href,
      referrer: document.referrer
    });
    
    console.log('✅ Manual page view tracked for testing');
  }, []);
  
  const handleManualEvent = () => {
    trackEvent('Manual Test Event', {
      props: {
        testId: '123',
        testTime: new Date().toISOString()
      }
    });
    console.log('✅ Manual test event tracked');
  };
  
  return (
    <Container maxWidth="md" sx={{ py: 4 }}>
      <Paper elevation={3} sx={{ p: 4 }}>
        <Typography variant="h4" component="h1" gutterBottom>
          Plausible Analytics Test Page
        </Typography>
        
        <Typography paragraph>
          This page is designed to test if Plausible Analytics is working correctly.
          Check your browser's network tab for requests to "plausible.io".
        </Typography>
        
        <Box sx={{ my: 3 }}>
          <Typography variant="h6" gutterBottom>Manual Test</Typography>
          <Button 
            variant="contained" 
            color="primary"
            onClick={handleManualEvent}
            sx={{ mr: 2 }}
          >
            Track Manual Event
          </Button>
        </Box>
        
        <Box sx={{ my: 3 }}>
          <Typography variant="h6" gutterBottom>Component Test</Typography>
          <ExampleTracking />
        </Box>
        
        <Box sx={{ my: 3 }}>
          <Typography variant="h6" gutterBottom>Outbound Link Test</Typography>
          <Link href="https://plausible.io" target="_blank" rel="noopener">
            Visit Plausible (This should track as an outbound link)
          </Link>
        </Box>
        
        <Box sx={{ mt: 4, p: 2, bgcolor: 'background.paper' }}>
          <Typography variant="body2" color="text.secondary">
            Check your Plausible dashboard at <Link href="https://plausible.io/mediagear.ca" target="_blank">https://plausible.io/mediagear.ca</Link>
          </Typography>
        </Box>
      </Paper>
    </Container>
  );
}

Plausible Integration Guide is now complete📊

For more technical details you can visit https://www.npmjs.com/package/plausible-tracker

Share this post