### Install Pirsch JavaScript SDK Source: https://github.com/pirsch-analytics/pirsch-js-sdk/blob/master/README.md Install the Pirsch JavaScript SDK using npm. This is the first step before integrating the SDK into your project. ```bash npm i pirsch-sdk ``` -------------------------------- ### Manage Sessions and Handle Errors with Pirsch JS SDK Source: https://context7.com/pirsch-analytics/pirsch-js-sdk/llms.txt This example shows how to keep user sessions alive and implement comprehensive error handling for API interactions using the Pirsch JS SDK. It covers session management, tracking hits with custom tags, and differentiating between various API error types and status codes. Dependencies include 'pirsch-sdk' and 'PirschApiError'. It takes request details as input and outputs session status and error messages. ```javascript import { Pirsch, PirschApiError } from "pirsch-sdk"; const client = new Pirsch({ hostname: "example.com", clientId: "your_client_id", clientSecret: "your_client_secret", timeout: 10000 }); async function manageSessionsWithErrorHandling(request) { try { // Keep session alive (extends session duration) const sessionData = { ip: request.socket.remoteAddress, user_agent: request.headers["user-agent"] }; await client.session(sessionData); console.log("Session kept alive"); // Track hit with custom tags const hit = client.hitFromRequest(request); hit.tags = { user_type: "premium", experiment: "variant_a" }; await client.hit(hit); } catch (error) { if (error instanceof PirschApiError) { // Structured API error console.error(`API Error ${error.code}: ${error.message}`); // Check error type if (error.name === "PirschDomainNotFoundApiError") { console.error("Domain not configured in dashboard"); } else if (error.name === "PirschInvalidAccessModeApiError") { console.error("Invalid authentication for this operation"); } else if (error.data.validation) { // Validation errors console.error("Validation errors:", error.data.validation); } else if (error.data.error) { // General errors error.data.error.forEach(msg => console.error(msg)); } // Specific status code handling switch (error.code) { case 401: console.error("Authentication failed - check credentials"); break; case 403: console.error("Access forbidden"); break; case 404: console.error("Resource not found"); break; case 429: console.error("Rate limit exceeded"); break; case 500: console.error("Server error"); break; } } else { console.error("Unexpected error:", error); } } } ``` -------------------------------- ### Analyze Time-Based Metrics with Pirsch JS SDK Source: https://context7.com/pirsch-analytics/pirsch-js-sdk/llms.txt This snippet demonstrates how to use the Pirsch JS SDK to fetch and analyze time-based metrics. It includes session duration, time on page, time-of-day patterns, and entry/exit page analysis. Requires `pirsch-sdk` and proper client initialization. ```javascript import { Pirsch } from "pirsch-sdk"; const client = new Pirsch({ hostname: "example.com", clientId: "your_client_id", clientSecret: "your_client_secret" }); async function analyzeTimeMetrics() { const filter = { id: "domain_id", from: new Date("2025-01-01"), to: new Date("2025-01-31"), path: "/blog", // optional include_avg_time_on_page: true }; try { // Session duration by day const sessionDuration = await client.sessionDuration(filter); sessionDuration.forEach(stat => { console.log(`${stat.day}: avg ${stat.average_time_spent_seconds}s on ${stat.path}`); }); // Time spent on specific pages const timeOnPage = await client.timeOnPage(filter); timeOnPage.forEach(stat => { const minutes = Math.floor(stat.average_time_spent_seconds / 60); console.log(`${stat.path}: ${minutes}m ${stat.average_time_spent_seconds % 60}s`); console.log(` Title: ${stat.title}`); }); // Time of day patterns (hourly breakdown) const hourlyStats = await client.timeOfDay(filter); hourlyStats.forEach(stat => { console.log(`Hour ${stat.hour}:00 - ${stat.visitors} visitors, ${stat.views} views`); console.log(` Bounce Rate: ${stat.bounce_rate}%`); }); // Entry and exit page analysis const entryPages = await client.entryPages(filter); entryPages.forEach(entry => { console.log(`Entry: ${entry.path}`); console.log(` ${entry.entries} entries, ${entry.entry_rate}% entry rate`); console.log(` Avg time: ${entry.average_time_spent_seconds}s`); }); const exitPages = await client.exitPages(filter); exitPages.forEach(exit => { console.log(`Exit: ${exit.exit_path} - ${exit.exit_rate}% exit rate`); }); } catch (error) { console.error("Time analysis error:", error.message); } } ``` -------------------------------- ### Server-Side Hit Tracking with Pirsch SDK (Node.js) Source: https://github.com/pirsch-analytics/pirsch-js-sdk/blob/master/README.md This snippet demonstrates how to configure and use the Pirsch SDK in a Node.js environment to track page views. It shows how to initialize the client with credentials and send a hit based on the incoming request, handling potential errors. ```javascript import { createServer } from "node:http"; import { URL } from "node:url"; // Import the Pirsch client. import { Pirsch } from "pirsch-sdk"; // Create a client with the hostname, client ID, and client secret you have configured on the Pirsch dashboard. const client = new Pirsch({ hostname: "example.com", protocol: "http", // used to parse the request URL, default is https clientId: "", clientSecret: "" }); // Create your http handler and start the server. createServer((request, response) => { // In this example, we only want to track the / path and nothing else. // We parse the request URL to read and check the pathname. const url = new URL(request.url || "", "http://localhost:8765"); if (url.pathname === "/") { // Send the hit to Pirsch. hitFromRequest is a helper function that returns all required information from the request. // You can also built the Hit object on your own and pass it in. client.hit(client.hitFromRequest(request)).catch(error => { // Something went wrong, check the error output. console.error(error); }); } // Render your website... response.write("Hello from Pirsch!"); response.end(); }).listen(8765); ``` -------------------------------- ### Analyze Growth Metrics and Tags with Pirsch JS SDK Source: https://context7.com/pirsch-analytics/pirsch-js-sdk/llms.txt This snippet shows how to utilize the Pirsch JS SDK for growth metrics and tag analytics. It enables comparison of performance across periods, analysis of custom tags, and retrieval of domain information. Requires `pirsch-sdk` and proper client initialization. ```javascript import { Pirsch } from "pirsch-sdk"; const client = new Pirsch({ hostname: "example.com", clientId: "your_client_id", clientSecret: "your_client_secret" }); async function analyzeGrowthAndTags() { const filter = { id: "domain_id", from: new Date("2025-01-01"), to: new Date("2025-01-31"), tag: "campaign" // optional: filter by tag key }; try { // Growth comparison (compares to previous period) const growth = await client.growth(filter); console.log("Growth metrics:"); console.log(` Visitors: ${growth.visitors_growth > 0 ? '+' : ''}${growth.visitors_growth}%`); console.log(` Views: ${growth.views_growth > 0 ? '+' : ''}${growth.views_growth}%`); console.log(` Sessions: ${growth.sessions_growth > 0 ? '+' : ''}${growth.sessions_growth}%`); console.log(` Bounces: ${growth.bounces_growth}%`); console.log(` Time Spent: ${growth.time_spent_growth}%`); console.log(` Conversion: ${growth.cr_growth}%`); // Tag key analysis const tagKeys = await client.tagKeys(filter); tagKeys.forEach(tag => { console.log(`Tag ${tag.key}=${tag.value}`); console.log(` ${tag.visitors} visitors, ${tag.views} views`); console.log(` ${tag.relative_visitors}% of traffic`); }); // Detailed tag breakdown filter.tag = "campaign"; const tags = await client.tags(filter); tags.forEach(tag => { console.log(`${tag.key}: ${tag.value} - ${tag.visitors} visitors`); }); // Get domain information const domain = await client.domain(); if (!(domain instanceof Error)) { console.log("Domain info:", { hostname: domain.hostname, timezone: domain.timezone, public: domain.public, display_name: domain.display_name }); } } catch (error) { console.error("Analysis error:", error.message); } } ``` -------------------------------- ### Client-Side Tracking with Pirsch SDK (Browser) Source: https://github.com/pirsch-analytics/pirsch-js-sdk/blob/master/README.md This snippet shows how to use the Pirsch SDK in a web browser to track page views and custom events. It initializes the client with an identification code and demonstrates sending a basic hit and a custom event with associated data. ```javascript // Import the Pirsch client. import { Pirsch } from "pirsch-sdk/web"; // Create a client with the identification code you have configured on the Pirsch dashboard. const client = new Pirsch({ identificationCode: "" }); const main = async () => { await client.hit(); await client.event("test-event", 60, { clicks: 1, test: "xyz" }); } void main(); ``` -------------------------------- ### Analyze Conversion Funnels with Pirsch JS SDK Source: https://context7.com/pirsch-analytics/pirsch-js-sdk/llms.txt This snippet demonstrates how to create and analyze conversion funnels using the Pirsch JS SDK. It includes listing available funnels and retrieving detailed statistics for a specific funnel. Dependencies include the 'pirsch-sdk'. It takes date filters and optional funnel IDs as input and outputs funnel names, step details, and visitor counts. ```javascript import { Pirsch } from "pirsch-sdk"; const client = new Pirsch({ hostname: "example.com", clientId: "your_client_id", clientSecret: "your_client_secret" }); async function analyzeFunnels() { const filter = { id: "domain_id", from: new Date("2025-01-01"), to: new Date("2025-01-31"), funnel_id: "funnel_uuid" // optional: specific funnel }; try { // List all funnels for domain const funnels = await client.listFunnel(filter); funnels.forEach(funnel => { console.log(`Funnel: ${funnel.name} (${funnel.id})`); console.log(` Steps: ${funnel.steps.length}`); funnel.steps.forEach(step => { console.log(` ${step.step}. ${step.name}`); }); }); // Get funnel statistics filter.funnel_id = "your_funnel_uuid"; const funnelData = await client.funnel(filter); funnelData.forEach(result => { console.log(` Funnel: ${result.definition.name}`); result.data.forEach(step => { console.log(` Step ${step.step}:`); console.log(` Visitors: ${step.visitors}`); console.log(` Relative: ${step.relative_visitors}%`); console.log(` From previous: ${step.previous_visitors}`); console.log(` Dropped: ${step.dropped}`); console.log(` Drop-off rate: ${step.drop_off}%`); }); }); } catch (error) { console.error("Funnel analysis error:", error.message); } } ``` -------------------------------- ### Batch Tracking with Pirsch JS SDK Source: https://context7.com/pirsch-analytics/pirsch-js-sdk/llms.txt Send multiple hits, events, or sessions in a single API call using the Pirsch JS SDK. This method is ideal for high-volume applications to reduce overhead. It requires a hostname, clientId, and clientSecret for initialization. ```javascript import { Pirsch } from "pirsch-sdk"; const client = new Pirsch({ hostname: "analytics.example.com", clientId: "your_client_id", clientSecret: "your_client_secret" }); async function batchTrackData() { const now = new Date().toISOString(); // Batch hits try { await client.batchHits([ { url: "https://example.com/page1", ip: "192.168.1.100", user_agent: "Mozilla/5.0...", accept_language: "en-US,en;q=0.9", time: now, tags: { campaign: "summer_sale", source: "email" } }, { url: "https://example.com/page2", ip: "192.168.1.101", user_agent: "Mozilla/5.0...", time: now } ]); // Batch events await client.batchEvents([ { name: "video_watch", hit: { url: "https://example.com/video", ip: "192.168.1.100", user_agent: "Mozilla/5.0..." }, time: now, duration: 120, meta: { video_id: "abc123", quality: "1080p" } } ]); // Batch sessions to keep them alive await client.batchSessions([ { ip: "192.168.1.100", user_agent: "Mozilla/5.0...", time: now } ]); console.log("Batch tracking completed"); } catch (error) { console.error("Batch error:", error.message); } } ``` -------------------------------- ### Analyze Traffic Sources with Pirsch JS SDK Source: https://context7.com/pirsch-analytics/pirsch-js-sdk/llms.txt This snippet shows how to analyze traffic sources, UTM parameters, and referral data using the Pirsch JavaScript SDK. It allows filtering by UTM campaign and date range, and retrieves data on UTM sources, mediums, campaigns, referrers, and their associated metrics. Requires the 'pirsch-sdk' package. ```javascript import { Pirsch } from "pirsch-sdk"; const client = new Pirsch({ hostname: "example.com", clientId: "your_client_id", clientSecret: "your_client_secret" }); async function analyzeTrafficSources() { const filter = { id: "domain_id", from: new Date("2025-01-01"), to: new Date("2025-01-31"), utm_campaign: "summer_sale", // optional filter limit: 50 }; try { // UTM parameter analysis const utmSources = await client.utmSource(filter); utmSources.forEach(s => { console.log(`Source ${s.utm_source}: ${s.visitors} visitors (${s.relative_visitors}%)`); }); const utmMediums = await client.utmMedium(filter); const utmCampaigns = await client.utmCampaign(filter); const utmContent = await client.utmContent(filter); const utmTerms = await client.utmTerm(filter); // Referrer analysis const referrers = await client.referrer(filter); referrers.forEach(ref => { console.log(`Referrer: ${ref.referrer_name || ref.referrer}`); console.log(` Visitors: ${ref.visitors}, Sessions: ${ref.sessions}`); console.log(` Bounce Rate: ${ref.bounce_rate}%`); if (ref.referrer_icon) { console.log(` Icon: ${ref.referrer_icon}`); } }); } catch (error) { console.error("Traffic analysis error:", error.message); } } ``` -------------------------------- ### Fetch Geographic and Device Analytics with Pirsch JS SDK Source: https://context7.com/pirsch-analytics/pirsch-js-sdk/llms.txt Retrieves geographic data (countries, regions, cities) and device/browser statistics (browsers, OS, platforms, screen classes, languages). Utilizes the Pirsch JS SDK with OAuth credentials and accepts filters for date range and limits. Outputs are iterated and logged to the console. ```javascript import { Pirsch } from "pirsch-sdk"; const client = new Pirsch({ hostname: "example.com", clientId: "your_client_id", clientSecret: "your_client_secret" }); async function getGeoAndDeviceData() { const filter = { id: "domain_id", from: new Date("2025-01-01"), to: new Date("2025-01-31"), limit: 20 }; try { // Geographic data const countries = await client.country(filter); countries.forEach(c => { console.log(`${c.country_code}: ${c.visitors} visitors (${c.relative_visitors}%)`); }); const regions = await client.region(filter); const cities = await client.city(filter); // Device and browser data const browsers = await client.browser(filter); browsers.forEach(b => { console.log(`${b.browser}: ${b.visitors} visitors`); }); const browserVersions = await client.browserVersions(filter); const os = await client.os(filter); const osVersions = await client.osVersions(filter); // Platform breakdown const platforms = await client.platform(filter); console.log("Platform stats:", { desktop: platforms.platform_desktop, mobile: platforms.platform_mobile, unknown: platforms.platform_unknown }); // Screen classes const screens = await client.screen(filter); screens.forEach(s => { console.log(`${s.screen_class}: ${s.visitors} visitors`); }); // Languages const languages = await client.languages(filter); languages.forEach(l => { console.log(`${l.language}: ${l.visitors} visitors`); }); } catch (error) { console.error("Error fetching data:", error.message); } } ``` -------------------------------- ### Retrieve Visitor Statistics with Pirsch JS SDK Source: https://context7.com/pirsch-analytics/pirsch-js-sdk/llms.txt Fetches visitor statistics such as total visitors, page views, sessions, bounce rate, and real-time active visitors. Requires OAuth credentials and accepts various filter parameters like date range, scale, timezone, path, limit, and offset. Outputs include summary statistics and time-series data. ```javascript import { Pirsch } from "pirsch-sdk"; const client = new Pirsch({ hostname: "example.com", clientId: "your_client_id", clientSecret: "your_client_secret" }); async function getAnalytics() { const filter = { id: "domain_id_from_dashboard", from: new Date("2025-01-01"), to: new Date("2025-01-31"), scale: "day", // "day", "week", "month", "year" tz: "America/New_York", // optional timezone path: "/blog", // optional filter by path limit: 10, // optional limit results offset: 0 // optional pagination }; try { // Get total visitors summary const total = await client.totalVisitors(filter); console.log("Total stats:", { visitors: total.visitors, views: total.views, sessions: total.sessions, bounce_rate: total.bounce_rate, conversion_rate: total.cr }); // Get time-series visitor data const visitors = await client.visitors(filter); visitors.forEach(stat => { console.log(`${stat.day}: ${stat.visitors} visitors, ${stat.views} views`); }); // Get page statistics const pages = await client.pages(filter); pages.forEach(page => { console.log(`${page.path} - ${page.visitors} visitors, ${page.bounce_rate}% bounce`); }); // Get active visitors (real-time) const active = await client.activeVisitors(filter); console.log(`Active visitors: ${active.visitors}`); active.stats.forEach(page => { console.log(` ${page.path}: ${page.visitors} active`); }); } catch (error) { if (error.name === "PirschInvalidAccessModeApiError") { console.error("Cannot access statistics with access token, use OAuth"); } else { console.error("Analytics error:", error.message); } } } ``` -------------------------------- ### Analyze Custom Events and Conversions with Pirsch JS SDK Source: https://context7.com/pirsch-analytics/pirsch-js-sdk/llms.txt This snippet demonstrates how to track and analyze custom events, conversion goals, and user behavior using the Pirsch JavaScript SDK. It includes filtering by date, event type, and metadata, and retrieving data on events, pages, and conversion goals. Requires the 'pirsch-sdk' package. ```javascript import { Pirsch } from "pirsch-sdk"; const client = new Pirsch({ hostname: "example.com", clientId: "your_client_id", clientSecret: "your_client_secret" }); async function analyzeConversions() { const filter = { id: "domain_id", from: new Date("2025-01-01"), to: new Date("2025-01-31"), event: "purchase", // optional: filter by specific event event_meta: { plan: "premium" } // optional: filter by metadata }; try { // Get all custom events const events = await client.events(filter); events.forEach(event => { console.log(`Event: ${event.name}`); console.log(` Visitors: ${event.visitors}, Views: ${event.views}`); console.log(` Conversion Rate: ${event.cr}%`); console.log(` Avg Duration: ${event.average_duration_seconds}s`); console.log(` Metadata keys: ${event.meta_keys.join(", ")}`); }); // Get event list with full metadata const eventList = await client.listEvents(filter); eventList.forEach(e => { console.log(`${e.name}: ${e.count} times, ${e.visitors} unique visitors`); console.log(` Meta:`, e.meta); }); // Get event-specific metadata breakdown filter.event = "purchase"; filter.event_meta_key = "plan"; const eventMeta = await client.eventMetadata(filter); // Get pages where event occurred const eventPages = await client.eventPages(filter); eventPages.forEach(page => { console.log(`${page.path}: ${page.visitors} triggered event`); }); // Get conversion goals const goals = await client.conversionGoals(filter); goals.forEach(goal => { console.log(`Goal: ${goal.name}`); console.log(` Pattern: ${goal.path_pattern}`); console.log(` Visitor Goal: ${goal.visitor_goal}`); }); } catch (error) { console.error("Conversion analysis error:", error.message); } } ``` -------------------------------- ### Browser-Based Tracking with Pirsch JS SDK Source: https://context7.com/pirsch-analytics/pirsch-js-sdk/llms.txt Track page views and custom events directly from the browser using the Pirsch JS SDK's web client. Initialization requires an identification code, which is safe for browser use. Optional parameters include baseUrl and timeout. ```javascript // Import browser-specific client import { Pirsch } from "pirsch-sdk/web"; // Initialize with identification code (public, safe for browser) const client = new Pirsch({ identificationCode: "your_32_character_identification_code", baseUrl: "https://api.pirsch.io", // optional timeout: 5000 // optional }); async function trackPageAndEvents() { try { // Track page view with automatic data collection await client.hit(); // Track with custom data await client.hit({ url: "https://example.com/custom-url", title: "Custom Page Title", tags: { user_type: "premium", ab_test: "variant_b" } }); // Track custom event (uses sendBeacon API) await client.event( "purchase_completed", 0, // duration { order_id: "ORD-12345", amount: 99.99, currency: "USD", items: 3 } ); // Get automatically collected hit data const autoHitData = client.hitFromBrowser(); console.log("Auto-collected data:", autoHitData); // { // url: "https://example.com/page", // title: "Page Title", // referrer: "https://google.com", // screen_width: 1920, // screen_height: 1080 // } } catch (error) { console.error("Tracking failed:", error.message); } } // Track on page load trackPageAndEvents(); ``` -------------------------------- ### Track Server-Side Page Views with Node.js SDK Source: https://context7.com/pirsch-analytics/pirsch-js-sdk/llms.txt This snippet demonstrates how to track page views from a Node.js application using the Pirsch SDK. It requires client ID and secret for authentication and uses a Node.js HTTP server to capture requests and send them to Pirsch Analytics. Dependencies include the 'pirsch-sdk' and built-in Node.js modules 'node:http' and 'node:url'. ```javascript import { createServer } from "node:http"; import { URL } from "node:url"; import { Pirsch } from "pirsch-sdk"; // Initialize client with OAuth credentials const client = new Pirsch({ hostname: "example.com", protocol: "https", clientId: "your_32_character_client_id_here", clientSecret: "your_64_character_client_secret_or_access_key", baseUrl: "https://api.pirsch.io", // optional, default shown timeout: 5000, // optional, in milliseconds trustedProxyHeaders: ["cf-connecting-ip", "x-forwarded-for"] // optional }); // Create HTTP servercreateServer((request, response) => { const url = new URL(request.url || "", "https://example.com"); if (url.pathname === "/" || url.pathname.startsWith("/blog")) { // Track the page view using helper method client.hit(client.hitFromRequest(request)) .then(() => { console.log("Hit tracked successfully"); }) .catch(error => { console.error("Tracking error:", error.code, error.message); }); } response.writeHead(200, { "Content-Type": "text/html" }); response.end("Hello World"); }).listen(8080); ``` -------------------------------- ### Track Server-Side Custom Events with Node.js SDK Source: https://context7.com/pirsch-analytics/pirsch-js-sdk/llms.txt This code snippet illustrates how to track custom events from a Node.js application using the Pirsch SDK. It allows sending event names, associated hit data, duration, and custom metadata for detailed user interaction analysis. Authentication is handled via client ID and secret. Error handling for authentication and other issues is included. ```javascript import { Pirsch } from "pirsch-sdk"; const client = new Pirsch({ hostname: "example.com", clientId: "your_client_id", clientSecret: "your_client_secret" }); async function trackUserAction(request) { const hitData = client.hitFromRequest(request); try { // Track event with name, hit data, duration, and metadata await client.event( "button_click", hitData, 150, // duration in seconds { button_id: "checkout", product_count: 3, total_value: 129.99, user_tier: "premium" } ); console.log("Event tracked successfully"); } catch (error) { if (error.code === 401) { console.error("Authentication failed"); } else { console.error("Error:", error.message); } } } ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.