### Install Bento Provider SDK Source: https://analytics.stacksee.com/docs/quick-start Installs the server-side SDK for Bento analytics. The client-side integration for Bento does not require a separate installation as it uses a CDN. ```bash # Client-side: No installation needed (uses CDN) # Server-side: pnpm install @bentonow/bento-node-sdk ``` -------------------------------- ### Client-Side Analytics Setup with Bento Source: https://analytics.stacksee.com/docs/quick-start Initializes the client-side analytics instance with the Bento provider, excluding the 'pageView' event by default as it's not supported. This setup requires your Bento site UUID and enables debug mode in development. ```typescript import { createClientAnalytics } from '@stacksee/analytics/client'; import { BentoClientProvider } from '@stacksee/analytics/providers/client'; import type { AppEvents } from './events'; export const analytics = createClientAnalytics({ providers: [ // Bento doesn't support anonymous page views - exclude by default { provider: new BentoClientProvider({ siteUuid: 'your-bento-site-uuid' }), exclude: ['pageView'] } ], debug: import.meta.env.DEV }); ``` -------------------------------- ### Client-Side Analytics Setup with PostHog Source: https://analytics.stacksee.com/docs/quick-start Initializes the client-side analytics instance using @stacksee/analytics with the PostHog provider. This setup requires your PostHog API token and host, and enables debug mode in development environments. ```typescript import { createClientAnalytics } from '@stacksee/analytics/client'; import { PostHogClientProvider } from '@stacksee/analytics/providers/client'; import type { AppEvents } from './events'; export const analytics = createClientAnalytics({ providers: [ new PostHogClientProvider({ token: 'your-posthog-api-key', api_host: 'https://app.posthog.com' }) ], debug: import.meta.env.DEV }); ``` -------------------------------- ### Client-Side Analytics Setup with Pirsch Source: https://analytics.stacksee.com/docs/quick-start Initializes the client-side analytics instance with the Pirsch provider. This setup requires your Pirsch identification code and hostname, and enables debug mode in development environments. ```typescript import { createClientAnalytics } from '@stacksee/analytics/client'; import { PirschClientProvider } from '@stacksee/analytics/providers/client'; import type { AppEvents } from './events'; export const analytics = createClientAnalytics({ providers: [ new PirschClientProvider({ identificationCode: 'your-pirsch-identification-code', hostname: 'example.com' }) ], debug: import.meta.env.DEV }); ``` -------------------------------- ### Install Analytics Provider SDKs (npm) Source: https://analytics.stacksee.com/docs/installation Installs SDKs for various analytics providers like PostHog, Bento, and Pirsch. You can install them individually or all at once. ```bash npm install posthog-js posthog-node npm install @bentonow/bento-node-sdk npm install pirsch-sdk ``` ```bash # Install SDKs for all providers you want to use npm install posthog-js posthog-node @bentonow/bento-node-sdk pirsch-sdk ``` -------------------------------- ### Install @stacksee/analytics with Different Package Managers Source: https://analytics.stacksee.com/docs/installation Demonstrates how to install the core @stacksee/analytics library using various package managers including npm, pnpm, yarn, and bun. ```bash npm install @stacksee/analytics ``` ```bash pnpm install @stacksee/analytics ``` ```bash yarn add @stacksee/analytics ``` ```bash bun add @stacksee/analytics ``` -------------------------------- ### Install Stacksee Analytics and Provider SDKs Source: https://analytics.stacksee.com/docs/installation Installs the core Stacksee Analytics library along with specific provider SDKs like PostHog and Bento. This command ensures all necessary packages are available for analytics tracking. ```bash # Example: PostHog SDK not found npm install posthog-js posthog-node # Example: Bento SDK not found npm install @bentonow/bento-node-sdk ``` -------------------------------- ### Install Core @stacksee/analytics Library (npm) Source: https://analytics.stacksee.com/docs/installation Installs the main @stacksee/analytics library using npm. This library is zero-dependency and handles core analytics logic. ```bash npm install @stacksee/analytics ``` -------------------------------- ### Verify @stacksee/analytics Installation (npm) Source: https://analytics.stacksee.com/docs/installation Checks if the @stacksee/analytics package is correctly installed in your project's node_modules directory using the npm list command. ```bash npm list @stacksee/analytics ``` -------------------------------- ### Install Bento Node.js SDK Source: https://analytics.stacksee.com/docs/providers Installs the Bento Node.js SDK for server-side integration. Client-side integration uses a CDN and requires no installation. ```bash # Client: No installation (uses CDN) # Server: pnpm install @bentonow/bento-node-sdk ``` -------------------------------- ### Client-Side Environment Variables for Next.js Source: https://analytics.stacksee.com/docs/installation Sets up client-side environment variables for Next.js applications. Keys prefixed with `NEXT_PUBLIC_` are exposed to the browser. Access them via `process.env`. ```bash .env.local NEXT_PUBLIC_POSTHOG_KEY=your-posthog-api-key NEXT_PUBLIC_BENTO_SITE_UUID=your-bento-site-uuid NEXT_PUBLIC_PIRSCH_CODE=your-pirsch-code ``` ```typescript const analytics = createClientAnalytics({ providers: [ new PostHogClientProvider({ token: process.env.NEXT_PUBLIC_POSTHOG_KEY }) ] }); ``` -------------------------------- ### Install PostHog SDK (npm) Source: https://analytics.stacksee.com/docs/your-first-event Installs the PostHog JavaScript SDK using npm. This is the first step to integrating PostHog as an analytics provider. ```bash npm install posthog-js ``` -------------------------------- ### Track Events with Type Safety Source: https://analytics.stacksee.com/docs/quick-start Demonstrates how to track events using the initialized analytics instance. This example shows tracking a 'button_clicked' event with specific properties, leveraging the type safety defined in `appEvents` for autocompletion and error prevention. ```typescript import { analytics } from '@/lib/analytics'; export function SignupButton() { const handleClick = () => { // Full type safety - autocomplete works! analytics.track('button_clicked', { buttonId: 'signup-cta', location: 'hero' }); }; return ; } ``` -------------------------------- ### Install EmitKit Server SDK Source: https://analytics.stacksee.com/docs/providers Installs the EmitKit Node.js SDK for server-side event notifications and activity feeds. ```bash # Server-only: pnpm install @emitkit/js ``` -------------------------------- ### Track Server Events Source: https://analytics.stacksee.com/docs/quick-start Demonstrates tracking a 'user_signed_up' event on the server-side, including user context and properties. It also shows the necessary shutdown call for serverless environments. ```typescript import { serverAnalytics } from '@/lib/server-analytics'; export async function POST(req: Request) { const body = await req.json(); // Track with user context await serverAnalytics.track('user_signed_up', { email: body.email, plan: body.plan, referralSource: 'landing-page' }, { userId: body.userId, user: { email: body.email, traits: { plan: body.plan } } }); // Important: Always shutdown in serverless environments await serverAnalytics.shutdown(); return new Response('OK'); } ``` -------------------------------- ### Initialize Client Analytics with Multiple Providers Source: https://analytics.stacksee.com/docs/quick-start Sets up client-side analytics using both PostHog and Bento providers. Bento events are configured to exclude 'pageView'. Requires VITE_POSTHOG_KEY and VITE_BENTO_SITE_UUID environment variables. ```typescript import { createClientAnalytics } from '@stacksee/analytics/client'; import { PostHogClientProvider, BentoClientProvider } from '@stacksee/analytics/providers/client'; export const analytics = createClientAnalytics({ providers: [ // Product analytics with PostHog (all events) new PostHogClientProvider({ token: import.meta.env.VITE_POSTHOG_KEY! }), // Email marketing with Bento (exclude anonymous page views) { provider: new BentoClientProvider({ siteUuid: import.meta.env.VITE_BENTO_SITE_UUID! }), exclude: ['pageView'] } ] }); // One call, all providers receive the event analytics.track('user_signed_up', { email: 'user@example.com', plan: 'pro' }); ``` -------------------------------- ### Client-Side Environment Variables for Create React App Source: https://analytics.stacksee.com/docs/installation Sets up client-side environment variables for Create React App. Variables prefixed with `REACT_APP_` are embedded during the build process and accessed via `process.env`. ```bash .env.local REACT_APP_POSTHOG_KEY=your-posthog-api-key REACT_APP_BENTO_SITE_UUID=your-bento-site-uuid REACT_APP_PIRSCH_CODE=your-pirsch-code ``` ```typescript const analytics = createClientAnalytics({ providers: [ new PostHogClientProvider({ token: process.env.REACT_APP_POSTHOG_KEY }) ] }); ``` -------------------------------- ### Install Pirsch SDK (npm) Source: https://analytics.stacksee.com/docs/your-first-event Installs the Pirsch analytics SDK using npm. This is a prerequisite for using Pirsch as an analytics provider. ```bash npm install pirsch-sdk ``` -------------------------------- ### Initialize Server Analytics with Bento Source: https://analytics.stacksee.com/docs/quick-start Configures server-side analytics with the Bento provider, excluding 'pageView' events by default. Requires BENTO_SITE_UUID, BENTO_PUBLISHABLE_KEY, and BENTO_SECRET_KEY environment variables. ```typescript import { createServerAnalytics } from '@stacksee/analytics/server'; import { BentoServerProvider } from '@stacksee/analytics/providers/server'; import type { AppEvents } from './events'; export const serverAnalytics = createServerAnalytics({ providers: [ // Bento doesn't support anonymous page views - exclude by default { provider: new BentoServerProvider({ siteUuid: process.env.BENTO_SITE_UUID!, authentication: { publishableKey: process.env.BENTO_PUBLISHABLE_KEY!, secretKey: process.env.BENTO_SECRET_KEY! } }), exclude: ['pageView'] } ], debug: process.env.NODE_ENV === 'development' }); ``` -------------------------------- ### Initialize Server Analytics with PostHog Source: https://analytics.stacksee.com/docs/quick-start Sets up server-side analytics using the PostHog provider. It requires POSTHOG_API_KEY and POSTHOG_HOST environment variables. Debugging is enabled in development environments. ```typescript import { createServerAnalytics } from '@stacksee/analytics/server'; import { PostHogServerProvider } from '@stacksee/analytics/providers/server'; import type { AppEvents } from './events'; export const serverAnalytics = createServerAnalytics({ providers: [ new PostHogServerProvider({ apiKey: process.env.POSTHOG_API_KEY!, host: process.env.POSTHOG_HOST }) ], debug: process.env.NODE_ENV === 'development' }); ``` -------------------------------- ### Client-Side Environment Variables for SvelteKit Source: https://analytics.stacksee.com/docs/installation Configures client-side environment variables for SvelteKit projects. Public variables are prefixed with `PUBLIC_` and accessed via `$env/static/public`. ```bash .env PUBLIC_POSTHOG_KEY=your-posthog-api-key PUBLIC_BENTO_SITE_UUID=your-bento-site-uuid PUBLIC_PIRSCH_CODE=your-pirsch-code ``` ```typescript import { PUBLIC_POSTHOG_KEY } from '$env/static/public'; const analytics = createClientAnalytics({ providers: [ new PostHogClientProvider({ token: PUBLIC_POSTHOG_KEY }) ] }); ``` -------------------------------- ### Import Client Analytics in TypeScript Source: https://analytics.stacksee.com/docs/installation Shows how to import the `createClientAnalytics` function in TypeScript. Full autocomplete and type checking are available automatically due to the library's TypeScript nature. ```typescript // Types work automatically import { createClientAnalytics } from '@stacksee/analytics/client'; // ↑ Full autocomplete and type checking ``` -------------------------------- ### Complete EmitKit Configuration Example in JavaScript Source: https://analytics.stacksee.com/docs/providers/emitkit Demonstrates combining category-based channel mapping and per-event channel overrides for comprehensive event routing. Includes fallback to a default channel when no mapping applies. ```javascript const serverAnalytics = createServerAnalytics({ providers: [ new EmitKitServerProvider({ apiKey: process.env.EMITKIT_API_KEY!, channelName: 'general', // Fallback for unmapped categories categoryChannelMap: { 'user': 'user-activity', 'error': 'alerts', 'conversion': 'revenue' } }) ] }); // Goes to 'user-activity' (category mapping) await serverAnalytics.track('user_signed_up', { plan: 'pro' }); // Goes to 'alerts' (category mapping) await serverAnalytics.track('api_error', { endpoint: '/users' }); // Goes to 'critical-payments' (event override) await serverAnalytics.track('large_payment', { amount: 50000, __emitkit_channel: 'critical-payments' }); // Goes to 'general' (no mapping, uses default) await serverAnalytics.track('feature_flag_changed', { flag: 'beta' }); ``` -------------------------------- ### Client-Side Environment Variables for Vite Source: https://analytics.stacksee.com/docs/installation Configures client-side environment variables for Vite projects to store API keys for analytics providers. Access these variables using `import.meta.env`. ```bash .env.local VITE_POSTHOG_KEY=your-posthog-api-key VITE_BENTO_SITE_UUID=your-bento-site-uuid VITE_PIRSCH_IDENTIFICATION_CODE=your-pirsch-code ``` ```typescript const analytics = createClientAnalytics({ providers: [ new PostHogClientProvider({ token: import.meta.env.VITE_POSTHOG_KEY }) ] }); ``` -------------------------------- ### Install PostHog SDK Source: https://analytics.stacksee.com/docs/providers Installs the necessary PostHog JavaScript and Node.js SDKs for integration with StackSee Analytics. ```bash pnpm install posthog-js posthog-node ``` -------------------------------- ### Server-Side Environment Variables Configuration Source: https://analytics.stacksee.com/docs/installation Configures server-side environment variables for API keys. These should NOT be prefixed and must never be exposed to the client. Access them via `process.env`. ```bash .env.local # Server-only - NOT prefixed with PUBLIC_/NEXT_PUBLIC_/etc POSTHOG_API_KEY=your-posthog-api-key BENTO_SECRET_KEY=your-bento-secret-key PIRSCH_ACCESS_KEY=your-pirsch-access-key ``` ```typescript // Server-side code only const serverAnalytics = createServerAnalytics({ providers: [ new PostHogServerProvider({ apiKey: process.env.POSTHOG_API_KEY }) ] }); ``` -------------------------------- ### Initialize Server Analytics with Pirsch Source: https://analytics.stacksee.com/docs/quick-start Sets up server-side analytics using the Pirsch provider. It requires PIRSCH_HOSTNAME and PIRSCH_ACCESS_KEY environment variables. Debugging is enabled in development environments. ```typescript import { createServerAnalytics } from '@stacksee/analytics/server'; import { PirschServerProvider } from '@stacksee/analytics/providers/server'; import type { AppEvents } from './events'; export const serverAnalytics = createServerAnalytics({ providers: [ new PirschServerProvider({ hostname: process.env.PIRSCH_HOSTNAME!, clientSecret: process.env.PIRSCH_ACCESS_KEY! }) ], debug: process.env.NODE_ENV === 'development' }); ``` -------------------------------- ### Client-Side Analytics Setup with PostHog Source: https://analytics.stacksee.com/docs/core-concepts/client-vs-server Initializes the client-side analytics instance using the createClientAnalytics function. It configures the PostHogClientProvider with an API key from environment variables. This setup is for browser environments and handles user interactions and page views. ```typescript import { createClientAnalytics } from '@stacksee/analytics/client'; import { PostHogClientProvider } from '@stacksee/analytics/providers/client'; import type { AppEvents } from './events'; export const analytics = createClientAnalytics({ providers: [ new PostHogClientProvider({ token: import.meta.env.VITE_POSTHOG_KEY }) ] }); ``` -------------------------------- ### Create a Basic Custom Analytics Provider in TypeScript Source: https://analytics.stacksee.com/docs/providers/custom This example demonstrates how to create a custom analytics provider by extending the BaseAnalyticsProvider class from '@stacksee/analytics'. It includes methods for initialization, tracking events, identifying users, and handling page views. Ensure you have '@stacksee/analytics' installed as a dependency. ```typescript import { BaseAnalyticsProvider, BaseEvent, EventContext } from '@stacksee/analytics'; export class CustomProvider extends BaseAnalyticsProvider { name = 'CustomProvider'; private client?: any; constructor(config: { apiKey: string; debug?: boolean }) { super({ debug: config.debug }); // Store config } async initialize(): Promise { if (!this.isEnabled()) return; // Initialize your SDK this.log('Initialized successfully'); } track(event: BaseEvent, context?: EventContext): void { if (!this.isEnabled() || !this.client) return; // Send event to your service this.client.track(event.action, event.properties); this.log('Tracked event', { event }); } identify(userId: string, traits?: Record): void { if (!this.isEnabled() || !this.client) return; this.client.identify(userId, traits); this.log('Identified user', { userId, traits }); } pageView(properties?: Record, context?: EventContext): void { if (!this.isEnabled() || !this.client) return; this.client.page(properties); this.log('Tracked page view', { properties }); } reset(): void { if (!this.isEnabled() || !this.client) return; this.client.reset(); this.log('Reset user session'); } } ``` -------------------------------- ### Server-Side Analytics Setup with PostHog Source: https://analytics.stacksee.com/docs/core-concepts/client-vs-server Initializes the server-side analytics instance using createServerAnalytics. It configures the PostHogServerProvider with an API key from environment variables. This setup is for backend environments and requires explicit user context per event. ```typescript import { createServerAnalytics } from '@stacksee/analytics/server'; import { PostHogServerProvider } from '@stacksee/analytics/providers/server'; import type { AppEvents } from './events'; export const serverAnalytics = createServerAnalytics({ providers: [ new PostHogServerProvider({ apiKey: process.env.POSTHOG_API_KEY! }) ] }); ``` -------------------------------- ### Identify Users and Attach Context Source: https://analytics.stacksee.com/docs/quick-start Shows how to identify users and attach contextual information (like email and plan) to their events. Once identified, all subsequent events will automatically include this user context. ```typescript // After successful login analytics.identify('user-123', { email: 'user@example.com', plan: 'pro', name: 'John Doe' }); // All subsequent events automatically include this context analytics.track('feature_used', { featureName: 'export', userId: 'user-123' }); ``` -------------------------------- ### Configure Provider with Environment Variables Source: https://analytics.stacksee.com/docs/providers Demonstrates configuring analytics providers using environment variables, showing examples for Vite and Next.js. ```javascript new PostHogClientProvider({ token: import.meta.env.VITE_POSTHOG_KEY, // Vite // OR token: process.env.NEXT_PUBLIC_POSTHOG_KEY // Next.js }) ``` -------------------------------- ### Pirsch Provider Installation Source: https://analytics.stacksee.com/docs/providers/pirsch Install the Pirsch SDK using pnpm. ```APIDOC ## Pirsch Provider Installation ### Description Install the Pirsch SDK using your package manager. ### Method ```bash pnpm install pirsch-sdk ``` ### Endpoint N/A ### Parameters N/A ### Request Example N/A ### Response N/A ``` -------------------------------- ### Initialize Client Analytics with PostHog Provider (JavaScript) Source: https://analytics.stacksee.com/docs/core-concepts/providers Demonstrates how to create an analytics client instance and configure it with the PostHog client provider. This setup allows for tracking user events, which are then transformed and sent to PostHog servers by the provider. ```javascript import { createClientAnalytics } from '@stacksee/analytics/client'; import { PostHogClientProvider } from '@stacksee/analytics/providers/client'; const analytics = createClientAnalytics({ providers: [ new PostHogClientProvider({ token: 'xxx' }) ] }); // You call track() analytics.track('user_signed_up', { email: 'user@example.com' }); // Provider handles the rest: // 1. Transforms event to PostHog format // 2. Sends to PostHog servers // 3. Handles errors gracefully ``` -------------------------------- ### Install Pirsch SDK using pnpm Source: https://analytics.stacksee.com/docs/providers/pirsch Installs the Pirsch SDK package using the pnpm package manager. This is the first step to integrate Pirsch analytics into your project. ```bash pnpm install pirsch-sdk ``` -------------------------------- ### Install EmitKit Provider (Node.js) Source: https://analytics.stacksee.com/docs/providers/emitkit Installs the EmitKit JavaScript SDK for server-side analytics. This package is exclusively for server environments. ```bash pnpm install @emitkit/js ``` -------------------------------- ### Initialize Client Analytics in SvelteKit Source: https://analytics.stacksee.com/docs/guides Configures the client-side analytics instance for SvelteKit applications. It integrates with the PostHog client provider and uses the PUBLIC_POSTHOG_KEY from environment variables. ```typescript import { createClientAnalytics } from '@stacksee/analytics/client'; import { PostHogClientProvider } from '@stacksee/analytics/providers/client'; import { PUBLIC_POSTHOG_KEY } from '$env/static/public'; export const analytics = createClientAnalytics({ providers: [ new PostHogClientProvider({ token: PUBLIC_POSTHOG_KEY }) ] }); ``` -------------------------------- ### Install Analytics Provider SDKs (pnpm) Source: https://analytics.stacksee.com/docs Commands to install SDKs for popular analytics providers like PostHog, Bento, and Pirsch using pnpm. These are required to use specific analytics services with StackSee Analytics. ```bash # PostHog pnpm install posthog-js posthog-node # Bento pnpm install @bentonow/bento-node-sdk # Pirsch pnpm install pirsch-sdk ``` -------------------------------- ### Client-Side Tracking API Source: https://analytics.stacksee.com/docs/core-concepts/client-vs-server Documentation for the client-side analytics API, including setup, stateful user context, and fire-and-forget tracking. ```APIDOC ## Client-Side Tracking API ### Description Use client-side tracking for browser interactions, page views, user behavior, and client-side state changes. The client maintains user state across interactions. ### Setup ```javascript import { createClientAnalytics } from '@stacksee/analytics/client'; import { PostHogClientProvider } from '@stacksee/analytics/providers/client'; import type { AppEvents } from './events'; export const analytics = createClientAnalytics({ providers: [ new PostHogClientProvider({ token: import.meta.env.VITE_POSTHOG_KEY }) ] }); ``` ### Stateful User Context Identify the user once and subsequent events will automatically include their context. Reset the state on logout. **Identify User:** ```javascript analytics.identify('user-123', { email: 'user@example.com', name: 'John Doe', plan: 'pro' }); ``` **Track Event:** ```javascript analytics.track('button_clicked', { buttonId: 'checkout' }); // Providers receive: { userId: 'user-123', email: 'user@example.com', ... } ``` **Reset User:** ```javascript analytics.reset(); ``` ### Fire-and-Forget Tracking Client-side events are sent asynchronously without blocking user interactions, ensuring a responsive UI. ```javascript function handleClick() { // Don't await - events send in background analytics.track('button_clicked', { buttonId: 'cta' }); // User continues immediately navigateTo('/checkout'); } ``` ### Page Views Track page views manually or leverage automatic tracking provided by most frameworks. **Manual Page View:** ```javascript analytics.pageView({ path: window.location.pathname, title: document.title, referrer: document.referrer }); ``` ``` -------------------------------- ### Client Tracking Non-Blocking (JavaScript) Source: https://analytics.stacksee.com/docs/core-concepts/client-vs-server Demonstrates the 'fire and forget' approach for client-side analytics tracking. The 'Good' example shows tracking an event without awaiting it, allowing for immediate UI navigation. The 'Bad' example illustrates how awaiting client tracking can unnecessarily block the user interface. ```javascript // ✅ Good - fire and forget analytics.track('button_clicked', { id: 'cta' }); navigate('/checkout'); // ❌ Bad - blocks UI await analytics.track('button_clicked', { id: 'cta' }); navigate('/checkout'); // User waits for analytics! ``` -------------------------------- ### Server-Side Tracking API Source: https://analytics.stacksee.com/docs/core-concepts/client-vs-server Documentation for the server-side analytics API, including setup, stateless user context, and awaiting critical events. ```APIDOC ## Server-Side Tracking API ### Description Use server-side tracking for API endpoints, background jobs, server actions, sensitive data, and critical events where delivery must be guaranteed. The server is stateless, requiring user context to be passed with each event. ### Setup ```javascript import { createServerAnalytics } from '@stacksee/analytics/server'; import { PostHogServerProvider } from '@stacksee/analytics/providers/server'; import type { AppEvents } from './events'; export const serverAnalytics = createServerAnalytics({ providers: [ new PostHogServerProvider({ apiKey: process.env.POSTHOG_API_KEY! }) ] }); ``` ### Stateless User Context User context must be explicitly passed with each server-side event. **Track Event with User Context:** ```javascript await serverAnalytics.track('api_request', { endpoint: '/users', method: 'POST' }, { // Pass user info for this event only userId: 'user-123', user: { email: 'user@example.com', traits: { plan: 'pro', company: 'Acme Corp' } } }); ``` **Subsequent Request (Different User):** ```javascript await serverAnalytics.track('api_request', { endpoint: '/products', method: 'GET' }, { userId: 'user-456', // Different user user: { email: 'other@example.com' } }); ``` ### Await for Critical Events Server-side tracking calls should be awaited to ensure critical events are processed before proceeding. ```javascript export async function POST(req: Request) { const body = await req.json(); try { // Process payment const payment = await processPayment(body); // Await analytics to ensure it completes await serverAnalytics.track('payment_processed', { amount: payment.amount, transactionId: payment.id }, { userId: body.userId }); return Response.json({ success: true }); } catch (error) { // Track failure await serverAnalytics.track('payment_failed', { error: error.message }, { userId: body.userId }); return Response.json({ error: 'Payment failed' }, { status: 500 }); } finally { // IMPORTANT: Always shutdown server analytics await serverAnalytics.shutdown(); } } ``` ``` -------------------------------- ### Initialize Client Analytics in Next.js App Router Source: https://analytics.stacksee.com/docs/guides Sets up the client-side analytics instance for Next.js applications using the App Router. It utilizes the PostHog client provider and requires the NEXT_PUBLIC_POSTHOG_KEY environment variable. ```typescript import { createClientAnalytics } from '@stacksee/analytics/client'; import { PostHogClientProvider } from '@stacksee/analytics/providers/client'; export const analytics = createClientAnalytics({ providers: [ new PostHogClientProvider({ token: process.env.NEXT_PUBLIC_POSTHOG_KEY! }) ] }); ``` -------------------------------- ### Uninstall Stacksee Analytics and Provider SDKs Source: https://analytics.stacksee.com/docs/installation Removes the core Stacksee Analytics library and any installed provider SDKs from the project. This command ensures a clean removal of the analytics stack. ```bash # Remove core library npm uninstall @stacksee/analytics # Remove provider SDKs npm uninstall posthog-js posthog-node @bentonow/bento-node-sdk pirsch-sdk ``` -------------------------------- ### Upgrade Stacksee Analytics Source: https://analytics.stacksee.com/docs/installation Updates the Stacksee Analytics library to the latest version. It's recommended to check the changelog for any breaking changes before upgrading. ```bash npm install @stacksee/analytics@latest ``` -------------------------------- ### Client-Side and Server-Side Event Tracking Example (User Signup) Source: https://analytics.stacksee.com/docs/core-concepts/client-vs-server Demonstrates tracking a user signup event from both the client and server. The client tracks the 'signup_button_clicked' event to capture user interaction details like location, while the server tracks the 'user_signed_up' event with critical signup data like email and plan. This provides a comprehensive view of the user journey. ```javascript // Client-side: Track button click analytics.track('signup_button_clicked', { location: 'hero' }); // Server-side: Track actual signup await serverAnalytics.track('user_signed_up', { email: body.email, plan: body.plan }, { userId: newUser.id, user: { email: newUser.email } }); ``` -------------------------------- ### Configure TypeScript Module Resolution Source: https://analytics.stacksee.com/docs/installation Ensures TypeScript can correctly resolve modules, especially when using bundlers. This configuration is crucial for type safety and proper module loading in TypeScript projects. ```json { "compilerOptions": { "moduleResolution": "bundler", // or "node16" "esModuleInterop": true, "skipLibCheck": false } } ``` -------------------------------- ### Correct Import Path for Client Analytics Source: https://analytics.stacksee.com/docs/installation Illustrates the correct way to import client-side analytics functions from the @stacksee/analytics package. Incorrect import paths can lead to 'Module Not Found' errors. ```typescript // ✅ Correct import { createClientAnalytics } from '@stacksee/analytics/client'; // ❌ Wrong import { createClientAnalytics } from '@stacksee/analytics'; ``` -------------------------------- ### Server-Side Analytics Setup with Multiple Providers (JavaScript) Source: https://analytics.stacksee.com/docs/providers/emitkit Demonstrates how to create a server-side analytics instance using Stacksee, integrating multiple providers like PostHog and EmitKit. It shows how to configure providers individually and group them for centralized management. Dependencies include '@stacksee/analytics/server' and '@stacksee/analytics/providers/server'. ```javascript import { createServerAnalytics } from '@stacksee/analytics/server'; import { EmitKitServerProvider } from '@stacksee/analytics/providers/server'; import { PostHogServerProvider } from '@stacksee/analytics/providers/server'; const serverAnalytics = createServerAnalytics({ providers: [ // Use PostHog for analytics and dashboards new PostHogServerProvider({ apiKey: process.env.POSTHOG_API_KEY! }), // Use EmitKit for activity feeds and notifications { provider: new EmitKitServerProvider({ apiKey: process.env.EMITKIT_API_KEY!, channelName: 'user-activity', notify: true }), // Only send important events to EmitKit methods: ['track', 'identify'] } ] }); ``` -------------------------------- ### SvelteKit: Client-Side Page Component for Signup Source: https://analytics.stacksee.com/docs/core-concepts/client-vs-server A SvelteKit page component (`+page.svelte`) that initiates the signup process. It tracks a 'signup_button_clicked' event when the signup button is interacted with, noting the location ('hero'). Subsequently, it triggers a POST request to the server-side API route to complete the signup, where the server-side event is tracked. ```typescript ``` -------------------------------- ### Define Specific Union Types for Properties (TypeScript) Source: https://analytics.stacksee.com/docs/core-concepts/type-safety This example illustrates how to define specific union types for object properties in TypeScript. The 'good' example uses a union of literal strings ('free' | 'pro' | 'enterprise') for precise type checking. The 'bad' example uses a general `string`, which is too loose and allows any string value. ```typescript // ✅ Good - specific values properties: {} as { plan: 'free' | 'pro' | 'enterprise'; } // ❌ Bad - too loose properties: {} as { plan: string; } ``` -------------------------------- ### Troubleshooting: Environment Variables Source: https://analytics.stacksee.com/docs/guides/sveltekit This section provides guidance on correctly setting environment variables for client-side and server-side analytics. It highlights the importance of the `PUBLIC_` prefix for client-side variables. -------------------------------- ### Install StackSee Analytics Library (pnpm) Source: https://analytics.stacksee.com/docs Command to install the core @stacksee/analytics library using the pnpm package manager. This is the first step to integrating StackSee Analytics into your project. ```bash pnpm install @stacksee/analytics ``` -------------------------------- ### Analytics Instance Management (JavaScript) Source: https://analytics.stacksee.com/docs/core-concepts/client-vs-server Illustrates best practices for managing analytics client and server instances. It shows creating a single client instance for a session and creating new server instances per request or function, emphasizing the need for separate instances in different contexts. ```javascript // ✅ Client - one instance for the session // lib/analytics.ts export const analytics = createClientAnalytics({ /* ... */ }); // ✅ Server - new instance per request/function // Each API route creates its own instance export function createAnalytics() { return createServerAnalytics({ /* ... */ }); } ``` -------------------------------- ### Install @stacksee/analytics and PostHog Dependencies (npm) Source: https://analytics.stacksee.com/docs/guides/nextjs Installs the core StackSee analytics library and the PostHog SDKs for both client-side and server-side usage. This is the initial step for integrating analytics into your Next.js application. ```bash npm install @stacksee/analytics npm install posthog-js posthog-node ``` -------------------------------- ### Install StackSee Analytics and PostHog Dependencies Source: https://analytics.stacksee.com/docs/providers/posthog Installs the necessary packages for StackSee Analytics and PostHog integration using pnpm. This includes the core StackSee analytics library and the PostHog SDKs for both client-side and server-side. ```bash pnpm install @stacksee/analytics posthog-js posthog-node ``` -------------------------------- ### SvelteKit: Server-Side API Route for Signup Source: https://analytics.stacksee.com/docs/core-concepts/client-vs-server A SvelteKit server-side API route (`+server.ts`) that handles user signups. It tracks a 'user_signed_up' event, including the user's email and `userId`, and ensures `shutdown()` is called to flush events before sending a response. This is part of a complete signup flow involving both client and server tracking. ```typescript import { serverAnalytics } from '$lib/server-analytics'; import type { RequestHandler } from './$types'; export const POST: RequestHandler = async ({ request }) => { const body = await request.json(); // Track server-side await serverAnalytics.track('user_signed_up', { email: body.email }, { userId: body.userId }); await serverAnalytics.shutdown(); return new Response('OK'); }; ``` -------------------------------- ### Quick Example: Initialize and Track Events with StackSee Analytics (TypeScript) Source: https://analytics.stacksee.com/docs Demonstrates how to initialize the StackSee analytics client with a specific provider (PostHog) and track events with full type safety. It defines custom application events and shows how TypeScript enforces correct event names and properties. ```typescript import { createClientAnalytics } from '@stacksee/analytics/client'; import { PostHogClientProvider } from '@stacksee/analytics/providers/client'; // Define your events with full type safety const appEvents = { userSignedUp: { name: 'user_signed_up', category: 'user', properties: {} as { email: string; plan: 'free' | 'pro' | 'enterprise'; } } } as const; // Initialize with your providers const analytics = createClientAnalytics({ providers: [ new PostHogClientProvider({ token: 'your-key' }) ] }); // Track events with autocomplete and type checking analytics.track('user_signed_up', { email: 'user@example.com', plan: 'pro' // ✅ TypeScript knows this must be 'free' | 'pro' | 'enterprise' }); ``` -------------------------------- ### Server-Side: API Route Example for User Tracking Source: https://analytics.stacksee.com/docs/identifying-users This example shows how to track user-related events within an API route. It retrieves user information and then uses `serverAnalytics.track()` to send events with user context. This is essential for tracking user actions that originate from server-side operations. ```typescript import { serverAnalytics } from '@/lib/server-analytics'; export async function POST(req: Request) { const body = await req.json(); const user = await getCurrentUser(req); // Track with user context await serverAnalytics.track('user_created', { email: body.email }, { userId: user.id, user: { email: user.email, traits: { plan: user.plan, role: user.role } } }); await serverAnalytics.shutdown(); return Response.json({ success: true }); } ``` -------------------------------- ### Server Analytics Shutdown (JavaScript) Source: https://analytics.stacksee.com/docs/core-concepts/client-vs-server Highlights the importance of always shutting down server analytics instances to ensure all events are sent. The 'Good' example shows tracking an event followed by a shutdown, while the 'Bad' example demonstrates how omitting shutdown can lead to lost events when the function terminates. ```javascript // ✅ Good await serverAnalytics.track('event', {}); await serverAnalytics.shutdown(); // ❌ Bad - events may be lost await serverAnalytics.track('event', {}); // Function terminates before events are sent! ``` -------------------------------- ### Configure Bento Analytics Provider (TypeScript) Source: https://analytics.stacksee.com/docs/your-first-event Configures the analytics client to use Bento as the provider. This requires creating a `BentoClientProvider` instance with your site's UUID. The analytics instance is initialized with this provider. ```typescript import { createClientAnalytics } from '@stacksee/analytics/client'; import { BentoClientProvider } from '@stacksee/analytics/providers/client'; import type { appEvents } from './events'; export const analytics = createClientAnalytics({ providers: [ new BentoClientProvider({ siteUuid: 'your-bento-site-uuid' }) ] }); ``` -------------------------------- ### Server-Side User Context (JavaScript) Source: https://analytics.stacksee.com/docs/core-concepts/client-vs-server Explains how to pass user context explicitly when tracking events server-side. The 'Good' example shows providing `userId` and user details in the tracking options. The 'Bad' example illustrates the lack of user context when tracking without these options, making it difficult to attribute events. ```javascript // ✅ Good - explicit context await serverAnalytics.track('event', {}, { userId: 'user-123', user: { email: 'user@example.com' } }); // ❌ Bad - no user context await serverAnalytics.track('event', {}); // Who triggered this event? ``` -------------------------------- ### Automatic Initialization of Analytics Providers (JavaScript) Source: https://analytics.stacksee.com/docs/core-concepts/providers Demonstrates how StackSee Analytics automatically initializes providers when an analytics instance is created. It also shows how to explicitly call the `initialize()` method if manual control over the initialization timing is required. ```javascript const analytics = createClientAnalytics({ providers: [ new PostHogClientProvider({ token: 'xxx' }) ] }); // PostHogClientProvider.initialize() is called automatically await analytics.initialize(); ``` ```javascript const analytics = createClientAnalytics({ providers: [ new PostHogClientProvider({ token: 'xxx' }) ] }); // Initialize later await analytics.initialize(); ``` -------------------------------- ### Use `as const satisfies` for Literal Type Preservation (TypeScript) Source: https://analytics.stacksee.com/docs/core-concepts/type-safety This snippet demonstrates the recommended way to define event collections in TypeScript. Using `as const satisfies` ensures that literal types are preserved, preventing unintended type widening and maintaining precision. The 'good' example preserves specific literal types, while the 'bad' example loses this information. ```typescript // ✅ Good - preserves literal types export const appEvents = { /* ... */ } as const satisfies EventCollection>>; // ❌ Bad - loses type information export const appEvents = { /* ... */ }; ``` -------------------------------- ### Configure Pirsch Analytics Provider (TypeScript) Source: https://analytics.stacksee.com/docs/your-first-event Sets up the analytics client to use Pirsch as the provider. This involves instantiating `PirschClientProvider` with your identification code and hostname. The `createClientAnalytics` function initializes the analytics with this provider. ```typescript import { createClientAnalytics } from '@stacksee/analytics/client'; import { PirschClientProvider } from '@stacksee/analytics/providers/client'; import type { appEvents } from './events'; export const analytics = createClientAnalytics({ providers: [ new PirschClientProvider({ identificationCode: 'your-pirsch-code', hostname: 'example.com' }) ] }); ``` -------------------------------- ### Pirsch Client-Side Usage Source: https://analytics.stacksee.com/docs/providers/pirsch Initialize StackSee Analytics with the Pirsch client provider for client-side tracking. ```APIDOC ## Pirsch Client-Side Usage ### Description Initialize StackSee Analytics with the Pirsch client provider for client-side tracking. Ensure you replace 'your-pirsch-identification-code' and 'example.com' with your actual values. ### Method ```javascript import { createClientAnalytics } from '@stacksee/analytics/client'; import { PirschClientProvider } from '@stacksee/analytics/providers/client'; const analytics = createClientAnalytics({ providers: [ new PirschClientProvider({ identificationCode: 'your-pirsch-identification-code', hostname: 'example.com' }) ] }); await analytics.initialize(); ``` ### Endpoint N/A ### Parameters #### Request Body - **providers** (Array) - Required - An array containing an instance of PirschClientProvider. - **identificationCode** (string) - Required - Your Pirsch identification code. - **hostname** (string) - Required - The hostname of your website. ### Request Example ```json { "providers": [ { "identificationCode": "your-pirsch-identification-code", "hostname": "example.com" } ] } ``` ### Response #### Success Response (200) N/A (Initialization is asynchronous and does not return a value on success) #### Response Example N/A ``` -------------------------------- ### Pirsch Server-Side Context Requirements Source: https://analytics.stacksee.com/docs/providers/pirsch Important context requirements for the Pirsch server provider, including IP address and User-Agent. ```APIDOC ## Pirsch Server-Side Context Requirements ### Description The Pirsch server provider requires valid request context, specifically the IP address and User-Agent, to function correctly. Events without this context will be skipped. Ensure your proxy setup captures and enriches events with this information. ### Method N/A ### Endpoint N/A ### Parameters N/A ### Request Example N/A ### Response N/A ### Important Notes - Use the Proxy pattern to capture client requests. - Ensure your proxy handler enriches events with IP and User-Agent. - Refer to the Proxy Provider documentation for setup instructions. ``` -------------------------------- ### Create Client-Side Analytics Instance with PostHog Provider Source: https://analytics.stacksee.com/docs/guides/sveltekit Initializes the client-side analytics instance using StackSee's `createClientAnalytics`. It configures the PostHog client provider with public environment variables for the API key and host. Debug mode is enabled for development environments. ```typescript import { createClientAnalytics } from '@stacksee/analytics/client'; import { PostHogClientProvider } from '@stacksee/analytics/providers/client'; import { PUBLIC_POSTHOG_KEY, PUBLIC_POSTHOG_HOST } from '$env/static/public'; import type { AppEvents } from './events'; export const analytics = createClientAnalytics({ providers: [ new PostHogClientProvider({ token: PUBLIC_POSTHOG_KEY, api_host: PUBLIC_POSTHOG_HOST }) ], debug: import.meta.env.DEV }); ```