next-plausible

repository·master·Indexed 20 days ago

https://github.com/4lejandrito/next-plausible

A simple integration for adding Plausible analytics to Next.js applications. It provides the PlausibleProvider component for script injection, the usePlausible hook for custom event tracking, and withPlausibleProxy for proxying the analytics script through a custom domain to bypass adblockers. Supports both Pages and App Router.

Tokens
2.9K
Snippets
11
Records
13
Agent score
72%

What's inside next-plausible

  1. Include the Analytics Script with PlausibleProvider

    master

    To enable Plausible analytics, wrap your application (or specific pages) with the <PlausibleProvider /> component. You must provide the src prop with your site-specific script URL from the Plausible dashboard (e.g., https://plausible.io/js/pa-XXXXX.js).

    Usage in Pages Router (_app.js): Wrap the top-level component to enable analytics globally.

    Usage in App Router (layout.js): Wrap the children inside the root layout.

    Single Page Usage: Wrap only the specific page component where analytics are desired.

    // pages/_app.js
    import PlausibleProvider from 'next-plausible'
    
    export default function MyApp({ Component, pageProps }) {
      return (
        <PlausibleProvider src="https://plausible.io/js/pa-XXXXX.js">
          <Component {...pageProps} />
        </PlausibleProvider>
      )
    }
  2. Migrate withPlausibleProxy from v3 to v4

    master

    The withPlausibleProxy configuration in v4 requires the src property and uses different naming for path customization.

    Key Changes

    • src is now required: You must pass the same script URL used in PlausibleProvider to the proxy configuration.
    • customDomain is removed: Pass the custom domain's script URL directly to src.
    • Path Customization: subdirectory and scriptName are replaced by scriptPath and apiPath. These set the full local paths directly. Defaults are /js/script.js and /api/event.
    • Automatic Injection: When using the proxy, PlausibleProvider requires no props as src is injected automatically.
    // next.config.js
    const { withPlausibleProxy } = require('next-plausible')
    
    module.exports = withPlausibleProxy({
      src: 'https://plausible.io/js/pa-XXXXX.js',
      scriptPath: '/proxy/myscript.js',
      apiPath: '/proxy/api/event',
    })({ /* ...next config */ })
  3. Proxy the Analytics Script to avoid adblockers

    master

    To prevent adblockers from blocking Plausible, you can proxy the script through your own domain using withPlausibleProxy in next.config.js. This sets up necessary rewrites and configures PlausibleProvider to use local proxy URLs automatically.

    Requirements:

    • You must serve your site using next start. Static sites cannot perform these rewrites.
    • When using the proxy, the src prop is not required on <PlausibleProvider />.
    • If self-hosting Plausible, use your instance URL as src.

    Customizing Paths: You can override the default local paths for the proxied script (/js/script.js) and API endpoint (/api/event) using scriptPath and apiPath.

    const { withPlausibleProxy } = require('next-plausible')
    
    module.exports = withPlausibleProxy({
      src: 'https://plausible.io/js/pa-XXXXX.js',
      scriptPath: '/yourpath/script.js',
      apiPath: '/yourpath/api/event',
    })({
      // ...your next js config
    })
  4. Migrate PlausibleProvider from v3 to v4

    master

    When upgrading to v4, the PlausibleProvider API changes significantly to accommodate the Plausible v2 script. The primary change is moving from a domain based configuration to a src based configuration using the full script URL.

    Key Prop Changes

    • domainsrc: Replace domain="example.com" with src="https://plausible.io/js/pa-XXXXX.js". You can find this URL in your Plausible dashboard.
    • customDomain and selfHosted are removed: Instead of using these flags, pass the full script URL (from your custom domain or self-hosted instance) directly to the src prop.
    • Feature Flags → init object: Boolean props like trackLocalhost, manualPageviews, and hash are now moved into an init configuration object.
    • pageviewPropsinit.customProperties: Custom pageview properties are now passed via init.customProperties.
    • Automatic Features: trackOutboundLinks, taggedEvents, and revenue are now bundled in the v2 script and no longer require props.
    • exclude is removed: Page exclusion must now be configured in the Plausible dashboard rather than via props.
    <PlausibleProvider
      src="https://plausible.io/js/pa-XXXXX.js"
      init={{
        captureOnLocalhost: true,
        autoCapturePageviews: false,
        hashBasedRouting: true,
        fileDownloads: { fileExtensions: ['pdf', 'zip'] },
        customProperties: { author: 'Alice' },
      }}
    >
      {/* children */}
    </PlausibleProvider>
  5. Strip cookies from proxied API requests

    master

    When proxying, tracking requests are made to the same domain, meaning cookies are forwarded. If this is an issue, you can use Next.js middleware to strip cookies from requests targeting the proxy API endpoint.

    Example Middleware Implementation:

    import { NextResponse } from 'next/server'
    
    export function middleware(request) {
      const requestHeaders = new Headers(request.headers)
      requestHeaders.set('cookie', '')
      return NextResponse.next({
        request: {
          headers: requestHeaders,
        },
      })
    }
    
    export const config = {
      matcher: '/proxy/api/event',
    }
  6. Send Custom Events with usePlausible

    master

    Use the usePlausible hook to access the plausible function for sending custom events and goals.

    Basic Usage: Call plausible('eventName') to trigger an event.

    With Properties: Pass an object with a props key to include metadata: plausible('eventName', { props: { key: 'value' } }).

    TypeScript Support: You can provide a type definition to usePlausible<T>() to ensure only valid events and properties are sent.

    import { usePlausible } from 'next-plausible'
    
    type MyEvents = {
      event1: { prop1: string }
      event2: { prop3: string }
      event3: never
    }
    
    export default function PlausibleButton() {
      const plausible = usePlausible<MyEvents>()
    
      return (
        <button
          onClick={() =>
            plausible('event1', { props: { prop1: 'hello' } })
          }
        >
          Send Event
        </button>
      )
    }
  7. Use customProperties function in PlausibleProvider

    master

    The init.customProperties option can be a static object or a function. If you use a function, it receives the eventName as an argument.

    Important: The function must be self-contained. Because it is serialized into an inline script, it cannot reference variables defined outside its scope.

    <PlausibleProvider
      src="https://plausible.io/js/pa-XXXXX.js"
      init={{
        customProperties: (eventName) => ({
          author: 'Alice',
        }),
      }}
    />
  8. Configure Plausible init options

    master

    The init prop on <PlausibleProvider /> accepts an object of options passed directly to plausible.init(). Available options include:

    NameDescription
    customPropertiesSet custom properties as an object or function.
    endpointSet a custom tracking endpoint. Automatically set when using the proxy.
    fileDownloadsTrack specific file types, e.g., { fileExtensions: ['pdf'] }.
    hashBasedRoutingSet to true to enable hash-based routing.
    autoCapturePageviewsSet to false to disable automatic pageview events.
    captureOnLocalhostSet to true to enable localhost tracking.
  9. Configure init options in PlausibleProvider

    master

    In v4, all feature configuration is passed through the init object. This object is passed to plausible.init() at runtime.

    Old PropNew init OptionDescription
    trackLocalhostcaptureOnLocalhost: trueTracks pageviews on localhost
    manualPageviewsautoCapturePageviews: falseDisables automatic pageview capture
    hashhashBasedRouting: trueEnables hash-based routing
    trackFileDownloadsfileDownloads: { fileExtensions: [...] }Configures file download tracking
    pageviewPropscustomPropertiesSets custom properties for pageviews
    <PlausibleProvider
      src="https://plausible.io/js/pa-XXXXX.js"
      init={{
        captureOnLocalhost: true,
        autoCapturePageviews: false,
        hashBasedRouting: true,
        fileDownloads: { fileExtensions: ['pdf', 'zip'] },
      }}
    />
  10. Configure PlausibleProvider props

    master

    The <PlausibleProvider /> component accepts the following props:

    NameDescription
    srcThe site-specific script URL from your Plausible dashboard. Not required when using withPlausibleProxy.
    initOptions passed to plausible.init().
    enabledExplicitly decide whether to render the script. If not passed, it renders in production environments (based on NODE_ENV and VERCEL_ENV).
    integritySubresource integrity attribute for security.
    scriptPropsOverride props passed to the script element.
  11. Use PlausibleProvider as the default export

    master

    The PlausibleProvider component is the default export of the next-plausible package. It is used to wrap your application (typically in _app.tsx or layout.tsx) to provide the analytics context and manage the Plausible script injection.

    import PlausibleProvider from 'next-plausible';
  12. Use withPlausibleProxy for script proxying

    master

    The withPlausibleProxy function is a named export used to proxy the Plausible analytics script through your own domain. This is useful for bypassing ad-blockers and improving privacy compliance.

    import { withPlausibleProxy } from 'next-plausible';