Blog>
Snippets

Integrate Plausible Analytics without External Scripts

Integrate Plausible Analytics into a Next.js 14 app without using external scripts by using the Image component to ping the analytics server.
import { useEffect } from 'react';
import Image from 'next/image';

export default function PlausibleTracking({ domain, pathname }) {
  useEffect(() => {
    // Construct the URL for the tracking image
    const plausibleTrackingUrl = `https://plausible.io/api/event`;
    // Create the query parameters
    const params = new URLSearchParams({
      domain,
      url: document.location.href,
      referrer: document.referrer || '',
      screen_width: window.innerWidth,
      user_agent: navigator.userAgent
    });

    // Function to handle visibility change
    const onVisibilityChange = () => {
      if (document.visibilityState === 'visible') {
        // Send a 'pageview' event if the page becomes visible
        fetch(`${plausibleTrackingUrl}?${params}`, {
          method: 'POST',
          headers: { 'Content-Type': 'image/png' }
        });
      }
    };

    // Attach the handler to the visibility change event
    document.addEventListener('visibilitychange', onVisibilityChange);

    return () => {
      // Clean up the event listener when the component unmounts
      document.removeEventListener('visibilitychange', onVisibilityChange);
    };
  }, [domain, pathname]);

  return (
    <Image
      src={`https://plausible.io/api/event?${params.toString()}`}
      width="1"
      height="1"
      alt=""
    />
  );
}
This React component for Next.js uses the built-in Image component and the useEffect hook to integrate Plausible Analytics without using external scripts. It constructs a tracking pixel URL with relevant analytics parameters and hooks into the document's visibility change event to only send a pageview event when the page becomes visible, mimicking the behavior of Plausible's standard tracking script.