### Install Analytics Provider SDKs Source: https://github.com/stackseehq/analytics/blob/main/www/content/docs/quick-start.mdx Install additional SDKs for specific analytics providers like PostHog, Bento or Pirsch. Each provider has different installation requirements. ```bash pnpm install posthog-js posthog-node ``` ```bash # Client-side: No installation needed (uses CDN) # Server-side: pnpm install @bentonow/bento-node-sdk ``` ```bash pnpm install pirsch-sdk ``` -------------------------------- ### Initialize Client Analytics for Bento Source: https://github.com/stackseehq/analytics/blob/main/www/content/docs/quick-start.mdx Set up Bento as analytics provider on client-side using site UUID. No client-side installation required as it uses CDN. ```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' }) ], debug: import.meta.env.DEV }); ``` -------------------------------- ### Install PostHog and Bento Node SDKs Source: https://github.com/stackseehq/analytics/blob/main/www/content/docs/installation.mdx Commands to install necessary provider SDKs for @stacksee/analytics. This example shows how to install the PostHog Node.js SDK and the Bento Node.js SDK, which are required if you encounter errors related to these providers not loading. ```bash # Example: PostHog SDK not found npm install posthog-js posthog-node # Example: Bento SDK not found npm install @bentonow/bento-node-sdk ``` -------------------------------- ### Track Server Events (TypeScript) Source: https://github.com/stackseehq/analytics/blob/main/www/content/docs/quick-start.mdx Illustrates how to track server events using the initialized Stacksee Analytics. It includes examples of passing user context and ensures proper shutdown in 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'); } ``` -------------------------------- ### Install Stacksee Analytics and PostHog Dependencies Source: https://github.com/stackseehq/analytics/blob/main/www/content/docs/guides/sveltekit.mdx Installs the necessary @stacksee/analytics package and PostHog SDKs for both client-side and server-side tracking. Ensure you have Node.js and npm/yarn/pnpm installed. ```bash npm install @stacksee/analytics npm install posthog-js posthog-node ``` -------------------------------- ### Client Analytics Setup for Next.js Source: https://github.com/stackseehq/analytics/blob/main/www/content/docs/guides/index.mdx Initializes the client-side analytics instance for a Next.js application using the App Router. It configures the PostHog client provider with the necessary API key from environment variables. This setup is crucial for tracking page views and user interactions within the browser. ```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! }) ] }); ``` -------------------------------- ### Client Analytics Setup for SvelteKit Source: https://github.com/stackseehq/analytics/blob/main/www/content/docs/guides/index.mdx Configures the client-side analytics instance for a SvelteKit application. It leverages the PostHog client provider and retrieves the public PostHog API key from SvelteKit's environment variables. This enables tracking of user events and page views in SvelteKit applications. ```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 @stacksee/analytics Core Library (bun) Source: https://github.com/stackseehq/analytics/blob/main/www/content/docs/installation.mdx Installs the core @stacksee/analytics library using the bun package manager. ```bash bun add @stacksee/analytics ``` -------------------------------- ### Environment Variable Configuration for Analytics (Bash) Source: https://github.com/stackseehq/analytics/blob/main/www/content/docs/guides/sveltekit.mdx This is a configuration example showing the correct way to set environment variables for analytics tracking. It emphasizes the requirement for `PUBLIC_` prefix for client-side variables and no prefix for server-side variables, highlighting correct and incorrect examples. ```bash # ✅ Correct - client-side variables must have PUBLIC_ prefix PUBLIC_POSTHOG_KEY=xxx # ✅ Correct - server-side variables have no prefix POSTHOG_API_KEY=xxx # ❌ Wrong - missing PUBLIC_ prefix for client POSTHOG_KEY=xxx ``` -------------------------------- ### Vite Client-Side Environment Variables for Analytics Source: https://github.com/stackseehq/analytics/blob/main/www/content/docs/installation.mdx Sets up client-side environment variables in a Vite project for analytics API keys and provides an example of accessing them to configure analytics providers. ```bash 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 and Configure PostHog Analytics Provider Source: https://github.com/stackseehq/analytics/blob/main/www/content/docs/your-first-event.mdx Installs posthog-js package and configures StackSee client provider with API token and host. Requires credentials from PostHog dashboard. Replaces console logger to send events to PostHog cloud infrastructure. ```bash npm install posthog-js ``` ```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-key', api_host: 'https://app.posthog.com' }) ] }); ``` -------------------------------- ### Install Multiple Analytics Provider SDKs (npm) Source: https://github.com/stackseehq/analytics/blob/main/www/content/docs/installation.mdx Installs SDKs for multiple analytics providers simultaneously, allowing for combined usage of services like PostHog, Bento, and Pirsch. ```bash # Install SDKs for all providers you want to use npm install posthog-js posthog-node @bentonow/bento-node-sdk pirsch-sdk ``` -------------------------------- ### Install Provider SDKs (Bash) Source: https://github.com/stackseehq/analytics/blob/main/www/content/docs/index.mdx Provides installation commands for optional provider SDKs like PostHog, Bento, and Pirsch using pnpm. These are needed if you intend to use specific third-party 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 ``` -------------------------------- ### Install @stacksee/analytics Core Library (yarn) Source: https://github.com/stackseehq/analytics/blob/main/www/content/docs/installation.mdx Installs the core @stacksee/analytics library using the yarn package manager. ```bash yarn add @stacksee/analytics ``` -------------------------------- ### Initialize Client Analytics for Pirsch Source: https://github.com/stackseehq/analytics/blob/main/www/content/docs/quick-start.mdx Set up Pirsch as analytics provider on client-side with identification code and hostname configuration. ```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 }); ``` -------------------------------- ### Initialize Client Analytics for PostHog Source: https://github.com/stackseehq/analytics/blob/main/www/content/docs/quick-start.mdx Set up PostHog as analytics provider on client-side with API key and host configuration. Includes debug mode based on development environment. ```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 }); ``` -------------------------------- ### Install Bento Analytics Node SDK (npm) Source: https://github.com/stackseehq/analytics/blob/main/www/content/docs/installation.mdx Installs the server-side Node.js SDK for Bento, an email marketing and automation platform with event tracking. The client-side integration uses a CDN and requires no installation. ```bash # Server-side only: npm install @bentonow/bento-node-sdk ``` -------------------------------- ### Verify @stacksee/analytics Installation (npm) Source: https://github.com/stackseehq/analytics/blob/main/www/content/docs/installation.mdx Verifies that the @stacksee/analytics package is installed correctly in your project by listing installed packages. ```bash npm list @stacksee/analytics ``` -------------------------------- ### Install @stacksee/analytics (Bash) Source: https://github.com/stackseehq/analytics/blob/main/www/content/docs/index.mdx Shows the command to install the core @stacksee/analytics library using the pnpm package manager. This is the first step in integrating the analytics library into a project. ```bash pnpm install @stacksee/analytics ``` -------------------------------- ### Install and Configure Pirsch Analytics Provider Source: https://github.com/stackseehq/analytics/blob/main/www/content/docs/your-first-event.mdx Installs pirsch-sdk package and configures client provider with identification code and hostname. Requires credentials from Pirsch dashboard. Enables privacy-focused analytics tracking with EU compliance. ```bash npm install pirsch-sdk ``` ```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' }) ] }); ``` -------------------------------- ### Install @stacksee/analytics Core Library (npm) Source: https://github.com/stackseehq/analytics/blob/main/www/content/docs/installation.mdx Installs the core @stacksee/analytics library, which handles analytics logic without external dependencies. ```bash npm install @stacksee/analytics ``` -------------------------------- ### Install PostHog Dependencies (Bash) Source: https://github.com/stackseehq/analytics/blob/main/www/content/docs/providers/index.mdx Installs the necessary PostHog client and server libraries using pnpm. ```bash pnpm install posthog-js posthog-node ``` -------------------------------- ### Initialize Server Analytics with Bento (TypeScript) Source: https://github.com/stackseehq/analytics/blob/main/www/content/docs/quick-start.mdx Demonstrates the initialization of Stacksee Analytics with the Bento server provider. It requires a site UUID, publishable key, and secret key from environment variables for authentication. ```typescript import { createServerAnalytics } from '@stacksee/analytics/server'; import { BentoServerProvider } from '@stacksee/analytics/providers/server'; import type { AppEvents } from './events'; export const serverAnalytics = createServerAnalytics({ providers: [ new BentoServerProvider({ siteUuid: process.env.BENTO_SITE_UUID!, authentication: { publishableKey: process.env.BENTO_PUBLISHABLE_KEY!, secretKey: process.env.BENTO_SECRET_KEY! } }) ], debug: process.env.NODE_ENV === 'development' }); ``` -------------------------------- ### Initialize Server Analytics with PostHog (TypeScript) Source: https://github.com/stackseehq/analytics/blob/main/www/content/docs/quick-start.mdx Demonstrates the initialization of Stacksee Analytics with the PostHog server provider. It uses environment variables for API keys and host configuration, enabling debugging in development mode. ```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' }); ``` -------------------------------- ### Initialize Server-Side Analytics with PostHog Source: https://github.com/stackseehq/analytics/blob/main/www/content/docs/installation.mdx Configures server-side analytics using the PostHog provider. It requires the PostHog API key to be set as an environment variable (POSTHOG_API_KEY). This setup is intended for server environments only and should not expose sensitive keys to the client. ```typescript // Server-side code only const serverAnalytics = createServerAnalytics({ providers: [ new PostHogServerProvider({ apiKey: process.env.POSTHOG_API_KEY }) ] }); ``` -------------------------------- ### Initialize Server Analytics with Pirsch (TypeScript) Source: https://github.com/stackseehq/analytics/blob/main/www/content/docs/quick-start.mdx Demonstrates the initialization of Stacksee Analytics with the Pirsch server provider. It uses environment variables for hostname and access key for authentication. ```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' }); ``` -------------------------------- ### TypeScript Type Definitions for @stacksee/analytics Source: https://github.com/stackseehq/analytics/blob/main/www/content/docs/installation.mdx Demonstrates how TypeScript type definitions are automatically available for @stacksee/analytics, providing autocomplete and type checking without additional setup. ```typescript // Types work automatically import { createClientAnalytics } from '@stacksee/analytics/client'; // ↑ Full autocomplete and type checking ``` -------------------------------- ### Server-Side Environment Variables for Analytics Source: https://github.com/stackseehq/analytics/blob/main/www/content/docs/installation.mdx Example of setting up non-public environment variables for server-side analytics tracking. These variables are typically used for API keys and credentials that should not be exposed client-side. ```bash # .env.local ``` -------------------------------- ### Using Multiple Analytics Providers (TypeScript) Source: https://github.com/stackseehq/analytics/blob/main/www/content/docs/quick-start.mdx Demonstrates how to use multiple analytics providers (PostHog and Bento) simultaneously for client-side analytics. This allows sending events to multiple services with a single call. ```typescript import { createClientAnalytics } from '@stacksee/analytics/client'; import { PostHogClientProvider, BentoClientProvider } from '@stacksee/analytics/providers/client'; export const analytics = createClientAnalytics({ providers: [ // Product analytics with PostHog new PostHogClientProvider({ token: import.meta.env.VITE_POSTHOG_KEY! }), // Email marketing with Bento new BentoClientProvider({ siteUuid: import.meta.env.VITE_BENTO_SITE_UUID! }) ] }); // One call, all providers receive the event analyrics.track('user_signed_up', { email: 'user@example.com', plan: 'pro' }); ``` -------------------------------- ### Identify Users for Context Source: https://github.com/stackseehq/analytics/blob/main/www/content/docs/quick-start.mdx Associate user context with all subsequent events using identify(). Takes user ID and properties like email, plan and name. ```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' }); ``` -------------------------------- ### Install PostHog Analytics SDKs (npm) Source: https://github.com/stackseehq/analytics/blob/main/www/content/docs/installation.mdx Installs the PostHog JavaScript and Node.js SDKs for integrating PostHog analytics services. PostHog offers product analytics, feature flags, and session replay. ```bash npm install posthog-js posthog-node ``` -------------------------------- ### Basic Client Analytics Initialization (TypeScript) Source: https://github.com/stackseehq/analytics/blob/main/www/content/docs/index.mdx A minimal example of initializing the client analytics without specific event definitions or providers. This demonstrates the basic structure required to set up the analytics client, with a placeholder for providers. ```typescript import { createClientAnalytics } from '@stacksee/analytics/client'; const analytics = createClientAnalytics({ providers: [/* your providers */] }); analytics.track('button_clicked', { buttonId: 'cta' }); ``` -------------------------------- ### Set Up Environment Variables Source: https://github.com/stackseehq/analytics/blob/main/www/content/docs/guides/nextjs.mdx Configures necessary environment variables for PostHog analytics, separating client-side (public) and server-side (private) keys for security. ```bash NEXT_PUBLIC_POSTHOG_KEY=your-posthog-api-key NEXT_PUBLIC_POSTHOG_HOST=https://app.posthog.com POSTHOG_API_KEY=your-posthog-api-key ``` -------------------------------- ### Installing PostHog Provider Dependencies (Bash) Source: https://github.com/stackseehq/analytics/blob/main/www/content/docs/providers/posthog.mdx Installs required packages for StackSee Analytics with PostHog integration using pnpm. Requires Node.js and pnpm to be installed beforehand. No inputs or outputs beyond package installation; no known limitations. ```bash pnpm install @stacksee/analytics posthog-js posthog-node ``` -------------------------------- ### SvelteKit Client-Side Environment Variables for Analytics Source: https://github.com/stackseehq/analytics/blob/main/www/content/docs/installation.mdx Configures client-side environment variables in a SvelteKit project for analytics keys and shows how to import and use them in your application. ```bash 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 }) ] }); ``` -------------------------------- ### Install @stacksee/analytics and Providers Source: https://github.com/stackseehq/analytics/blob/main/readme.md Installs the core analytics library and optional provider packages like PostHog, Bento, or Pirsch. Ensure you install the necessary SDKs for the providers you intend to use. ```bash pnpm install @stacksee/analytics # For PostHog support pnpm install posthog-js posthog-node # For Bento support (server-side only) pnpm install @bentonow/bento-node-sdk # For Pirsch support pnpm install pirsch-sdk ``` -------------------------------- ### Install Bento Node SDK Source: https://github.com/stackseehq/analytics/blob/main/www/content/docs/providers/bento.mdx Installs the Bento Node.js SDK for server-side integration. This package is required for server-side analytics. ```bash pnpm install @bentonow/bento-node-sdk ``` -------------------------------- ### Client-Side Analytics Setup (TypeScript) Source: https://github.com/stackseehq/analytics/blob/main/www/content/docs/core-concepts/client-vs-server.mdx Initializes the client-side analytics instance using @stacksee/analytics. It requires a PostHogClientProvider and an environment variable for the API key. This setup is suitable for browser environments to track 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 }) ] }); ``` -------------------------------- ### Next.js Client-Side Environment Variables for Analytics Source: https://github.com/stackseehq/analytics/blob/main/www/content/docs/installation.mdx Sets up client-side environment variables in a Next.js project for analytics API keys and demonstrates how to access them for provider configuration. ```bash 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 }) ] }); ``` -------------------------------- ### Track Events in Components Source: https://github.com/stackseehq/analytics/blob/main/www/content/docs/quick-start.mdx Use the analytics instance to track events with full TypeScript autocompletion. Events are type-safe based on defined event schema. ```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 ; } ``` -------------------------------- ### Create React App Client-Side Environment Variables for Analytics Source: https://github.com/stackseehq/analytics/blob/main/www/content/docs/installation.mdx Sets up client-side environment variables for a Create React App project to store analytics API keys and demonstrates their usage in initializing analytics clients. ```bash 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 }) ] }); ``` -------------------------------- ### Create Client Analytics Instance Source: https://github.com/stackseehq/analytics/blob/main/www/content/docs/guides/nextjs.mdx Initializes the client-side analytics instance with PostHog provider configuration, using environment variables for API keys and host. ```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: process.env.NEXT_PUBLIC_POSTHOG_KEY!, api_host: process.env.NEXT_PUBLIC_POSTHOG_HOST }) ], debug: process.env.NODE_ENV === 'development' }); ``` -------------------------------- ### Server-Side Analytics Setup (TypeScript) Source: https://github.com/stackseehq/analytics/blob/main/www/content/docs/core-concepts/client-vs-server.mdx Sets up the server-side analytics instance using @stacksee/analytics. It utilizes a PostHogServerProvider and requires the PostHog API key from environment variables. This setup is intended for backend environments like Node.js. ```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! }) ] }); ``` -------------------------------- ### Define Type-Safe Events Source: https://github.com/stackseehq/analytics/blob/main/www/content/docs/quick-start.mdx Create an event collection with full TypeScript support. Defines event names, categories and typed properties for better developer experience. ```typescript import type { CreateEventDefinition, EventCollection } from '@stacksee/analytics'; export const appEvents = { userSignedUp: { name: 'user_signed_up', category: 'user', properties: {} as { email: string; plan: 'free' | 'pro' | 'enterprise'; referralSource?: string; } }, buttonClicked: { name: 'button_clicked', category: 'engagement', properties: {} as { buttonId: string; location: string; } }, featureUsed: { name: 'feature_used', category: 'engagement', properties: {} as { featureName: string; userId: string; } } } as const satisfies EventCollection>>; // Export types for use in your app export type AppEvents = typeof appEvents; ``` -------------------------------- ### Svelte Runes Analytics Integration Source: https://github.com/stackseehq/analytics/blob/main/www/content/docs/guides/sveltekit.mdx An example of integrating Stacksee analytics into a Svelte 5 application using Svelte Runes. It covers initializing analytics on component mount, tracking page views reactively, and identifying users based on application data. This snippet assumes the 'analytics' instance is imported from '$lib/analytics' and user data is available in the layout's props. ```svelte {@render children()} ``` -------------------------------- ### Create Server Analytics Instance Source: https://github.com/stackseehq/analytics/blob/main/www/content/docs/guides/nextjs.mdx Initializes the server-side analytics instance with PostHog provider configuration, using environment variables for API keys and host. ```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.NEXT_PUBLIC_POSTHOG_HOST }) ], debug: process.env.NODE_ENV === 'development' }); ``` -------------------------------- ### Install Pirsch SDK with pnpm Source: https://github.com/stackseehq/analytics/blob/main/www/content/docs/providers/pirsch.mdx Installs the Pirsch SDK using the pnpm package manager. This is the first step before integrating Pirsch analytics into your project. ```bash pnpm install pirsch-sdk ``` -------------------------------- ### Initialize Bento Client-Side Analytics Source: https://github.com/stackseehq/analytics/blob/main/www/content/docs/providers/bento.mdx Sets up client-side analytics with the Bento provider. Requires a Bento site UUID and optionally a debug flag. No installation is needed as it uses a CDN. ```typescript import { createClientAnalytics } from '@stacksee/analytics/client'; import { BentoClientProvider } from '@stacksee/analytics/providers/client'; const analytics = createClientAnalytics({ providers: [ new BentoClientProvider({ siteUuid: 'your-bento-site-uuid', debug: false }) ] }); await analytics.initialize(); ``` -------------------------------- ### Universal API Example (TypeScript) Source: https://github.com/stackseehq/analytics/blob/main/www/content/docs/index.mdx Highlights the universal API design of @stacksee/analytics, where the same methods (`track`, `identify`, `pageView`) are available for both client-side and server-side implementations. This allows for consistent analytics code across different environments. ```typescript // Client-side import { createClientAnalytics } from '@stacksee/analytics/client'; // Server-side import { createServerAnalytics } from '@stacksee/analytics/server'; // Both support the same methods analytics.track(); analytics.identify(); analytics.pageView(); ``` -------------------------------- ### Environment Variable Best Practices Source: https://github.com/stackseehq/analytics/blob/main/www/content/docs/guides/nextjs.mdx Highlights the correct way to configure environment variables for client-side and server-side analytics tracking. ```bash # Client-side must be prefixed with NEXT_PUBLIC_ NEXT_PUBLIC_POSTHOG_KEY=xxx # Server-side should NOT be prefixed POSTHOG_API_KEY=xxx ``` -------------------------------- ### Type-Safe Event Tracking Examples (TypeScript) Source: https://github.com/stackseehq/analytics/blob/main/www/content/docs/index.mdx Illustrates the compile-time type checking provided by @stacksee/analytics. It shows examples of incorrect event tracking attempts that would result in TypeScript errors, alongside a correct, fully typed event tracking call. ```typescript // ❌ This will error - wrong property analytics.track('user_signed_up', { wrongProperty: 'value' }); // ❌ This will error - wrong event name analytics.track('wrong_event', {}); // ✅ This works - fully typed analytics.track('user_signed_up', { email: 'user@example.com', plan: 'pro' }); ``` -------------------------------- ### Track API Requests in Middleware Source: https://github.com/stackseehq/analytics/blob/main/www/content/docs/guides/nextjs.mdx This middleware function tracks 'apiRequest' events for paths starting with '/api/'. It attempts to get user information from the request, tracks the event with request details and user context if available, and shuts down the analytics client. ```typescript import { NextResponse } from 'next/server'; import type { NextRequest } from 'next/server'; import { serverAnalytics } from '@/lib/server-analytics'; export async function middleware(request: NextRequest) { // Track API requests if (request.nextUrl.pathname.startsWith('/api/')) { const user = await getUserFromRequest(request); // Assuming getUserFromRequest is defined elsewhere await serverAnalytics.track('apiRequest', { path: request.nextUrl.pathname, method: request.method }, user ? { userId: user.id, user: { email: user.email, traits: { plan: user.plan } } } : undefined); await serverAnalytics.shutdown(); } return NextResponse.next(); } export const config = { matcher: '/api/:path*' }; ``` -------------------------------- ### Create Client-Side Stacksee Analytics Instance Source: https://github.com/stackseehq/analytics/blob/main/www/content/docs/guides/sveltekit.mdx Initializes the client-side analytics instance using @stacksee/analytics. It configures the PostHog client provider with public environment variables and enables debug mode if in development. ```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 }); ``` -------------------------------- ### Signup with Server Actions (TypeScript) Source: https://github.com/stackseehq/analytics/blob/main/www/content/docs/guides/nextjs.mdx This snippet demonstrates how to track a user signup event using a server action in Next.js. It utilizes serverAnalytics to track the event and includes user details. ```typescript import Form from 'next/form'; import { signup } from './actions'; export default function SignupPage() { return (
); } ``` ```typescript 'use server'; import { serverAnalytics } from '@/lib/server-analytics'; import { redirect } from 'next/navigation'; export async function signup(formData: FormData) { const email = formData.get('email') as string; // Create user... const user = await db.user.create({ data: { email } }); // Track signup await serverAnalytics.track('userSignedUp', { email, plan: 'free' }, { userId: user.id, user: { email, traits: { plan: 'free' } } }); await serverAnalytics.shutdown(); redirect('/dashboard'); } ``` -------------------------------- ### Configure Environment Variables for PostHog Source: https://github.com/stackseehq/analytics/blob/main/www/content/docs/guides/sveltekit.mdx Sets up environment variables for Stacksee Analytics. PUBLIC variables are exposed to the client, while private variables are for server-side use only. Ensure these are correctly prefixed. ```dotenv # Client-side (public - must be prefixed with PUBLIC_) PUBLIC_POSTHOG_KEY=your-posthog-api-key PUBLIC_POSTHOG_HOST=https://app.posthog.com # Server-side (private - no prefix) POSTHOG_API_KEY=your-posthog-api-key ``` -------------------------------- ### Combine Product Analytics and Email Marketing Providers Source: https://github.com/stackseehq/analytics/blob/main/www/content/docs/core-concepts/providers.mdx This example demonstrates how to configure the analytics client with both product analytics (PostHog) and email marketing (Bento) providers for a combined solution. ```typescript const analytics = createClientAnalytics({ providers: [ new PostHogClientProvider({ token: 'xxx' }), // Track behavior new BentoClientProvider({ siteUuid: 'xxx' }) // Send emails ] }); ``` -------------------------------- ### Get User Context for Server-Side Events Source: https://github.com/stackseehq/analytics/blob/main/www/content/docs/guides/nextjs.mdx This utility function retrieves user context from the authentication session for server-side analytics. It uses '@/lib/auth' to get the session and returns a user object with ID, email, name, and plan, or undefined if not authenticated. ```typescript import { auth } from '@/lib/auth'; export async function getUserContext() { const session = await auth(); if (!session?.user) { return undefined; } return { userId: session.user.id, user: { email: session.user.email, traits: { name: session.user.name, plan: session.user.plan } } }; } ``` -------------------------------- ### SaaS application event patterns in TypeScript Source: https://github.com/stackseehq/analytics/blob/main/www/content/docs/core-concepts/events.mdx Example event definitions for SaaS applications including user signups, trials, feature usage, and subscription changes. Includes typed properties for each event. ```typescript export const appEvents = { userSignedUp: { name: 'user_signed_up', category: 'user', properties: {} as { email: string; plan: 'free' | 'pro' | 'enterprise'; referralSource?: string; } }, trialStarted: { name: 'trial_started', category: 'conversion', properties: {} as { plan: 'pro' | 'enterprise'; trialDays: number; } }, featureUsed: { name: 'feature_used', category: 'engagement', properties: {} as { featureName: string; plan: string; } }, subscriptionUpgraded: { name: 'subscription_upgraded', category: 'conversion', properties: {} as { fromPlan: string; toPlan: string; price: number; } } } as const; ``` -------------------------------- ### Track Page Views in SvelteKit Server Load Function Source: https://github.com/stackseehq/analytics/blob/main/www/content/docs/guides/sveltekit.mdx Example of tracking a 'pageViewed' event within a SvelteKit server load function. It fetches post data, tracks the page view with relevant properties, and ensures analytics is shut down, especially in serverless environments. ```typescript import { serverAnalytics } from '$lib/server-analytics'; import type { PageServerLoad } from './$types'; export const load: PageServerLoad = async ({ params }) => { const post = await db.getPost(params.slug); // Track page view await serverAnalytics.track('pageViewed', { path: `/blog/${params.slug}`, title: post.title }); // Always shutdown in serverless await serverAnalytics.shutdown(); return { post }; }; ``` -------------------------------- ### Vercel Edge Function Analytics Tracking (TypeScript) Source: https://github.com/stackseehq/analytics/blob/main/www/content/docs/guides/sveltekit.mdx This TypeScript code defines a GET request handler for an API route (`src/routes/api/edge/+server.ts`) intended to run on the Vercel Edge runtime. It tracks an 'edgeFunction' event and explicitly calls `serverAnalytics.shutdown()` as required for edge environments. Dependencies: SvelteKit's `json` and `$lib/server-analytics`. ```typescript import { json } from '@sveltejs/kit'; import { serverAnalytics } from '$lib/server-analytics'; import type { RequestHandler } from './$types'; export const config = { runtime: 'edge' }; export const GET: RequestHandler = async () => { await serverAnalytics.track('edgeFunction', { runtime: 'edge' }); // Always shutdown in edge functions await serverAnalytics.shutdown(); return json({ success: true }); }; ``` -------------------------------- ### Protect Routes and Track Unauthorized Access (TypeScript) Source: https://github.com/stackseehq/analytics/blob/main/www/content/docs/guides/sveltekit.mdx This `handle` hook in `src/hooks.server.ts` protects routes starting with '/dashboard'. It checks for a session ID, attempts to retrieve user data, and if the user is not authenticated, it tracks an 'unauthorizedAccess' event before redirecting to the login page. Dependencies: SvelteKit's `redirect`, `Handle`, and `$lib/server-analytics`. ```typescript import { redirect } from '@sveltejs/kit'; import { serverAnalytics } from '$lib/server-analytics'; import type { Handle } from '@sveltejs/kit'; export const handle: Handle = async ({ event, resolve }) => { const sessionId = event.cookies.get('sessionid'); if (sessionId) { event.locals.user = await db.getUserFromSession(sessionId); } // Protect dashboard routes if (event.url.pathname.startsWith('/dashboard') && !event.locals.user) { // Track unauthorized access await serverAnalytics.track('unauthorizedAccess', { path: event.url.pathname }); await serverAnalytics.shutdown(); throw redirect(307, '/login'); } return resolve(event); }; ``` -------------------------------- ### Correct Analytics Client and Server Imports Source: https://github.com/stackseehq/analytics/blob/main/www/content/docs/guides/sveltekit.mdx Shows the proper import paths for initializing client-side and server-side analytics. Importing from '@stacksee/analytics/client' and '@stacksee/analytics/server' respectively ensures correct initialization and functionality. Importing both from the base package '@stacksee/analytics' is incorrect. ```typescript // ✅ Correct import { createClientAnalytics } from '@stacksee/analytics/client'; import { createServerAnalytics } from '@stacksee/analytics/server'; // ❌ Wrong import { createClientAnalytics, createServerAnalytics } from '@stacksee/analytics'; ``` -------------------------------- ### Node.js Adapter Analytics Shutdown (TypeScript) Source: https://github.com/stackseehq/analytics/blob/main/www/content/docs/guides/sveltekit.mdx This TypeScript code provides a GET request handler for an API route (`src/routes/api/data/+server.ts`) suitable for Node.js deployments. It fetches data, tracks a 'dataFetched' event with the count of items, and crucially calls `serverAnalytics.shutdown()` to ensure events are flushed before responding. Dependencies: SvelteKit's `json` and `$lib/server-analytics`. ```typescript import { json } from '@sveltejs/kit'; import { serverAnalytics } from '$lib/server-analytics'; import type { RequestHandler } from './$types'; export const GET: RequestHandler = async () => { const data = await fetchData(); await serverAnalytics.track('dataFetched', { count: data.length }); // Shutdown to flush events await serverAnalytics.shutdown(); return json(data); }; ``` -------------------------------- ### Install Pirsch Analytics SDK (npm) Source: https://github.com/stackseehq/analytics/blob/main/www/content/docs/installation.mdx Installs the Pirsch SDK for integrating Pirsch, a privacy-focused, cookie-free web analytics service. This SDK supports both client-side and server-side usage. ```bash npm install pirsch-sdk ``` -------------------------------- ### Server-Side Analytics for User Sign-ups (TypeScript) Source: https://github.com/stackseehq/analytics/blob/main/www/content/docs/guides/sveltekit.mdx This server action in TypeScript handles user sign-ups, validates input, creates a user in the database, and tracks the 'userSignedUp' event server-side using `serverAnalytics`. It includes user details and plan information in the tracking payload. Dependencies: SvelteKit's `fail` and `redirect`, and a local `$lib/server-analytics` module. ```typescript import { serverAnalytics } from '$lib/server-analytics'; import { fail, redirect } from '@sveltejs/kit'; import type { Actions } from './$types'; export const actions: Actions = { signup: async ({ request }) => { const data = await request.formData(); const email = data.get('email') as string; if (!email) { return fail(400, { email, missing: true }); } const user = await db.user.create({ data: { email } }); // Track server-side await serverAnalytics.track('userSignedUp', { email, plan: 'free' }, { userId: user.id, user: { email, traits: { plan: 'free' } } }); await serverAnalytics.shutdown(); throw redirect(303, '/dashboard'); } }; ``` -------------------------------- ### Shutdown Analytics in Serverless Functions with TypeScript Source: https://github.com/stackseehq/analytics/blob/main/www/content/docs/core-concepts/client-vs-server.mdx This example shows calling shutdown() in serverless environments to flush queued events before function termination. It tracks API requests and ensures delivery in platforms like Vercel or AWS Lambda. Inputs include request URL; no specific outputs beyond response; dependencies on serverAnalytics; limitations apply to cold starts where events might still queue briefly. ```typescript import { serverAnalytics } from '@/lib/server-analytics'; export async function handler(req, res) { // Track event await serverAnalytics.track('api_request', { endpoint: req.url }); // Shutdown to flush events before function terminates await serverAnalytics.shutdown(); return res.json({ success: true }); } ``` -------------------------------- ### Configure Multiple Analytics Providers in TypeScript Source: https://github.com/stackseehq/analytics/blob/main/www/content/docs/your-first-event.mdx Demonstrates sending events to multiple providers simultaneously by passing provider array. Shows combining PostHog and Bento for redundancy or phased migrations. Events dispatch to all configured providers automatically. ```typescript const analytics = createClientAnalytics({ providers: [ new PostHogClientProvider({ token: 'xxx' }), new BentoClientProvider({ siteUuid: 'xxx' }) ] }); ``` -------------------------------- ### Client-Side and Server-Side Proxy Provider Setup Source: https://github.com/stackseehq/analytics/blob/main/www/content/docs/core-concepts/providers.mdx This setup uses a Proxy client provider to route analytics events through a custom endpoint, which can help bypass ad-blockers. ```typescript const analytics = createClientAnalytics({ providers: [ new ProxyClientProvider({ endpoint: '/api/analytics' // Bypass ad-blockers }) ] }); ``` -------------------------------- ### Uninstall @stacksee/analytics and Provider SDKs Source: https://github.com/stackseehq/analytics/blob/main/www/content/docs/installation.mdx Instructions for completely removing the @stacksee/analytics package and its associated provider SDKs. This involves uninstalling the core library along with any specific provider packages that were installed. ```bash # Remove core library npm uninstall @stacksee/analytics # Remove provider SDKs npm uninstall posthog-js posthog-node @bentonow/bento-node-sdk pirsch-sdk ``` -------------------------------- ### TypeScript: Mark Optional Properties with `?` Source: https://github.com/stackseehq/analytics/blob/main/www/content/docs/core-concepts/type-safety.mdx Explains the correct way to mark optional properties in TypeScript using the `?` operator. The good example clearly indicates an optional `referralSource`, while the bad example uses `string | undefined`, which is less explicit about optionality. ```typescript // ✅ Good - clearly optional properties: {} as { email: string; referralSource?: string; // Optional with ? } // ❌ Bad - unclear if required properties: {} as { email: string; referralSource: string | undefined; } ``` -------------------------------- ### TypeScript: Define Specific Union Types for Properties Source: https://github.com/stackseehq/analytics/blob/main/www/content/docs/core-concepts/type-safety.mdx Illustrates how to define specific union types for properties in TypeScript for better type safety. The good example uses literal union types ('free' | 'pro' | 'enterprise'), whereas the bad example uses a too-loose `string` type. ```typescript // ✅ Good - specific values properties: {} as { plan: 'free' | 'pro' | 'enterprise'; } // ❌ Bad - too loose properties: {} as { plan: string; } ``` -------------------------------- ### Configure client analytics with multiple providers (TypeScript) Source: https://github.com/stackseehq/analytics/blob/main/readme.md Shows how to instantiate a client analytics instance that sends events to several services simultaneously, including PostHog, Google Analytics, and a custom Mixpanel provider. Demonstrates passing environment variables and enabling debug mode. ```TypeScript import { createClientAnalytics } from '@stacksee/analytics/client'; import { PostHogClientProvider } from '@stacksee/analytics/providers/client'; // Import your custom providers import { GoogleAnalyticsProvider } from './providers/google-analytics'; import { MixpanelProvider } from './providers/mixpanel'; const analytics = createClientAnalytics({ providers: [ // PostHog for product analytics new PostHogClientProvider({ apiKey: process.env.NEXT_PUBLIC_POSTHOG_KEY, host: 'https://app.posthog.com' }), // Google Analytics for marketing insights new GoogleAnalyticsProvider({ measurementId: process.env.NEXT_PUBLIC_GA_ID }), // Mixpanel for detailed user journey analysis new MixpanelProvider({ projectToken: process.env.NEXT_PUBLIC_MIXPANEL_TOKEN }) ], debug: process.env.NODE_ENV === 'development', enabled: true }); // All providers will receive this event analytics.track('user_signed_up', { userId: 'user-123', plan: 'pro' }); ``` -------------------------------- ### TypeScript: Use `as const satisfies` for Literal Type Preservation Source: https://github.com/stackseehq/analytics/blob/main/www/content/docs/core-concepts/type-safety.mdx Demonstrates the correct usage of `as const satisfies` in TypeScript to preserve literal types for event collections. The good example ensures type information is maintained, while the bad example shows how to lose type information by omitting `satisfies`. ```typescript // ✅ Good - preserves literal types export const appEvents = { /* ... */ } as const satisfies EventCollection>>; // ❌ Bad - loses type information export const appEvents = { /* ... */ }; ``` -------------------------------- ### Initialize Analytics with PostHog Provider Source: https://github.com/stackseehq/analytics/blob/main/www/content/docs/core-concepts/providers.mdx Demonstrates creating an analytics client instance with a PostHog provider. Requires the @stacksee/analytics and @stacksee/analytics/providers/client packages. Takes a provider token as input and returns a configured analytics client that can track events. ```typescript import { createClientAnalytics } from '@stacksee/analytics/client'; import { PostHogClientProvider } from '@stacksee/analytics/providers/client'; const analytics = createClientAnalytics({ providers: [ new PostHogClientProvider({ token: 'xxx' }) ] }); analytics.track('user_signed_up', { email: 'user@example.com' }); ``` -------------------------------- ### Setting Up Client-Side Analytics with PostHog (TypeScript) Source: https://github.com/stackseehq/analytics/blob/main/www/content/docs/providers/posthog.mdx Creates and initializes a client-side analytics instance using PostHogClientProvider for browser-based tracking. Depends on @stacksee/analytics/client and posthog-js; requires a valid PostHog API key. Supports all PostHog JS SDK options; initializes asynchronously without return value. ```typescript import { createClientAnalytics } from '@stacksee/analytics/client'; import { PostHogClientProvider } from '@stacksee/analytics/providers/client'; const analytics = createClientAnalytics({ providers: [ new PostHogClientProvider({ token: 'your-posthog-project-api-key', api_host: 'https://app.posthog.com', // optional debug: false }) ] }); await analytics.initialize(); ``` -------------------------------- ### Documented event definition in TypeScript Source: https://github.com/stackseehq/analytics/blob/main/www/content/docs/core-concepts/events.mdx Example of a well-documented event with comments explaining when it fires and who uses the data. Includes typed properties. ```typescript export const appEvents = { // Fired when user completes the onboarding flow // Triggers: After final step submission // Used by: Marketing team for conversion tracking onboardingCompleted: { name: 'onboarding_completed', category: 'user', properties: {} as { steps: number; duration: number; skipped: boolean; } } } as const; ``` -------------------------------- ### Create Console Analytics Provider Source: https://github.com/stackseehq/analytics/blob/main/www/content/docs/your-first-event.mdx Sets up a basic console logger provider for testing analytics events. This provider logs events to the console instead of sending them to a real analytics service. ```typescript import { createClientAnalytics } from '@stacksee/analytics/client'; import { BaseAnalyticsProvider } from '@stacksee/analytics'; import type { appEvents } from './events'; class ConsoleProvider extends BaseAnalyticsProvider { name = 'ConsoleProvider'; track(event: any) { console.log('📊 Event tracked:', event); } identify(userId: string, traits: any) { console.log('👤 User identified:', userId, traits); } pageView() { console.log('📄 Page view tracked'); } pageLeave() { console.log('👋 Page leave tracked'); } reset() { console.log('🔄 Analytics reset'); } } export const analytics = createClientAnalytics({ providers: [new ConsoleProvider()], debug: true }); ``` -------------------------------- ### Event deprecation pattern in TypeScript Source: https://github.com/stackseehq/analytics/blob/main/www/content/docs/core-concepts/events.mdx Shows how to properly deprecate events while maintaining backward compatibility. Includes example of marking an event as deprecated. ```typescript export const appEvents = { // @deprecated Use 'subscription_upgraded' instead planUpgraded: { /* ... */ }, subscriptionUpgraded: { /* ... */ } // New event } as const; ``` -------------------------------- ### Signup Form with useTransition (TypeScript) Source: https://github.com/stackseehq/analytics/blob/main/www/content/docs/guides/nextjs.mdx This snippet implements a signup form with client-side tracking and a server action using `useTransition`. It demonstrates tracking a form submission before the server action is triggered, enhancing user experience with a pending state. ```typescript 'use client'; import { useState, useTransition } from 'react'; import { analytics } from '@/lib/analytics'; import { signup } from '@/app/signup/actions'; export function SignupForm() { const [isPending, startTransition] = useTransition(); const handleSubmit = (e: React.FormEvent) => { e.preventDefault(); // Track client-side analytics.track('formSubmitted', { formId: 'signup', formType: 'signup' }); // Submit via server action const formData = new FormData(e.currentTarget); startTransition(() => { signup(formData); }); }; return (
); } ```