Plausible Tracker

repository·master·Indexed 42 days ago

https://github.com/plausible/plausible-tracker

A lightweight (<1kb) frontend library for interacting with Plausible Analytics. It provides an NPM-based alternative to the official Plausible script, supporting SPAs, custom events, and automatic outbound link tracking. Key features include trackPageview(), trackEvent(), enableAutoPageviews(), and enableAutoOutboundTracking().

Tokens
3.3K
Snippets
13
Records
16
Agent score
54%

What's inside Plausible Tracker

  1. Exclude yourself from analytics via localStorage

    master

    Because the tracker is bundled with your application code, standard ad-blockers may not prevent your own visits from being tracked. To opt out, set the following key in your browser's localStorage:

    localStorage.plausible_ignore = "true"

    When this is set, the tracker will not send any events.

  2. Enable automatic page view tracking for SPAs

    master

    For Single Page Applications (SPAs) using JS-based routing, enableAutoPageviews() automatically tracks page views by overriding history.pushState and listening to popstate and hashchange events.

    Hash-based Routing

    If your app uses URL hashes for navigation, initialize the tracker with hashMode: true before calling enableAutoPageviews().

    Cleaning up

    enableAutoPageviews() returns a cleanup function. Call this function to remove event listeners and restore the original history.pushState behavior.

    import Plausible from 'plausible-tracker'
    
    const { enableAutoPageviews } = Plausible({
      hashMode: true
    })
    
    // Starts tracking current and future page views
    const cleanup = enableAutoPageviews()
    
    // Later, to stop tracking and restore history behavior:
    cleanup()
  3. Initialize the Plausible tracker

    master

    To start tracking, call the Plausible() function with a configuration object. This returns an object containing tracking methods like trackPageview, trackEvent, and enableAutoPageviews.

    Initialization Options

    OptionTypeDescriptionDefault
    domainstringYour site's domain, as declared in Plausible's settingslocation.hostname
    hashModeboolEnables tracking based on URL hash changesfalse
    trackLocalhostboolEnables tracking on localhostfalse
    apiHoststringPlausible's API host (change if self-hosting)'https://plausible.io'
    import Plausible from 'plausible-tracker'
    
    const plausible = Plausible({
      domain: 'my-app.com'
    })
  4. Track outbound link clicks automatically

    master

    The enableAutoOutboundTracking() function adds a click event listener to all <a> tags and uses a MutationObserver to ensure dynamically added links are also tracked.

    Cleaning up

    enableAutoOutboundTracking() returns a cleanup function. Call it to remove the click listeners and disconnect the MutationObserver.

    import Plausible from 'plausible-tracker'
    
    const { enableAutoOutboundTracking } = Plausible()
    
    // Start tracking all existing and future outbound links
    const cleanup = enableAutoOutboundTracking()
    
    // Later, to stop tracking:
    cleanup()
  5. Track custom events and goals with trackEvent()

    master

    Use trackEvent(name, eventOptions, overrideOptions) to track custom user actions or goals.

    • name: The name of the goal or event (string).
    • eventOptions: An object containing props (custom properties) and a callback function.
    • overrideOptions: An object containing the same configuration options used during initialization (e.g., trackLocalhost, domain).
    import Plausible from 'plausible-tracker'
    
    const { trackEvent } = Plausible()
    
    // Track a simple goal
    trackEvent('signup')
    
    // Track a goal with custom properties
    trackEvent('download', { props: { method: 'HTTP' } })
    
    // Track a goal with properties, a callback, and initialization overrides
    trackEvent(
      'signup',
      {
        callback: () => console.log('done'),
        props: { variation: 'button A' }
      },
      { trackLocalhost: true }
    )
  6. Track page views with trackPageview()

    master

    Use trackPageview() to manually record a single page view. You can override the global initialization settings by passing an options object as the first parameter, and provide event options (like a callback) as the second parameter.

    Override Options (First Parameter)

    OptionTypeDescriptionDefault
    urlstringCurrent page's URLlocation.href
    referrerstring or nullReferrer's addressdocument.referrer
    deviceWidthnumberUser's device width for device trackingwindow.innerWidth

    Note: You can also pass the same initialization options (like trackLocalhost) to the override object.

    import Plausible from 'plausible-tracker'
    
    const { trackPageview } = Plausible()
    
    // Basic usage
    trackPageview()
    
    // Usage with overrides and callbacks
    trackPageview(
      {
        url: "https://my-app.com/my-url"
      },
      { callback: () => console.log("Done!") }
    )
  7. Initialize the Plausible tracker with Plausible()

    master

    The Plausible class is the main entrypoint for the tracker. You initialize it by importing the default export and providing a configuration object that satisfies the PlausibleOptions type. This instance is then used to track page views and custom events.

    import Plausible from 'plausible-tracker';
    
    const tracker = new Plausible({
      domain: 'yourdomain.com',
      apiHost: 'https://plausible.io'
    });
  8. Track custom events with trackEvent()

    master

    Use trackEvent to track custom goals or user actions. You can pass a name for the event, optional event properties (via EventOptions), and optional event data (via PlausibleOptions).

    Parameters:

    • eventName: The name of the event (e.g., 'signup').
    • options: (Optional) EventOptions for the request.
    • eventData: (Optional) PlausibleOptions to override default metadata like url or domain.
    import Plausible from 'plausible-tracker'
    
    const { trackEvent } = Plausible()
    
    // Tracks the 'signup' goal
    trackEvent('signup')
    
    // Tracks the 'Download' goal passing a 'method' property.
    trackEvent('Download', { props: { method: 'HTTP' } })
  9. Send custom events with sendEvent()

    master

    Use the sendEvent function to manually trigger an event to the Plausible API. This function requires the event name, a PlausibleOptions object containing core tracking data, and an optional EventOptions object for additional metadata.

    Important Behaviors:

    • Localhost Protection: By default, events are ignored if the website is running on localhost or 127.0.0.1 unless trackLocalhost is set to true in your PlausibleOptions.
    • Opt-out Check: The function checks localStorage.plausible_ignore. If this is set to 'true', the event will be ignored.
    • Payload Construction: The function automatically maps your options to the internal Plausible payload format, including device width and hash mode status.
    import { sendEvent } from './plausible-tracker'; // Adjust import path as needed
    
    // Example usage
    sendEvent(
      'button_click',
      {
        url: window.location.href,
        domain: 'example.com',
        apiHost: 'https://plausible.io',
        trackLocalhost: true, // Required if testing on localhost
        // ... other required PlausibleOptions
      },
      {
        props: {
          button_color: 'blue',
          user_tier: 'premium'
        },
        callback: (args) => {
          console.log('Event sent with status:', args.status);
        }
      }
    );
  10. Enable automatic outbound link tracking

    master

    Call enableAutoOutboundTracking() to automatically detect and track clicks on outbound links (links where the host differs from the current location). It uses a MutationObserver to watch for new links added to the DOM.

    Parameters:

    • targetNode: (Optional) The node to observe. Defaults to document.
    • observerInit: (Optional) Configuration for the MutationObserver (e.g., subtree, childList).

    Cleanup: enableAutoOutboundTracking() returns a cleanup function. Calling this will disconnect the observer and remove all attached click listeners from tracked links.

    import Plausible from 'plausible-tracker'
    
    const { enableAutoOutboundTracking } = Plausible()
    
    // This tracks all the existing and future outbound links on your page.
    enableAutoOutboundTracking()
    
    const cleanup = enableAutoOutboundTracking()
    
    // Remove event listeners and disconnect the observer
    cleanup()
  11. Manually track page views with trackPageview()

    master

    Use trackPageview to manually record a page view. This is useful for single-page applications (SPAs) where you want to trigger a pageview event on specific route changes without using the automatic mode.

    import Plausible from 'plausible-tracker'
    
    const { trackPageview } = Plausible()
    
    // Track a page view
    trackPageview()