### Plausible initialization examples Source: https://github.com/plausible/plausible-tracker/blob/master/_autodocs/api-reference/tracker.md Shows basic initialization with `trackPageview()` and a self-hosted setup with `apiHost` and `hashMode` for hash routing. Note that `hashMode` must be passed to `Plausible(...)` to activate hash-change tracking. ```ts import Plausible from 'plausible-tracker' // Basic initialization const tracker = Plausible({ domain: 'my-app.com' }) tracker.trackPageview() // Self-hosted API + hash routing const { trackEvent, enableAutoPageviews } = Plausible({ domain: 'my-app.com', apiHost: 'https://analytics.example.com', hashMode: true, }) enableAutoPageviews() ``` -------------------------------- ### Install plausible-tracker with npm or yarn Source: https://github.com/plausible/plausible-tracker/blob/master/README.md Install the plausible-tracker package using either npm or yarn. Both commands are provided as alternatives. ```bash npm install plausible-tracker ``` ```bash yarn add plausible-tracker ``` -------------------------------- ### enableAutoPageviews usage example Source: https://github.com/plausible/plausible-tracker/blob/master/_autodocs/api-reference/tracker.md Example of enabling auto pageviews with hashMode and cleaning up later. ```ts import Plausible from 'plausible-tracker' const { enableAutoPageviews } = Plausible({ hashMode: true }) // Start tracking; cleanup restores history.pushState and removes listeners const cleanup = enableAutoPageviews() // later, e.g. on app teardown cleanup() ``` -------------------------------- ### Enable auto outbound tracking example Source: https://github.com/plausible/plausible-tracker/blob/master/_autodocs/api-reference/tracker.md Example usage of enableAutoOutboundTracking. It initializes the tracker, enables auto outbound tracking, and shows how to stop tracking by calling the returned cleanup function. ```ts import Plausible from 'plausible-tracker' const { enableAutoOutboundTracking } = Plausible() const cleanup = enableAutoOutboundTracking() // All existing and future outbound tags are now tracked. // Visualize event in your Plausible dashboard under "Outbound Link: Click". // Stop tracking cleanup() ``` -------------------------------- ### Direct sendEvent usage example Source: https://github.com/plausible/plausible-tracker/blob/master/_autodocs/api-reference/request.md Example of calling sendEvent directly with a fully-resolved configuration. It sends a 'signup' event with custom props and a callback that warns on non-200 status. ```ts import { sendEvent } from 'plausible-tracker/build/main/lib/request' sendEvent( 'signup', { hashMode: false, trackLocalhost: false, url: location.href, domain: 'my-app.com', referrer: document.referrer || null, deviceWidth: window.innerWidth, apiHost: 'https://plausible.io', }, { props: { plan: 'pro' }, callback: ({ status }) => { if (status !== 200) console.warn(`Plausible returned HTTP ${status}`) }, } ) ``` -------------------------------- ### trackPageview usage example Source: https://github.com/plausible/plausible-tracker/blob/master/_autodocs/api-reference/tracker.md Example of using trackPageview with explicit URL and a callback that logs the HTTP status. ```ts import Plausible from 'plausible-tracker' const { trackPageview } = Plausible({ trackLocalhost: true }) // Track the current page with explicit URL and a completion callback trackPageview( { url: 'https://my-app.com/checkout' }, { callback: ({ status }) => console.log('pageview sent, HTTP', status) } ) ``` -------------------------------- ### Example request body for trackEvent Source: https://github.com/plausible/plausible-tracker/blob/master/_autodocs/endpoints.md Example request body produced by trackEvent('signup', { props: { plan: 'pro' } }). Shows the JSON structure with the event name, URL, domain, referrer, device width, hash mode flag, and stringified props. ```json { "n": "signup", "u": "https://my-app.com/pricing", "d": "my-app.com", "r": "https://google.com", "w": 1920, "h": 0, "p": "{\"plan\":\"pro\"}" } ``` -------------------------------- ### trackEvent Usage Example Source: https://github.com/plausible/plausible-tracker/blob/master/_autodocs/api-reference/tracker.md Example of importing Plausible and calling trackEvent with custom properties and a callback, overriding the referrer. ```ts import Plausible from 'plausible-tracker' const { trackEvent } = Plausible({ domain: 'my-app.com' }) // Track a goal with custom properties and a callback trackEvent( 'download', { callback: ({ status }) => console.log('tracked, HTTP', status), props: { method: 'HTTP', variation: 2, loggedIn: true }, }, { referrer: 'https://google.com' } ) ``` -------------------------------- ### Observing request status in consumer code Source: https://github.com/plausible/plausible-tracker/blob/master/_autodocs/endpoints.md Consumer example showing how to observe the request status via the callback option. It warns when status is 0 (network/CORS failure) or >= 400 (API rejection). Demonstrates the only way to access the HTTP status since the library does not parse the response. ```ts import Plausible from 'plausible-tracker' const { trackPageview } = Plausible({ domain: 'my-app.com' }) trackPageview( { url: 'https://my-app.com/blog/hello' }, { callback: ({ status }) => { if (status === 0) { console.warn('Plausible request could not be completed (network/CORS)') } else if (status >= 400) { console.warn(`Plausible API rejected the event with HTTP ${status}`) } }, } ) ``` -------------------------------- ### Track event with overrides Source: https://github.com/plausible/plausible-tracker/blob/master/README.md Tracks a custom goal with override values through the third parameter. The example overrides trackLocalhost to true and provides a callback and props. ```ts import Plausible from 'plausible-tracker' const { trackEvent } = Plausible({ trackLocalhost: false, }) // Tracks the 'signup' goal with a callback, props and a different referrer. trackEvent( 'signup', { callback: () => console.log('done'), props: { variation: 'button A' } }, { trackLocalhost: true } ); ``` -------------------------------- ### Consumer error handling with trackEvent Source: https://github.com/plausible/plausible-tracker/blob/master/_autodocs/api-reference/request.md Example of error handling in consumer code using the Plausible factory. It shows how to detect network errors or CORS blocks via a callback that checks for status 0. ```ts import Plausible from 'plausible-tracker' // sendEvent never throws; silent-ignore conditions surface only as console.warn // messages when (a) tracking a local site without trackLocalhost, or (b) the // localStorage.plausible_ignore flag is "true". Completion is observable via callback: const { trackEvent } = Plausible({ domain: 'my-app.com' }) trackEvent('checkout', { callback: ({ status }) => { if (status === 0) { console.warn('Plausible request failed (network error or CORS block)') } }, }) ``` -------------------------------- ### trackEvent Source: https://github.com/plausible/plausible-tracker/blob/master/_autodocs/api-reference/tracker.md Documentation for the trackEvent function from the plausible-tracker library, including its signature, parameters, return value, and usage example. ```APIDOC ## `trackEvent(eventName, options?, eventData?)` ### Description Tracks a custom event or goal with optional properties and per-call overrides. The event is sent asynchronously to the Plausible API via `XMLHttpRequest`. ### Signature ```ts type TrackEvent = ( eventName: string, options?: EventOptions, eventData?: PlausibleOptions ) => void; ``` ### Parameters | Parameter | Type | Required | Default | Description | |-----------|------|----------|---------|-------------| | `eventName` | `string` | yes | — | Name of the event/goal to track (e.g. `'signup'`). Sent as the `n` payload field. | | `options` | `EventOptions` | no | `undefined` | `{ readonly callback?: (args: { readonly status: number }) => void; readonly props?: { readonly [propName: string]: string \| number \| boolean } }`. `props` are JSON-stringified into the `p` payload field; `callback` fires once the HTTP request round-trip completes (`readyState === 4`). | | `eventData` | `PlausibleOptions` | no | runtime defaults | Per-call overrides merged over the factory defaults. Inline expansion: `{ readonly hashMode?: boolean; readonly trackLocalhost?: boolean; readonly domain?: Location['hostname']; readonly apiHost?: string; readonly url?: Location['href']; readonly referrer?: Document['referrer'] \| null; readonly deviceWidth?: Window['innerWidth'] }`. | ### Return value `void`. The request is sent asynchronously via `XMLHttpRequest`; nothing is returned. ### Throws None. Potential blocking conditions are handled by logging a warning with `console.warn` and returning early. ### Example ```ts import Plausible from 'plausible-tracker' const { trackEvent } = Plausible({ domain: 'my-app.com' }) // Track a goal with custom properties and a callback trackEvent( 'download', { callback: ({ status }) => console.log('tracked, HTTP', status), props: { method: 'HTTP', variation: 2, loggedIn: true }, }, { referrer: 'https://google.com' } ) ``` ``` -------------------------------- ### Usage pattern for plausible-tracker entry point Source: https://github.com/plausible/plausible-tracker/blob/master/_autodocs/api-reference/index.md Usage pattern for the entry point. Import the default export and types, create a tracker with domain, then call tracking methods. ```ts import Plausible, { PlausibleOptions, EventOptions } from 'plausible-tracker' const tracker = Plausible({ domain: 'my-app.com' }) tracker.trackPageview() tracker.trackEvent('signup') const cleanup = tracker.enableAutoPageviews() ``` -------------------------------- ### Initialize Plausible tracker with domain Source: https://github.com/plausible/plausible-tracker/blob/master/README.md Initialize the tracker with the required domain option. The returned object contains the tracking functions. ```ts import Plausible from 'plausible-tracker' const plausible = Plausible({ domain: 'my-app.com' }) ``` -------------------------------- ### PlausibleInitOptions Source: https://github.com/plausible/plausible-tracker/blob/master/_autodocs/types.md Configuration options for initializing the Plausible tracker. ```APIDOC ## PlausibleInitOptions ### Description Configuration options for initializing the Plausible tracker. ### Type TypeScript type ### Fields - **hashMode** (boolean) - Optional - Track pageviews on URL hash changes (hash-based routing). - **trackLocalhost** (boolean) - Optional - Track events when the site runs locally (localhost / `file:` protocol). - **domain** (Location['hostname']) - Optional - Site domain as declared in Plausible settings. - **apiHost** (string) - Optional - API host to send events to; change when self-hosting. ### Usage Used by the `Plausible()` factory's `defaults` parameter. ``` -------------------------------- ### enableAutoOutboundTracking(targetNode?, observerInit?) Source: https://github.com/plausible/plausible-tracker/blob/master/_autodocs/api-reference/tracker.md Documentation for the enableAutoOutboundTracking function from the plausible-tracker library. ```APIDOC ## `enableAutoOutboundTracking(targetNode?, observerInit?)` ### Description Enables automatic tracking of outbound link clicks. It scans the target node for anchor tags, attaches click listeners to outbound links, and observes the DOM for newly added or removed anchors. ### Signature ```ts type EnableAutoOutboundTracking = ( targetNode?: Node & ParentNode, observerInit?: MutationObserverInit ) => Cleanup; ``` ### Parameters | Parameter | Type | Required | Default | Description | |-----------|------|----------|---------|-------------| | `targetNode` | `Node & ParentNode` | no | `document` | The node subtree to scan and observe for anchor tags. | | `observerInit` | `MutationObserverInit` | no | `{ subtree: true, childList: true, attributes: true, attributeFilter: ['href'] }` | Options passed to `MutationObserver.observe` (same shape as the native API). | ### Return Value A `Cleanup` function. Calling it removes the `click` listeners from all tracked anchors and disconnects the `MutationObserver`. ### Behavior - **Click handling:** a `click` listener is attached to every `` element whose `node.host !== location.host` (outbound links only). The handler fires `trackEvent('Outbound Link: Click', { props: { url: this.href } })`, then — unless `process.env.NODE_ENV === 'test'` — schedules `location.href = this.href` after `150ms`, and finally calls `event.preventDefault()`. The delayed navigation gives the tracking request time to fire; in a test environment the redirect is skipped. - **Initial scan:** `targetNode.querySelectorAll('a')` is walked and each anchor is added. - **Mutation handling:** a `MutationObserver` watches the `targetNode`: - `attributes` mutations (href changes) trigger remove-then-re-add of the target node. - `childList` mutations add listeners for `addedNodes` and remove them for `removedNodes`. - Newly added anchors are tracked automatically; removed/tracked anchors are kept in a `Set` used by cleanup. - **Cleanup:** iterates the tracked set, removes the `click` listeners, clears the set, and disconnects the observer. ### Throws None. ### Examples ```ts import Plausible from 'plausible-tracker' const { enableAutoOutboundTracking } = Plausible() const cleanup = enableAutoOutboundTracking() // All existing and future outbound tags are now tracked. // Visualize event in your Plausible dashboard under "Outbound Link: Click". // Stop tracking cleanup() ``` ``` -------------------------------- ### Plausible() Source: https://github.com/plausible/plausible-tracker/blob/master/README.md Initializes the Plausible tracker with configuration options and returns an object of tracking functions. ```APIDOC ## [NPM] Plausible() ### Description Initializes the Plausible tracker with configuration options. Returns an object containing tracking functions. ### Method NPM Package Initialization ### Endpoint `Plausible(options?: PlausibleInitOptions)` ### Parameters #### Options - **domain** (string) - Optional - Your site's domain, as declared by you in Plausible's settings. Default: `location.hostname` - **hashMode** (bool) - Optional - Enables tracking based on URL hash changes. Default: `false` - **trackLocalhost** (bool) - Optional - Enables tracking on *localhost*. Default: `false` - **apiHost** (string) - Optional - Plausible's API host to use. Change this if you are self-hosting. Default: `'https://plausible.io'` ### Request Example ```ts import Plausible from 'plausible-tracker' const plausible = Plausible({ domain: 'my-app.com' }) ``` ### Response #### Success Response Returns an object with the following functions: `trackPageview`, `trackEvent`, `enableAutoPageviews`. ``` -------------------------------- ### PlausibleOptions Source: https://github.com/plausible/plausible-tracker/blob/master/_autodocs/types.md Combined options for initializing the tracker and attaching event data. ```APIDOC ## PlausibleOptions ### Description Combined options for initializing the tracker and attaching event data. ### Type TypeScript type (intersection of PlausibleInitOptions and PlausibleEventData) ### Fields - **hashMode** (boolean) - Optional - Pageview tracking on hash changes. - **trackLocalhost** (boolean) - Optional - Track on localhost. - **domain** (Location['hostname']) - Optional - Site domain for the event. - **apiHost** (string) - Optional - API host. - **url** (Location['href']) - Optional - URL the event is bound to. - **referrer** (Document['referrer'] | null) - Optional - Referrer; `null` allowed. - **deviceWidth** (Window['innerWidth']) - Optional - Device width. ### Usage Used by `eventData`/per-call override parameters of `trackEvent` and `trackPageview`; also the shape of the merged config that `sendEvent` receives as `Required`. ``` -------------------------------- ### window.plausible Source: https://github.com/plausible/plausible-tracker/blob/master/_autodocs/api-reference/tracker.md Documentation for the global `window.plausible` function exposed by the plausible-tracker library. ```APIDOC ## `window.plausible` ### Description Global function exposed on `window.plausible` that tracks events. It is set synchronously when `Plausible()` is called and mirrors `tracker.trackEvent`. ### Method `window.plausible(eventName, options?)` ### Parameters - **eventName** (string) - Required - The name of the event to track. - **options** (object) - Optional - Event options (see `EventOptions` in `request.md`). ### Example ```ts import Plausible from 'plausible-tracker' const tracker = Plausible() // window.plausible is now set to the same function as tracker.trackEvent window.plausible('signup') ``` ``` -------------------------------- ### PlausibleInitOptions type definition Source: https://github.com/plausible/plausible-tracker/blob/master/_autodocs/types.md Configuration options for initializing the Plausible tracker. `hashMode` enables pageview tracking on URL hash changes for hash-based routing; `trackLocalhost` enables tracking on localhost; `domain` defaults to `location.hostname`; `apiHost` defaults to `'https://plausible.io'` and should be changed when self-hosting. Not re-exported at the package entry point; import from the module path. ```typescript export type PlausibleInitOptions = { /** * If true, pageviews will be tracked when the URL hash changes. * Enable this if you are using a frontend that uses hash-based routing. */ readonly hashMode?: boolean; /** * Set to true if you want events to be tracked when running the site locally. */ readonly trackLocalhost?: boolean; /** * The domain to bind the event to. * Defaults to `location.hostname` */ readonly domain?: Location['hostname']; /** * The API host where the events will be sent. * Defaults to `'https://plausible.io'` */ readonly apiHost?: string; }; ``` -------------------------------- ### Outbound link click handler with NODE_ENV test check Source: https://github.com/plausible/plausible-tracker/blob/master/_autodocs/configuration.md Conditional navigation for outbound link clicks. When NODE_ENV is not 'test', schedules navigation to the link target after a 150 ms delay to allow the tracking request to fire; otherwise skips navigation. Always calls event.preventDefault(). The typeof process guard ensures safety in browsers without a process global. ```ts if (!(typeof process !== 'undefined' && process && process.env.NODE_ENV === 'test')) { setTimeout(() => { location.href = this.href; }, 150); } event.preventDefault(); ``` -------------------------------- ### Module graph of plausible-tracker Source: https://github.com/plausible/plausible-tracker/blob/master/_autodocs/api-reference/index.md Module graph showing the public entry point and internal dependencies. The Plausible factory closes over defaults and sends events via sendEvent. ```text src/index.ts (public entry point) ├── default export Plausible ──────────┐ └── export type PlausibleOptions │ └── export type EventOptions │ ▼ src/lib/tracker.ts (Plausible factory) ├── export types: PlausibleInitOptions, PlausibleEventData, PlausibleOptions ├── declare global Window.plausible └── imports sendEvent, EventOptions ──► src/lib/request.ts ├── export type EventOptions ├── export function sendEvent └── (internal) EventPayload, CallbackArgs ``` -------------------------------- ### EventOptions Source: https://github.com/plausible/plausible-tracker/blob/master/_autodocs/types.md Options for sending an event. ```APIDOC ## EventOptions ### Description Options for sending an event. ### Type TypeScript type ### Fields - **callback** ((args: CallbackArgs) => void) - Optional - Called when the HTTP request round-trip completes (`readyState === 4`), with the response status. It fires regardless of success/failure. - **props** ({ readonly [propName: string]: string | number | boolean }) - Optional - Custom properties bound to the event; JSON-stringified into the `p` payload field. Values are limited to string, number, or boolean. ### Usage Used by the `options` parameter of `trackEvent`, `trackPageview`, and `sendEvent`. ``` -------------------------------- ### Track event with custom props Source: https://github.com/plausible/plausible-tracker/blob/master/README.md Tracks a custom goal with custom props provided via the second parameter. ```ts // Tracks the 'download' goal and provides a 'method' property. trackEvent('download', { props: { method: 'HTTP' } }) ``` -------------------------------- ### enableAutoPageviews() Source: https://github.com/plausible/plausible-tracker/blob/master/_autodocs/api-reference/tracker.md Enables automatic pageview tracking by wrapping history.pushState and adding event listeners, returning a cleanup function. ```APIDOC ## `enableAutoPageviews()` ### Description Enables automatic pageview tracking by wrapping `history.pushState` and adding event listeners. Returns a cleanup function to restore original behavior. ### Signature ```ts type EnableAutoPageviews = () => Cleanup; // where Cleanup = () => void (src/lib/tracker.ts:114) ``` ### Parameters None. ### Return value A `Cleanup` function. Calling it removes the added event listeners and restores the original `history.pushState` (see below). ### Behavior (exact, from source) 1. Captures the original `history.pushState`. If present, it wraps it: every call to `pushState(data, title, url)` invokes the original first, then fires `trackPageview()`. It also adds a `popstate` event listener that fires `trackPageview()`. 2. If the factory was initialized with `defaults.hashMode === true`, it additionally adds a `hashchange` listener that fires `trackPageview()`. 3. Immediately triggers an initial `trackPageview()` for the current page. 4. The returned cleanup: restores `history.pushState` to the original, removes the `popstate` listener (and the `hashchange` listener when `hashMode` was on). The `hashMode` check reads `defaults && defaults.hashMode` — the factory's init option, not the merged per-call config. ### Throws None. No error paths exist in the implementation. ### Examples ```ts import Plausible from 'plausible-tracker' const { enableAutoPageviews } = Plausible({ hashMode: true }) // Start tracking; cleanup restores history.pushState and removes listeners const cleanup = enableAutoPageviews() // later, e.g. on app teardown cleanup() ``` ``` -------------------------------- ### Plausible(defaults?: PlausibleInitOptions) Source: https://github.com/plausible/plausible-tracker/blob/master/_autodocs/api-reference/index.md The Plausible factory function is the default export of the plausible-tracker package. It initializes a tracker with optional default options and returns an object with methods for tracking page views, custom events, and enabling automatic tracking. ```APIDOC ## [FACTORY] Plausible(defaults?: PlausibleInitOptions) ### Description Creates a tracker instance configured with optional default options. Returns an object with methods to track page views, events, and enable automatic tracking. ### Method Factory function ### Endpoint `plausible-tracker` (default export) ### Parameters #### Request Body - **defaults** (PlausibleInitOptions) - Optional - Default configuration options for the tracker. ### Request Example ```ts import Plausible from 'plausible-tracker' const tracker = Plausible({ domain: 'my-app.com' }) ``` ### Response #### Success Response - **trackEvent** (function) - Tracks a custom event. - **trackPageview** (function) - Tracks a page view. - **enableAutoPageviews** (function) - Enables automatic page view tracking for SPAs. - **enableAutoOutboundTracking** (function) - Enables automatic outbound link click tracking. #### Response Example ```ts const tracker = Plausible({ domain: 'my-app.com' }) tracker.trackPageview() tracker.trackEvent('signup') const cleanup = tracker.enableAutoPageviews() ``` ``` -------------------------------- ### Track a page view with trackPageview Source: https://github.com/plausible/plausible-tracker/blob/master/README.md Track a single page view using the trackPageview function. The tracker is initialized without options, so the domain defaults to location.hostname. ```ts import Plausible from 'plausible-tracker' const { trackPageview } = Plausible() // Track a page view trackPageview() ``` -------------------------------- ### Track a custom goal with trackEvent Source: https://github.com/plausible/plausible-tracker/blob/master/README.md Tracks a custom goal or event by name. The first parameter is the goal/event name. ```ts import Plausible from 'plausible-tracker' const { trackEvent } = Plausible() // Tracks the 'signup' goal trackEvent('signup') ``` -------------------------------- ### Cleanup type Source: https://github.com/plausible/plausible-tracker/blob/master/_autodocs/types.md Return type of EnableAutoPageviews and EnableAutoOutboundTracking. ```ts type Cleanup = () => void; ``` -------------------------------- ### enableAutoPageviews type signature Source: https://github.com/plausible/plausible-tracker/blob/master/_autodocs/api-reference/tracker.md Type signature for enableAutoPageviews. It returns a Cleanup function. ```ts type EnableAutoPageviews = () => Cleanup; // where Cleanup = () => void (src/lib/tracker.ts:114) ``` -------------------------------- ### getConfig: Build merged runtime configuration Source: https://github.com/plausible/plausible-tracker/blob/master/_autodocs/configuration.md Returns the fully merged runtime configuration object of type Required. It combines hard-coded defaults with the factory defaults passed to Plausible(). Used as the base for every tracking call. ```typescript const getConfig = (): Required => ({ hashMode: false, trackLocalhost: false, url: location.href, domain: location.hostname, referrer: document.referrer || null, deviceWidth: window.innerWidth, apiHost: 'https://plausible.io', ...defaults, }); ``` -------------------------------- ### trackPageview() Source: https://github.com/plausible/plausible-tracker/blob/master/README.md Tracks a single page view. Accepts optional overrides for tracking options and event options. ```APIDOC ## [NPM] trackPageview() ### Description Tracks a single page view. Accepts optional overrides for tracking options and event options. ### Method NPM Package Function ### Endpoint `trackPageview(options?: PlausibleOptions, eventOptions?: EventOptions)` ### Parameters #### Options (first parameter) - **url** (string) - Optional - Current page's URL. Default: `location.href` - **referrer** (string or null) - Optional - Referrer's address. Default: `document.referrer` - **deviceWidth** (number) - Optional - User's device width for device tracking. Default: `window.innerWidth` - **domain** (string) - Optional - Your site's domain, as declared by you in Plausible's settings. Default: `location.hostname` - **hashMode** (bool) - Optional - Enables tracking based on URL hash changes. Default: `false` - **trackLocalhost** (bool) - Optional - Enables tracking on *localhost*. Default: `false` - **apiHost** (string) - Optional - Plausible's API host to use. Change this if you are self-hosting. Default: `'https://plausible.io'` #### Event Options (second parameter) Similar to the options provided by the official Plausible script, including a `callback` option. ### Request Example ```ts import Plausible from 'plausible-tracker' const { trackPageview } = Plausible({ // Track localhost by default trackLocalhost: true, }) // Override it on this call and also set a custom url trackPageview({ trackLocalhost: false, url: "https://my-app.com/my-url" }) ``` ### Response No response body documented. ``` -------------------------------- ### Enable automatic page views with enableAutoPageviews Source: https://github.com/plausible/plausible-tracker/blob/master/README.md Enables automatic page view tracking for SPAs using JS-based routing. Overrides history.pushState and attaches popstate and hashchange listeners. Call this once to track the current and future page views. ```ts import Plausible from 'plausible-tracker' const { enableAutoPageviews } = Plausible() // This tracks the current page view and all future ones as well enableAutoPageviews() ``` -------------------------------- ### POST {apiHost}/api/event Source: https://github.com/plausible/plausible-tracker/blob/master/_autodocs/endpoints.md Documentation for the single HTTP endpoint used by the plausible-tracker library to send events to the Plausible Analytics ingestion API. ```APIDOC ## POST {apiHost}/api/event ### Description Sends an event to the Plausible Analytics ingestion endpoint. This is the only outbound HTTP route in the plausible-tracker library, called internally by `sendEvent()`. ### Method POST ### Endpoint `{apiHost}/api/event` ### Parameters #### Path Parameters - `apiHost` (string) - Required - The host for the Plausible API. Defaults to `https://plausible.io`. #### Request Body - `n` (string) - Required - The event name (e.g., `'pageview'` or a goal/event name). - `u` (string) - Required - The URL of the page (defaults to `location.href`). - `d` (string) - Required - The domain (defaults to `location.hostname`). - `r` (string | null) - Required - The referrer (defaults to `document.referrer || null`). - `w` (number) - Required - The device width (defaults to `window.innerWidth`). - `h` (1 | 0) - Required - Indicates hash mode (1 if `data.hashMode` is true, else 0). - `p` (string) - Optional - JSON string of additional properties; omitted if no props are supplied. ### Request Example ```json { "n": "signup", "u": "https://my-app.com/pricing", "d": "my-app.com", "r": "https://google.com", "w": 1920, "h": 0, "p": "{\"plan\":\"pro\"}" } ``` ### Response #### Success Response (200) The client does not parse or inspect the response body. The callback receives an object with the raw HTTP status code. #### Response Example No response body is parsed; the callback receives `{ status: req.status }`. ### Notes - The request is sent asynchronously with `Content-Type: text/plain`. - No authentication headers are attached. - The request is suppressed (no request sent) if the site is running locally and `trackLocalhost` is false, or if `localStorage.plausible_ignore` is set to `'true'`. - The client does not define, validate, or react to specific HTTP status codes; success/failure interpretation is left to the consumer. ``` -------------------------------- ### Enable auto outbound tracking Source: https://github.com/plausible/plausible-tracker/blob/master/README.md Enables automatic tracking of clicks to outbound links. Adds a click event listener to all a tags and creates a MutationObserver to track dynamically-added links. ```ts import Plausible from 'plausible-tracker' const { enableAutoOutboundTracking } = Plausible() // Track all existing and future outbound links enableAutoOutboundTracking() ``` -------------------------------- ### Localhost detection regex in request.ts Source: https://github.com/plausible/plausible-tracker/blob/master/_autodocs/configuration.md Regex used to detect localhost and loopback addresses. Matches 'localhost', '127.0.0.1' (and 127.x.y.z up to 4 octets), and IPv6 loopback forms like '::1'. When matched and trackLocalhost is not enabled, event sending is skipped with a console.warn. ```ts /^localhost$|^127(?:\.[0-9]+){0,2}\.[0-9]+$|^(?:0*:)*?:?0*1$/ ``` -------------------------------- ### Type re-exports for PlausibleOptions and EventOptions Source: https://github.com/plausible/plausible-tracker/blob/master/_autodocs/api-reference/index.md Type re-exports from the package entry point. These types are available from 'plausible-tracker'. ```ts export type { PlausibleOptions } from './lib/tracker'; export type { EventOptions } from './lib/request'; ``` -------------------------------- ### Use callback option in trackPageview Source: https://github.com/plausible/plausible-tracker/blob/master/README.md Pass an event options object as the second parameter to trackPageview. The callback option is invoked when the event is sent. ```ts import Plausible from 'plausible-tracker' const { trackPageview } = Plausible() // And override it on this call trackPageview({}, { callback: () => console.log("Done!") }) ``` -------------------------------- ### EnableAutoOutboundTracking type Source: https://github.com/plausible/plausible-tracker/blob/master/_autodocs/types.md Type of the enableAutoOutboundTracking property returned by Plausible(). Defaults (targetNode = document, observerInit = { subtree: true, childList: true, attributes: true, attributeFilter: ['href'] }) are applied by the implementation, not by the type. ```ts type EnableAutoOutboundTracking = ( targetNode?: Node & ParentNode, observerInit?: MutationObserverInit ) => Cleanup; ``` -------------------------------- ### Enable auto pageviews with hashMode Source: https://github.com/plausible/plausible-tracker/blob/master/README.md Enables automatic page view tracking with hashMode enabled for apps that use URL hashes to represent pages. Hash changes will also trigger page views. ```ts import Plausible from 'plausible-tracker' const { enableAutoPageviews } = Plausible({ hashMode: true }) // Hash changes will also trigger page views enableAutoPageviews() ``` -------------------------------- ### sendEvent(eventName, data, options?) Source: https://github.com/plausible/plausible-tracker/blob/master/_autodocs/api-reference/request.md Sends a custom event to the Plausible API. It constructs a POST request to the configured apiHost with the event payload and invokes an optional callback with the HTTP status. ```APIDOC ## sendEvent(eventName, data, options?) ### Description Sends a custom event to the Plausible analytics API. It constructs a POST request to the configured apiHost with the event payload and invokes an optional callback with the HTTP status. ### Method POST ### Endpoint `${data.apiHost}/api/event` ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body - `n` (string) - Required - Event name. - `u` (string) - Required - URL of the page where the event occurred. - `d` (string) - Required - Domain of the site. - `r` (string|null) - Required - Referrer URL or null. - `w` (number) - Required - Device width. - `h` (number) - Required - Hash mode flag (1 or 0). - `p` (string|undefined) - Optional - JSON string of custom properties. ### Request Example ```json { "n": "signup", "u": "https://example.com/page", "d": "example.com", "r": "https://google.com", "w": 1920, "h": 0, "p": "{\"plan\":\"pro\"}" } ``` ### Response #### Success Response (200) - No response body is documented. #### Response Example No response body is documented. ### Error Handling - The function never throws. It logs a warning and returns without sending a request if the site is local and `trackLocalhost` is false, or if `localStorage.plausible_ignore` is set to 'true'. - Network errors or CORS blocks result in a status of 0 in the callback. ### Notes - The request is asynchronous; completion is reported via the `callback` option. - The `callback` receives an object with a `status` property containing the HTTP status code. - The `Content-Type` header is set to `text/plain`. - The `props` field is JSON stringified; if no props are provided, the field is omitted. ``` -------------------------------- ### Using window.plausible after Plausible() Source: https://github.com/plausible/plausible-tracker/blob/master/_autodocs/api-reference/tracker.md Shows that calling `Plausible()` synchronously sets `window.plausible` to the same function as `tracker.trackEvent`. The library does not remove it when a tracker instance goes out of scope. ```ts import Plausible from 'plausible-tracker' const tracker = Plausible() // window.plausible is now set to the same function as tracker.trackEvent window.plausible('signup') ``` -------------------------------- ### POST /api/event via XMLHttpRequest Source: https://github.com/plausible/plausible-tracker/blob/master/_autodocs/endpoints.md The core HTTP request made by the library's sendEvent() function. It opens an asynchronous POST to the Plausible ingestion endpoint, sets the Content-Type header to text/plain, and sends the JSON-stringified event payload. No authentication headers are attached. ```ts const req = new XMLHttpRequest(); req.open('POST', `${data.apiHost}/api/event`, true); req.setRequestHeader('Content-Type', 'text/plain'); req.send(JSON.stringify(payload)); ``` -------------------------------- ### EnableAutoPageviews type Source: https://github.com/plausible/plausible-tracker/blob/master/_autodocs/types.md Type of the enableAutoPageviews property returned by Plausible(). ```ts type EnableAutoPageviews = () => Cleanup; ``` -------------------------------- ### Override tracker options in trackPageview call Source: https://github.com/plausible/plausible-tracker/blob/master/README.md Override initialization options on a per-call basis. Here trackLocalhost is enabled at initialization but disabled for this specific page view, and a custom URL is provided. ```ts import Plausible from 'plausible-tracker' const { trackPageview } = Plausible({ // Track localhost by default trackLocalhost: true, }) // Override it on this call and also set a custom url trackPageview({ trackLocalhost: false, url: "https://my-app.com/my-url" }) ``` -------------------------------- ### EventOptions type definition Source: https://github.com/plausible/plausible-tracker/blob/master/_autodocs/types.md Options for sending events. `callback` is called when the HTTP request round-trip completes (`readyState === 4`) with the response status, firing regardless of success/failure despite the doc comment. `props` are custom properties JSON-stringified into the `p` payload field, limited to string, number, or boolean values. Used by `trackEvent`, `trackPageview`, and `sendEvent`. ```typescript export type EventOptions = { /** * Callback called when the event is successfully sent. */ readonly callback?: (args: CallbackArgs) => void; /** * Properties to be bound to the event. */ readonly props?: { readonly [propName: string]: string | number | boolean }; }; ``` -------------------------------- ### Callback invocation with status Source: https://github.com/plausible/plausible-tracker/blob/master/_autodocs/endpoints.md Invoked in the onreadystatechange handler when req.readyState === 4 and a callback was provided via EventOptions.callback. Passes the raw numeric XMLHttpRequest.status, which is 0 for network failures or blocked requests (e.g., CORS rejection). The client does not branch on the status value. ```ts options.callback({ status: req.status }); ``` -------------------------------- ### Default export of Plausible factory Source: https://github.com/plausible/plausible-tracker/blob/master/_autodocs/api-reference/index.md Default export of the Plausible factory function. Import it from 'plausible-tracker' using ES modules or CommonJS. ```ts export default Plausible; ``` -------------------------------- ### Global declaration of window.plausible Source: https://github.com/plausible/plausible-tracker/blob/master/_autodocs/api-reference/tracker.md Declares the global `window.plausible` property as a `TrackEvent` function. This is part of the official script's contract, matching the `window.plausible` function exposed by `plausible.js`. ```ts declare global { interface Window { plausible: TrackEvent; } } ``` -------------------------------- ### TrackPageview type Source: https://github.com/plausible/plausible-tracker/blob/master/_autodocs/types.md Type of the trackPageview property returned by Plausible(). Note the argument order differs from TrackEvent: event data comes before options. ```ts type TrackPageview = ( eventData?: PlausibleOptions, options?: EventOptions ) => void; ``` -------------------------------- ### PlausibleEventData type definition Source: https://github.com/plausible/plausible-tracker/blob/master/_autodocs/types.md Event data options for tracking. `url` defaults to `location.href`, `referrer` defaults to `document.referrer` and can be explicitly `null`, and `deviceWidth` defaults to `window.innerWidth`. Used by the `eventData` parameters of `trackEvent` and `trackPageview` via `PlausibleOptions`. ```typescript export type PlausibleEventData = { /** * The URL to bind the event to. * Defaults to `location.href`. */ readonly url?: Location['href']; /** * The referrer to bind the event to. * Defaults to `document.referrer` */ readonly referrer?: Document['referrer'] | null; /** * The current device's width. * Defaults to `window.innerWidth` */ readonly deviceWidth?: Window['innerWidth']; }; ``` -------------------------------- ### Clean up auto pageview listeners Source: https://github.com/plausible/plausible-tracker/blob/master/README.md Cleans up the event listeners and restores history.pushState after calling enableAutoPageviews(). The cleanup function is returned by enableAutoPageviews(). ```ts import Plausible from 'plausible-tracker' const { enableAutoPageviews } = Plausible() const cleanup = enableAutoPageviews() // ... // Remove event listeners and restore history.pushState cleanup() ``` -------------------------------- ### sendEvent request construction Source: https://github.com/plausible/plausible-tracker/blob/master/_autodocs/api-reference/request.md Exact request construction for sendEvent. It builds the payload, sends a POST request to the apiHost endpoint with a text/plain content type, and invokes the callback when the request completes. ```ts const payload: EventPayload = { n: eventName, u: data.url, d: data.domain, r: data.referrer, w: data.deviceWidth, h: data.hashMode ? 1 : 0, p: options && options.props ? JSON.stringify(options.props) : undefined, }; const req = new XMLHttpRequest(); req.open('POST', `${data.apiHost}/api/event`, true); req.setRequestHeader('Content-Type', 'text/plain'); req.send(JSON.stringify(payload)); req.onreadystatechange = () => { if (req.readyState !== 4) return; if (options && options.callback) { options.callback({ status: req.status }); } }; ``` -------------------------------- ### Plausible factory function signature Source: https://github.com/plausible/plausible-tracker/blob/master/_autodocs/api-reference/tracker.md Signature of the default-exported factory function `Plausible` from `src/lib/tracker.ts`. It accepts optional `PlausibleInitOptions` and returns an object with four readonly tracking functions. ```ts export default function Plausible( defaults?: PlausibleInitOptions ): { readonly trackEvent: TrackEvent; readonly trackPageview: TrackPageview; readonly enableAutoPageviews: EnableAutoPageviews; readonly enableAutoOutboundTracking: EnableAutoOutboundTracking; } ``` -------------------------------- ### sendEvent: Apply per-call event data overrides Source: https://github.com/plausible/plausible-tracker/blob/master/_autodocs/configuration.md Shows how per-call event data overrides the merged runtime configuration. The spread order gives precedence to eventData over getConfig() defaults. Used in trackEvent and trackPageview. ```typescript sendEvent(eventName, { ...getConfig(), ...eventData }, options); ``` -------------------------------- ### PlausibleEventData Source: https://github.com/plausible/plausible-tracker/blob/master/_autodocs/types.md Data fields that can be attached to an event. ```APIDOC ## PlausibleEventData ### Description Data fields that can be attached to an event. ### Type TypeScript type ### Fields - **url** (Location['href']) - Optional - URL the event is bound to. - **referrer** (Document['referrer'] | null) - Optional - Referrer address; can be explicitly `null`. - **deviceWidth** (Window['innerWidth']) - Optional - User's device width, used for device tracking. ### Usage Used by the `eventData` parameters of `trackEvent` and `trackPageview`. ``` -------------------------------- ### Clean up outbound tracking listeners Source: https://github.com/plausible/plausible-tracker/blob/master/README.md Cleans up the event listeners and disconnects the MutationObserver after calling enableAutoOutboundTracking(). The cleanup function is returned by enableAutoOutboundTracking(). ```ts import Plausible from 'plausible-tracker' const { enableAutoOutboundTracking } = Plausible() const cleanup = enableAutoOutboundTracking() // ... // Remove event listeners and disconnect the MutationObserver cleanup() ``` -------------------------------- ### CallbackArgs type Source: https://github.com/plausible/plausible-tracker/blob/master/_autodocs/types.md Defines the argument passed to EventOptions.callback. The status field is the XMLHttpRequest.status of the completed request; 0 typically indicates a network/CORS failure. ```ts type CallbackArgs = { readonly status: number; }; ``` -------------------------------- ### sendEvent function signature Source: https://github.com/plausible/plausible-tracker/blob/master/_autodocs/api-reference/request.md TypeScript signature for the sendEvent function. It takes an event name, fully-resolved configuration, and optional EventOptions, returning void. ```ts export function sendEvent( eventName: string, data: Required, options?: EventOptions ): void; ``` -------------------------------- ### TrackEvent type Source: https://github.com/plausible/plausible-tracker/blob/master/_autodocs/types.md Type of the trackEvent property returned by Plausible() and the declared type of Window.plausible. ```ts type TrackEvent = ( eventName: string, options?: EventOptions, eventData?: PlausibleOptions ) => void; ``` -------------------------------- ### PlausibleOptions type definition Source: https://github.com/plausible/plausible-tracker/blob/master/_autodocs/types.md Intersection type combining `PlausibleInitOptions` and `PlausibleEventData`. Re-exported from the package entry point. Used for per-call overrides in `trackEvent` and `trackPageview`, and is the shape of the merged config that `sendEvent` receives as `Required`. ```typescript export type PlausibleOptions = PlausibleInitOptions & PlausibleEventData; ``` -------------------------------- ### EventPayload type definition Source: https://github.com/plausible/plausible-tracker/blob/master/_autodocs/endpoints.md The TypeScript type for the event payload sent to the /api/event endpoint. Fields n, u, d, r, w, and h are required; p is optional and omitted when no props are supplied. The h field is 1 when hashMode is enabled, otherwise 0. ```ts type EventPayload = { readonly n: string; readonly u: Location['href']; readonly d: Location['hostname']; readonly r: Document['referrer'] | null; readonly w: Window['innerWidth']; readonly h: 1 | 0; readonly p?: string; }; ```