### Install Dependencies and Start Local Development Source: https://github.com/samhoque/convex-posthog/blob/main/CONTRIBUTING.md Installs project dependencies, navigates to the example directory, installs its dependencies, and starts the local Convex development server. ```sh npm i cd example npm i npx convex dev ``` -------------------------------- ### Run Example App Source: https://github.com/samhoque/convex-posthog/blob/main/README.md Starts the development server and generates types for the example application. ```bash npm run dev ``` -------------------------------- ### Install Dependencies Source: https://github.com/samhoque/convex-posthog/blob/main/README.md Installs the necessary packages for development. ```bash npm install ``` -------------------------------- ### Install convex-test Source: https://github.com/samhoque/convex-posthog/blob/main/_autodocs/api-reference/test-helper.md Install the `convex-test` library as a development dependency for your project. ```bash npm install --save-dev convex-test ``` -------------------------------- ### Event Tracking with Custom Properties Source: https://github.com/samhoque/convex-posthog/blob/main/_autodocs/endpoints.md This example shows how to track an event with custom properties, such as item ID, amount, and currency for a purchase. ```json { "api_key": "phc_abc123def456", "event": "item_purchased", "distinct_id": "user_456", "properties": { "itemId": "item_789", "amount": 99.99, "currency": "USD", "$lib": "convex-posthog", "$lib_version": "0.1.1" }, "timestamp": "2024-06-27T10:31:00.456Z" } ``` -------------------------------- ### Instantiate PostHog Client Source: https://github.com/samhoque/convex-posthog/blob/main/_autodocs/api-reference/PostHog.md Examples of how to instantiate the PostHog client, either using environment variables or explicit configuration for API key and host. ```typescript import { mutation } from "./_generated/server"; import { components } from "./_generated/api"; import { PostHog } from "@samhoque/convex-posthog"; // Create client with environment variables const posthog = new PostHog(components.posthog); // Or with explicit configuration const posthog = new PostHog(components.posthog, { apiKey: "phc_your_api_key_here", host: "https://us.i.posthog.com", }); // For EU Cloud const posthogEu = new PostHog(components.posthog, { host: "https://eu.i.posthog.com", }); ``` -------------------------------- ### Example Error Log Source: https://github.com/samhoque/convex-posthog/blob/main/_autodocs/endpoints.md This example shows the format of a warning log when PostHog tracking fails, including the status code, response body, and event details. ```log PostHog tracking failed: 401 Unauthorized { responseBody: '{"status":"error","message":"Invalid API key"}', event: "purchase", userId: "user_123", url: "https://us.i.posthog.com/i/v0/e/" } ``` -------------------------------- ### Install Convex PostHog Component Source: https://github.com/samhoque/convex-posthog/blob/main/README.md Install the PostHog Convex component using npm. This is the first step to integrating server-side analytics. ```bash npm install @samhoque/convex-posthog ``` -------------------------------- ### Minimal Configuration using Environment Variables Source: https://github.com/samhoque/convex-posthog/blob/main/_autodocs/configuration.md Configure Convex PostHog by setting environment variables. This example shows how to import and use the posthog configuration. ```typescript // convex/convex.config.ts import { defineApp } from "convex/server"; import posthog from "@samhoque/convex-posthog/convex.config"; const app = defineApp(); app.use(posthog); export default app; ``` ```bash npx convex env set POSTHOG_API_KEY phc_abc123 ``` -------------------------------- ### Basic Test Setup for PostHog Tracking Source: https://github.com/samhoque/convex-posthog/blob/main/_autodocs/api-reference/test-helper.md Demonstrates a basic test case for tracking user signup events. It shows how to initialize the test environment, register the PostHog component, and then execute a mutation that utilizes PostHog tracking. ```typescript import { convexTest } from "convex-test"; import { register } from "@samhoque/convex-posthog/test"; import { defineSchema } from "convex/server"; describe("PostHog tracking tests", () => { test("tracks user signup", async () => { // Create test instance with empty schema const schema = defineSchema({}); const t = convexTest(schema, modules); // Register the PostHog component register(t); // Run your mutation with PostHog tracking const result = await t.mutation(api.signupUser, { userId: "user_123", email: "user@example.com", name: "Test User", }); expect(result.success).toBe(true); }); }); ``` -------------------------------- ### Instantiate PostHog Client with Component Source: https://github.com/samhoque/convex-posthog/blob/main/_autodocs/api-reference/PostHogComponent.md Example of how to instantiate the PostHog client class using the PostHogComponent obtained from Convex's generated components. ```typescript import { components } from "./_generated/api"; import { PostHog } from "@samhoque/convex-posthog"; // components.posthog is of type PostHogComponent const posthog = new PostHog(components.posthog); ``` -------------------------------- ### Set Environment Variables for PostHog Source: https://github.com/samhoque/convex-posthog/blob/main/_autodocs/api-reference/PostHogOptions.md Example of setting PostHog API key and host using shell export commands. ```bash export POSTHOG_API_KEY="phc_your_api_key_here" export POSTHOG_HOST="https://us.i.posthog.com" ``` -------------------------------- ### Simple Event Tracking Source: https://github.com/samhoque/convex-posthog/blob/main/_autodocs/endpoints.md This example demonstrates how to track a simple event with basic properties. It includes the API key, event name, distinct ID, and essential properties like the library used and its version. ```APIDOC ## POST /i/v0/e/ ### Description Tracks a simple event with basic properties. ### Method POST ### Endpoint /i/v0/e/ ### Request Body - **api_key** (string) - Required - Your PostHog API key. - **event** (string) - Required - The name of the event to track. - **distinct_id** (string) - Required - A unique identifier for the user or device. - **properties** (object) - Optional - A set of properties associated with the event. - **$lib** (string) - Required - The name of the library used for tracking. - **$lib_version** (string) - Required - The version of the library used for tracking. - **timestamp** (string) - Optional - The timestamp when the event occurred in ISO 8601 format. ### Request Example { "api_key": "phc_abc123def456", "event": "user_signed_up", "distinct_id": "user_123", "properties": { "email": "user@example.com", "$lib": "convex-posthog", "$lib_version": "0.1.1" }, "timestamp": "2024-06-27T10:30:45.123Z" } ### Response #### Success Response (200) - **status** (string) - Indicates the status of the request, typically "ok" for success. #### Response Example { "status": "ok" } ``` -------------------------------- ### Typical Test File Structure with Register Source: https://github.com/samhoque/convex-posthog/blob/main/_autodocs/api-reference/test-helper.md This example shows a typical structure for a test file using `convex-test` and the `register` function from `@samhoque/convex-posthog/test`. It demonstrates how to set up the test environment and register the PostHog component. ```typescript import { describe, test, expect } from "vitest"; import { convexTest } from "convex-test"; import { register } from "@samhoque/convex-posthog/test"; describe("My mutations", () => { test("tracks events", async () => { const t = convexTest(schema, modules); register(t); // Your test code }); }); ``` -------------------------------- ### Event Tracking with User Properties ($set, $set_once) Source: https://github.com/samhoque/convex-posthog/blob/main/_autodocs/endpoints.md This example demonstrates how to update user properties using $set for mutable properties and $set_once for properties that should only be set once. ```json { "api_key": "phc_abc123def456", "event": "profile_updated", "distinct_id": "user_789", "properties": { "$set": { "name": "John Doe", "email": "john@example.com", "plan": "premium" }, "$set_once": { "signup_date": "2024-01-15", "referral_source": "search" }, "$lib": "convex-posthog", "$lib_version": "0.1.1" }, "timestamp": "2024-06-27T10:32:15.789Z" } ``` -------------------------------- ### Event with User Properties Source: https://github.com/samhoque/convex-posthog/blob/main/_autodocs/endpoints.md This example illustrates tracking an event that also updates user properties, using `$set` for immediate updates and `$set_once` for properties that should only be set one time. ```APIDOC ## POST /i/v0/e/ ### Description Tracks an event and updates user properties. `$set` updates properties immediately, while `$set_once` sets properties only if they haven't been set before. ### Method POST ### Endpoint /i/v0/e/ ### Request Body - **api_key** (string) - Required - Your PostHog API key. - **event** (string) - Required - The name of the event to track. - **distinct_id** (string) - Required - A unique identifier for the user or device. - **properties** (object) - Optional - A set of properties associated with the event. - **$set** (object) - Optional - Properties to be updated immediately for the user. - **name** (string) - Example user property. - **email** (string) - Example user property. - **plan** (string) - Example user property. - **$set_once** (object) - Optional - Properties to be set only once for the user. - **signup_date** (string) - Example user property. - **referral_source** (string) - Example user property. - **$lib** (string) - Required - The name of the library used for tracking. - **$lib_version** (string) - Required - The version of the library used for tracking. - **timestamp** (string) - Optional - The timestamp when the event occurred in ISO 8601 format. ### Request Example { "api_key": "phc_abc123def456", "event": "profile_updated", "distinct_id": "user_789", "properties": { "$set": { "name": "John Doe", "email": "john@example.com", "plan": "premium" }, "$set_once": { "signup_date": "2024-01-15", "referral_source": "search" }, "$lib": "convex-posthog", "$lib_version": "0.1.1" }, "timestamp": "2024-06-27T10:32:15.789Z" } ### Response #### Success Response (200) - **status** (string) - Indicates the status of the request, typically "ok" for success. #### Response Example { "status": "ok" } ``` -------------------------------- ### Combine All Property Types for Purchase Tracking Source: https://github.com/samhoque/convex-posthog/blob/main/_autodocs/usage-patterns.md This example demonstrates using regular `properties`, `setProperties`, and `setOnceProperties` together in a single `trackUserEvent` call. It's useful for tracking event-specific details, updating user-level metrics, and setting initial user attributes. ```typescript export const completePurchase = mutation({ args: { userId: v.string(), orderId: v.string(), amount: v.number(), }, handler: async (ctx, args) => { // Process payment // ... // Track with all property types await posthog.trackUserEvent(ctx, { userId: args.userId, event: "purchase_completed", // Regular properties for this event properties: { orderId: args.orderId, amount: args.amount, currency: "USD", }, // Update user-level properties setProperties: { lastPurchaseAmount: args.amount, lastPurchaseDate: new Date().toISOString(), totalSpent: args.amount, // Would be calculated in real app }, // Set one-time properties setOnceProperties: { firstPurchaseDate: new Date().toISOString(), firstPurchaseAmount: args.amount, hasCompletedPurchase: true, }, }); return { success: true }; }, }); ``` -------------------------------- ### Track User Event Usage Example Source: https://github.com/samhoque/convex-posthog/blob/main/_autodocs/api-reference/trackEvent.md This TypeScript example demonstrates how to use the trackUserEvent function to send an event to PostHog. It shows the required parameters and how properties are passed. ```typescript const posthog = new PostHog(components.posthog); await posthog.trackUserEvent(ctx, { userId: "user_123", event: "purchase", properties: { amount: 99.99 }, }); ``` -------------------------------- ### Test Suite Setup with beforeEach Hook Source: https://github.com/samhoque/convex-posthog/blob/main/_autodocs/api-reference/test-helper.md Shows how to set up the test environment and register the PostHog component using the `beforeEach` hook in Vitest. This ensures that the PostHog component is registered for each test within the suite. ```typescript import { convexTest } from "convex-test"; import { register } from "@samhoque/convex-posthog/test"; import { defineSchema } from "convex/server"; import { describe, beforeEach, test, expect } from "vitest"; describe("Event tracking", () => { let t; beforeEach(() => { const schema = defineSchema({}); t = convexTest(schema, modules); register(t); }); test("tracks simple event", async () => { const result = await t.mutation(api.trackEvent, { userId: "user_1", event: "test_event", }); expect(result.success).toBe(true); }); test("tracks event with properties", async () => { const result = await t.mutation(api.trackEvent, { userId: "user_2", event: "test_event", properties: { key: "value" }, }); expect(result.success).toBe(true); }); }); ``` -------------------------------- ### Tracking a User Event Source: https://github.com/samhoque/convex-posthog/blob/main/_autodocs/OVERVIEW.md Example of how to use the PostHog client to track a user event within a Convex mutation. ```typescript import { mutation } from "convex/server"; import type { PostHogComponent } from "@samhoque/convex-posthog"; export const trackSignup = mutation({ args: { userId: "string", email: "string" }, handler: async (ctx, args) => { const posthog = ctx.component.get("posthog") as PostHogComponent; await posthog.trackUserEvent({ userId: args.userId, event: "user_signed_up", properties: { email: args.email, }, }); // ... rest of your mutation logic }, }); ``` -------------------------------- ### Run Build, Typecheck, and Tests Source: https://github.com/samhoque/convex-posthog/blob/main/CONTRIBUTING.md Cleans the dist directory, builds the project, performs type checking, and runs tests. It also includes linting for the example directory. ```sh rm -rf dist/ && npm run build npm run typecheck npm run test cd example npm run lint cd .. ``` -------------------------------- ### Track User Signup Event with PostHog Source: https://github.com/samhoque/convex-posthog/blob/main/README.md Implement a Convex mutation to track a 'user_signed_up' event. This example demonstrates initializing the PostHog component and sending user properties. ```typescript import { mutation } from "./_generated/server"; import { components } from "./_generated/api"; import { PostHog } from "@samhoque/convex-posthog"; import { v } from "convex/values"; // Initialize the PostHog component const posthog = new PostHog(components.posthog, { // API key and host are read from environment variables by default // Or you can pass them explicitly: // apiKey: process.env.POSTHOG_API_KEY, // host: process.env.POSTHOG_HOST, }); export const signupUser = mutation({ args: { userId: v.string(), email: v.string(), name: v.string(), }, handler: async (ctx, args) => { // Your business logic here // ... // Track the signup event await posthog.trackUserEvent(ctx, { userId: args.userId, event: "user_signed_up", properties: { email: args.email, name: args.name, signupMethod: "email", }, }); return { success: true }; }, }); ``` -------------------------------- ### Event with Custom Properties Source: https://github.com/samhoque/convex-posthog/blob/main/_autodocs/endpoints.md This example shows how to track an event with custom properties, such as item ID, amount, and currency, in addition to the standard event details. ```APIDOC ## POST /i/v0/e/ ### Description Tracks an event with custom properties like item details and monetary values. ### Method POST ### Endpoint /i/v0/e/ ### Request Body - **api_key** (string) - Required - Your PostHog API key. - **event** (string) - Required - The name of the event to track. - **distinct_id** (string) - Required - A unique identifier for the user or device. - **properties** (object) - Optional - A set of properties associated with the event. - **itemId** (string) - Optional - Identifier for the item involved in the event. - **amount** (number) - Optional - The monetary amount associated with the event. - **currency** (string) - Optional - The currency of the amount. - **$lib** (string) - Required - The name of the library used for tracking. - **$lib_version** (string) - Required - The version of the library used for tracking. - **timestamp** (string) - Optional - The timestamp when the event occurred in ISO 8601 format. ### Request Example { "api_key": "phc_abc123def456", "event": "item_purchased", "distinct_id": "user_456", "properties": { "itemId": "item_789", "amount": 99.99, "currency": "USD", "$lib": "convex-posthog", "$lib_version": "0.1.1" }, "timestamp": "2024-06-27T10:31:00.456Z" } ### Response #### Success Response (200) - **status** (string) - Indicates the status of the request, typically "ok" for success. #### Response Example { "status": "ok" } ``` -------------------------------- ### Match Component Name in Registration Source: https://github.com/samhoque/convex-posthog/blob/main/_autodocs/api-reference/test-helper.md Highlights the importance of matching the component name used during registration with the name defined in your `convex.config.ts`. This example assumes the default 'posthog' name. ```typescript // convex/convex.config.ts app.use(posthogConfig); // Default name is "posthog" // tests register(t); // Uses default "posthog" ``` -------------------------------- ### Track Custom Product Purchase Event with PostHog Source: https://github.com/samhoque/convex-posthog/blob/main/README.md Implement a Convex mutation to track a 'product_purchased' event. This example shows how to send custom properties related to a purchase. ```typescript export const trackPurchase = mutation({ args: { userId: v.string(), productId: v.string(), amount: v.number(), }, handler: async (ctx, args) => { // Your business logic // ... // Track the purchase event await posthog.trackUserEvent(ctx, { userId: args.userId, event: "product_purchased", properties: { productId: args.productId, amount: args.amount, currency: "USD", }, }); return { success: true }; }, }); ``` -------------------------------- ### Build Component Source: https://github.com/samhoque/convex-posthog/blob/main/README.md Compiles the component for production. ```bash npm run build ``` -------------------------------- ### Initialize PostHog with Complete Configuration Source: https://github.com/samhoque/convex-posthog/blob/main/_autodocs/api-reference/PostHogOptions.md Provide both API key and host explicitly when initializing the PostHog client. ```typescript const posthog = new PostHog(components.posthog, { apiKey: "phc_your_api_key_here", host: "https://us.i.posthog.com", }); ``` -------------------------------- ### Valid Mutation Handler with Scheduler Source: https://github.com/samhoque/convex-posthog/blob/main/_autodocs/api-reference/RunMutationCtx.md Example of a valid mutation handler that correctly uses PostHog.trackUserEvent, which requires scheduler capability. ```typescript // ✅ Valid - mutations have scheduler export const userMutation = mutation({ handler: async (ctx, args) => { await posthog.trackUserEvent(ctx, {...}); }, }); ``` -------------------------------- ### Handling Invalid Response Format Source: https://github.com/samhoque/convex-posthog/blob/main/_autodocs/errors.md Example of console output when the PostHog API response body cannot be read or parsed. The mutation continues. ```console Console: "PostHog tracking failed: 500 Internal Server Error" { responseBody: "Unable to read response", event: "test_event", ... } ``` -------------------------------- ### Peer Dependencies for Convex PostHog Source: https://github.com/samhoque/convex-posthog/blob/main/_autodocs/module-graph.md Specifies the required peer dependency for this package. Applications must install 'convex' version 1.24.8 or higher. ```json "peerDependencies": { "convex": "^1.24.8" } ``` -------------------------------- ### Deploy a New Version (Standard Release) Source: https://github.com/samhoque/convex-posthog/blob/main/CONTRIBUTING.md Increments the version, commits the change, performs a dry run of publishing, and then publishes the package. Finally, it pushes tags to the repository. ```sh # this will change the version and commit it (if you run it in the root directory) npm version patch npm publish --dry-run # sanity check files being included npm publish git push --tags ``` -------------------------------- ### Tracking Event with Missing Required Fields Source: https://github.com/samhoque/convex-posthog/blob/main/_autodocs/errors.md Example of calling `trackUserEvent` with an empty `userId`. This will log a warning and return without making a request. ```typescript await posthog.trackUserEvent(ctx, { userId: "", // Empty! event: "test_event", }); // Console logs: "PostHog: userId and event are required" ``` -------------------------------- ### PostHog Constructor Source: https://github.com/samhoque/convex-posthog/blob/main/README.md Initializes a new PostHog instance. You can provide an API key and host, or rely on environment variables and default values. ```APIDOC ## `PostHog` Constructor ### Description Initializes a new PostHog instance. You can provide an API key and host, or rely on environment variables and default values. ### Parameters #### Options - **apiKey** (string, optional) - PostHog API key. Defaults to `POSTHOG_API_KEY` env var - **host** (string, optional) - PostHog host URL. Defaults to `POSTHOG_HOST` env var or `https://us.i.posthog.com` (US Cloud). Use `https://eu.i.posthog.com` for EU Cloud or your self-hosted domain. ``` -------------------------------- ### Main Entry Point: @samhoque/convex-posthog Source: https://github.com/samhoque/convex-posthog/blob/main/_autodocs/module-graph.md The main client for tracking events and related types are exported from the root of the package. ```APIDOC ## Main Entry Point: `@samhoque/convex-posthog` ### Description This is the primary entry point for the `@samhoque/convex-posthog` package, providing the main client for event tracking and associated types. ### Exported Symbols | Symbol | Type | |---|---| | `PostHog` | Class | | `PostHogComponent` | Type | | `PostHogOptions` | Type | | `OpaqueIds` | Type utility | | `UseApi` | Type utility | ### Re-exported from `src/client/types.ts` | Symbol | Type | |---|---| | `RunMutationCtx` | Type | | `RunQueryCtx` | Type | | `RunActionCtx` | Type | | `QueryCtx` | Type | | `ActionCtx` | Type | | `OpaqueIds` | Type utility | | `UseApi` | Type utility | ``` -------------------------------- ### Setting PostHog API Key via Environment Variable Source: https://github.com/samhoque/convex-posthog/blob/main/_autodocs/errors.md Shows how to set the PostHog API key using the Convex environment variables. ```bash npx convex env set POSTHOG_API_KEY your_api_key ``` -------------------------------- ### register() Source: https://github.com/samhoque/convex-posthog/blob/main/_autodocs/api-reference/test-helper.md Registers the PostHog component with a Convex test instance. This function must be called in test setup to enable the component when testing mutations that use `PostHog.trackUserEvent()`. ```APIDOC ## register(t: TestConvex>, name: string = "posthog") ### Description Registers the PostHog component with a Convex test instance. This function must be called in test setup to enable the component when testing mutations that use `PostHog.trackUserEvent()`. ### Parameters #### Path Parameters - None #### Query Parameters - None #### Request Body - None ### Parameters - **t** (TestConvex) - Required - The test Convex instance from `convexTest()` - **name** (string) - Optional - Defaults to `"posthog"` - Component name as registered in convex.config.ts ### Return Type `void` — No return value ### Usage Examples #### Basic Test Setup ```typescript import { convexTest } from "convex-test"; import { register } from "@samhoque/convex-posthog/test"; import { defineSchema } from "convex/server"; describe("PostHog tracking tests", () => { test("tracks user signup", async () => { // Create test instance with empty schema const schema = defineSchema({}); const t = convexTest(schema, modules); // Register the PostHog component register(t); // Run your mutation with PostHog tracking const result = await t.mutation(api.signupUser, { userId: "user_123", email: "user@example.com", name: "Test User", }); expect(result.success).toBe(true); }); }); ``` #### With Custom Component Name If the component is registered with a different name in convex.config.ts: ```typescript const app = defineApp(); app.use(posthogConfig, "analytics"); // Custom name // In tests register(t, "analytics"); ``` #### With Existing Schema If your application has a database schema: ```typescript import { defineSchema, defineTable } from "convex/server"; import { v } from "convex/values"; const schema = defineSchema({ users: defineTable({ email: v.string(), name: v.string(), }), }); const t = convexTest(schema, modules); register(t); // Component is registered alongside user tables ``` #### Multiple Tests with Setup ```typescript import { convexTest } from "convex-test"; import { register } from "@samhoque/convex-posthog/test"; import { defineSchema } from "convex/server"; import { describe, beforeEach, test, expect } from "vitest"; describe("Event tracking", () => { let t; beforeEach(() => { const schema = defineSchema({}); t = convexTest(schema, modules); register(t); }); test("tracks simple event", async () => { const result = await t.mutation(api.trackEvent, { userId: "user_1", event: "test_event", }); expect(result.success).toBe(true); }); test("tracks event with properties", async () => { const result = await t.mutation(api.trackEvent, { userId: "user_2", event: "test_event", properties: { key: "value" }, }); expect(result.success).toBe(true); }); }); ``` ``` -------------------------------- ### Initialize PostHog with Environment Variables Source: https://github.com/samhoque/convex-posthog/blob/main/_autodocs/api-reference/PostHogOptions.md Instantiate the PostHog client without explicit options, relying on environment variables for configuration. ```typescript import { PostHog } from "@samhoque/convex-posthog"; import { components } from "./_generated/api"; // Reads POSTHOG_API_KEY and POSTHOG_HOST from environment const posthog = new PostHog(components.posthog); ``` -------------------------------- ### Invalid Query Handler Attempting Scheduler Use Source: https://github.com/samhoque/convex-posthog/blob/main/_autodocs/api-reference/RunMutationCtx.md Example of an invalid query handler attempting to use PostHog.trackUserEvent, resulting in a type error due to the lack of scheduler capability. ```typescript // ❌ Invalid - queries don't have scheduler export const userQuery = query({ handler: async (ctx, args) => { await posthog.trackUserEvent(ctx, {...}); // Type error }, }); ``` -------------------------------- ### Initialize PostHog with Explicit Host Source: https://github.com/samhoque/convex-posthog/blob/main/_autodocs/api-reference/PostHogOptions.md Configure the PostHog client by providing an explicit host URL, while reading the API key from environment variables. ```typescript const posthog = new PostHog(components.posthog, { host: "https://custom.posthog.example.com", }); ``` -------------------------------- ### Register PostHog component with default name Source: https://github.com/samhoque/convex-posthog/blob/main/_autodocs/api-reference/test-helper.md Use this in your test setup to register the PostHog component with its default name ('posthog'). This is required before running mutations that involve PostHog tracking. ```typescript register(t); ``` -------------------------------- ### Full Configuration with Explicit Options Source: https://github.com/samhoque/convex-posthog/blob/main/_autodocs/configuration.md Provide explicit API key and host options directly in the code when initializing the PostHog class. ```typescript import { PostHog } from "@samhoque/convex-posthog"; import { components } from "./_generated/api"; const posthog = new PostHog(components.posthog, { apiKey: "phc_your_key", host: "https://us.i.posthog.com", }); ``` -------------------------------- ### Run Tests Source: https://github.com/samhoque/convex-posthog/blob/main/README.md Executes the test suite for the component. ```bash npm test ``` -------------------------------- ### Build a One-Off Package Source: https://github.com/samhoque/convex-posthog/blob/main/CONTRIBUTING.md Cleans the dist directory and creates a packaged version of the project using npm pack. ```sh rm -rf dist/ && npm run build npm pack ``` -------------------------------- ### Configure PostHog for Self-Hosted Instance Source: https://github.com/samhoque/convex-posthog/blob/main/_autodocs/api-reference/PostHogOptions.md Initialize the PostHog client with API key and host for a self-hosted PostHog deployment. ```typescript const posthog = new PostHog(components.posthog, { apiKey: "your_self_hosted_api_key", host: "https://analytics.mycompany.com", }); ``` -------------------------------- ### PostHog Constructor Options Source: https://github.com/samhoque/convex-posthog/blob/main/_autodocs/INDEX.md Configure PostHog with an API key and host. The host defaults to the US Cloud if not specified. ```typescript { apiKey?: string; host?: string; } ``` -------------------------------- ### Package Entry Points Configuration Source: https://github.com/samhoque/convex-posthog/blob/main/_autodocs/module-graph.md Defines the various entry points for the @samhoque/convex-posthog package, allowing different modules and types to be imported. ```json "exports": { "./package.json": "./package.json", ".": { "@convex-dev/component-source": "./src/client/index.ts", "types": "./dist/client/index.d.ts", "default": "./dist/client/index.js" }, "./test": "./src/test.ts", "./_generated/component.js": { "types": "./dist/component/_generated/component.d.ts", "default": "./dist/component/_generated/component.js" }, "./convex.config": { "@convex-dev/component-source": "./src/component/convex.config.ts", "types": "./dist/component/convex.config.d.ts", "default": "./dist/component/convex.config.js" }, "./convex.config.js": { "@convex-dev/component-source": "./src/component/convex.config.ts", "types": "./dist/component/convex.config.d.ts", "default": "./dist/component/convex.config.js" } } ``` -------------------------------- ### Initialize PostHog with Explicit API Key Source: https://github.com/samhoque/convex-posthog/blob/main/_autodocs/api-reference/PostHogOptions.md Configure the PostHog client by providing an explicit API key, while using environment variables for the host. ```typescript const posthog = new PostHog(components.posthog, { apiKey: "phc_custom_key_xyz", }); ``` -------------------------------- ### Set PostHog API Key in Convex Environment Source: https://github.com/samhoque/convex-posthog/blob/main/_autodocs/errors.md Before deploying, set your PostHog API key in the Convex environment variables. Tracking will silently fail without a valid API key. ```bash npx convex env set POSTHOG_API_KEY your_key ``` -------------------------------- ### PostHog Initialization Without API Key Source: https://github.com/samhoque/convex-posthog/blob/main/_autodocs/errors.md Demonstrates initializing PostHog without a configured API key. This will result in a console warning and skipped event tracking. ```typescript const posthog = new PostHog(components.posthog); // No API key await posthog.trackUserEvent(ctx, { userId: "user_123", event: "test_event", }); // Console logs: "PostHog API key not configured, skipping event tracking" ``` -------------------------------- ### List Convex Environment Variables Source: https://github.com/samhoque/convex-posthog/blob/main/_autodocs/configuration.md Command to list current environment variables for your Convex project, helpful for verifying POSTHOG_HOST configuration. ```bash npx convex env list ``` -------------------------------- ### Registering with `register()` Directly Source: https://github.com/samhoque/convex-posthog/blob/main/_autodocs/api-reference/test-helper.md Demonstrates the direct usage of the `register()` function after creating a test instance. This approach is an alternative to using the `initConvexTest()` helper. ```typescript const t = convexTest(schema, modules); register(t); ``` -------------------------------- ### Setting PostHog API Key via Constructor Source: https://github.com/samhoque/convex-posthog/blob/main/_autodocs/errors.md Illustrates configuring the PostHog API key directly during component initialization. ```typescript const posthog = new PostHog(components.posthog, { apiKey: "phc_your_key", }); ``` -------------------------------- ### Configure PostHog for EU Cloud Source: https://github.com/samhoque/convex-posthog/blob/main/_autodocs/api-reference/PostHogOptions.md Initialize the PostHog client with specific API key and host for PostHog's EU Cloud environment. ```typescript const posthog = new PostHog(components.posthog, { apiKey: "phc_eu_api_key_here", host: "https://eu.i.posthog.com", }); ``` -------------------------------- ### PostHog Constructor Source: https://github.com/samhoque/convex-posthog/blob/main/_autodocs/api-reference/PostHog.md Initializes a new PostHog client instance. This client is used to send events to PostHog from your Convex application. It can be configured with an API key and host, or it will attempt to use environment variables. ```APIDOC ## PostHog Constructor ### Description Creates a new PostHog client for tracking events in Convex mutations. The constructor validates and stores configuration for API requests. ### Parameters #### Path Parameters - `component` (PostHogComponent) - Required - Reference to the PostHog Convex component from `components.posthog` - `options` (PostHogOptions) - Optional - Configuration object for API key and host - `options.apiKey` (string) - Optional - PostHog API key for authentication - `options.host` (string) - Optional - PostHog host URL (US Cloud by default) ### Return Type `PostHog` instance ### Behavior - If `apiKey` is not provided, attempts to read from `process.env.POSTHOG_API_KEY` - If `host` is not provided, attempts to read from `process.env.POSTHOG_HOST`, falling back to `"https://us.i.posthog.com"` - Does not validate the API key or host at construction time; validation occurs during event tracking ### Example ```typescript import { mutation } from "./_generated/server"; import { components } from "./_generated/api"; import { PostHog } from "@samhoque/convex-posthog"; // Create client with environment variables const posthog = new PostHog(components.posthog); // Or with explicit configuration const posthog = new PostHog(components.posthog, { apiKey: "phc_your_api_key_here", host: "https://us.i.posthog.com", }); // For EU Cloud const posthogEu = new PostHog(components.posthog, { host: "https://eu.i.posthog.com", }); ``` ``` -------------------------------- ### PostHog Constructor Fallback Resolution Logic Source: https://github.com/samhoque/convex-posthog/blob/main/_autodocs/api-reference/PostHogOptions.md Illustrates the order of resolution for apiKey and host properties when initializing the PostHog constructor. ```plaintext For apiKey: 1. options.apiKey (if provided) 2. process.env.POSTHOG_API_KEY 3. Empty string (tracking skipped with warning) For host: 1. options.host (if provided) 2. process.env.POSTHOG_HOST 3. "https://us.i.posthog.com" ``` -------------------------------- ### Register Early for Multiple Tests Source: https://github.com/samhoque/convex-posthog/blob/main/_autodocs/api-reference/test-helper.md Shows the best practice of registering the component early, specifically within a `beforeEach` block, to ensure it's available for multiple tests in a suite. ```typescript beforeEach(() => { t = convexTest(schema, modules); register(t); }); ``` -------------------------------- ### Component Configuration Source: https://github.com/samhoque/convex-posthog/blob/main/_autodocs/INDEX.md Default configuration for the component. ```APIDOC ## Default Component Configuration ### Description Default definition for the component. ### Location `src/component/convex.config.ts` ``` -------------------------------- ### Initialize Convex Test Helper Source: https://github.com/samhoque/convex-posthog/blob/main/_autodocs/api-reference/test-helper.md This snippet shows how to initialize the `initConvexTest` helper from the library, which is a convenient way to set up your test environment. ```typescript import { initConvexTest } from "@samhoque/convex-posthog"; // Equivalent to: // const t = convexTest(schema, modules); // register(t, "posthog"); const t = initConvexTest(); ``` -------------------------------- ### Import Convex Configuration Source: https://github.com/samhoque/convex-posthog/blob/main/_autodocs/MANIFEST.txt Import the PostHog configuration for Convex. ```typescript import posthog from "@samhoque/convex-posthog/convex.config" ``` -------------------------------- ### PostHog Constructor Source: https://github.com/samhoque/convex-posthog/blob/main/_autodocs/MANIFEST.txt Instantiates the PostHog class. It requires a PostHogComponent and optionally accepts PostHogOptions. ```APIDOC ## CONSTRUCTOR ### Description Instantiates the PostHog class. ### Signature `new PostHog(component: PostHogComponent, options?: PostHogOptions)` ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Parameters - **component** (PostHogComponent) - Required - The component to use for PostHog integration. - **options** (PostHogOptions) - Optional - Configuration options for PostHog. ``` -------------------------------- ### Checking Convex Logs for PostHog Warnings Source: https://github.com/samhoque/convex-posthog/blob/main/_autodocs/errors.md Shows the command to view Convex logs, where warnings related to PostHog tracking failures (e.g., network issues, invalid configurations) can be found. Look for messages prefixed with 'PostHog'. ```bash npx convex logs ``` -------------------------------- ### Instantiate PostHog Source: https://github.com/samhoque/convex-posthog/blob/main/_autodocs/MANIFEST.txt Create a new PostHog instance with a component and optional options. ```typescript new PostHog(component: PostHogComponent, options?: PostHogOptions) ``` -------------------------------- ### Deploy an Alpha Release Source: https://github.com/samhoque/convex-posthog/blob/main/CONTRIBUTING.md Prepares and publishes an alpha release of the package. This involves setting the pre-release version with an alpha identifier and publishing with the 'alpha' tag. ```sh npm version prerelease --preid alpha npm publish --tag alpha ``` -------------------------------- ### Track Event with Property Merging Source: https://github.com/samhoque/convex-posthog/blob/main/_autodocs/api-reference/trackEvent.md Demonstrates how to use trackEvent with userId, event, properties, setProperties, and setOnceProperties. The resulting properties object shows how these are merged according to PostHog's conventions. ```typescript trackEvent({ userId: "user_123", event: "purchase", properties: { amount: 99.99, currency: "USD", }, setProperties: { lastPurchaseAmount: 99.99, lastPurchaseDate: "2024-06-27", }, setOnceProperties: { firstPurchaseDate: "2024-06-27", }, }) // Results in properties object: // { // amount: 99.99, // currency: "USD", // $set: { // lastPurchaseAmount: 99.99, // lastPurchaseDate: "2024-06-27", // }, // $set_once: { // firstPurchaseDate: "2024-06-27", // }, // $lib: "convex-posthog", // $lib_version: "0.1.1", // } ``` -------------------------------- ### Set Convex Environment Variables for PostHog Source: https://github.com/samhoque/convex-posthog/blob/main/_autodocs/api-reference/PostHogOptions.md Commands to set PostHog API key and host environment variables within a Convex deployment using the CLI. ```bash npx convex env set POSTHOG_API_KEY "phc_your_api_key_here" npx convex env set POSTHOG_HOST "https://us.i.posthog.com" ``` -------------------------------- ### Standard Usage Imports for Convex PostHog Source: https://github.com/samhoque/convex-posthog/blob/main/_autodocs/module-graph.md Import the main client, component types, context types, configuration, and testing utilities for standard usage. This is the recommended approach. ```typescript import { PostHog, type PostHogComponent, type PostHogOptions } from "@samhoque/convex-posthog" // Context types import type { RunMutationCtx } from "@samhoque/convex-posthog" // Component config import posthog from "@samhoque/convex-posthog/convex.config" // Testing import { register } from "@samhoque/convex-posthog/test" ``` -------------------------------- ### Set Production Environment Variables for PostHog Source: https://github.com/samhoque/convex-posthog/blob/main/_autodocs/configuration.md Commands to set the POSTHOG_API_KEY and POSTHOG_HOST environment variables for your Convex production deployment. ```bash # Set production environment variables npx convex env set POSTHOG_API_KEY phc_prod_key --prod npx convex env set POSTHOG_HOST https://us.i.posthog.com --prod ``` -------------------------------- ### Valid PostHogOptions Type Usage Source: https://github.com/samhoque/convex-posthog/blob/main/_autodocs/api-reference/PostHogOptions.md Demonstrates valid ways to define and use the PostHogOptions type, including full, partial, and empty configurations. ```typescript // ✅ Valid const opts: PostHogOptions = { apiKey: "phc_123", host: "https://us.i.posthog.com", }; // ✅ Valid (empty object) const opts2: PostHogOptions = {}; // ✅ Valid (partial) const opts3: PostHogOptions = { apiKey: "phc_456", }; ``` -------------------------------- ### PostHog Client Source: https://github.com/samhoque/convex-posthog/blob/main/_autodocs/MANIFEST.txt The main client class for interacting with PostHog. It allows for the creation of client instances and tracking user events. ```APIDOC ## PostHog Client Class ### Description This class is the primary interface for sending event data to PostHog. It provides methods for initialization and event tracking. ### Methods #### `PostHog.constructor(options: PostHogOptions)` ##### Description Initializes a new instance of the PostHog client. ##### Parameters - **options** (PostHogOptions) - Required - Configuration options for the PostHog client, including API keys and host. #### `PostHog.trackUserEvent(event: string, properties?: Record): Promise` ##### Description Asynchronously tracks a user event. This method is non-blocking and sends the event data to PostHog. ##### Parameters - **event** (string) - Required - The name of the event to track. - **properties** (Record) - Optional - An object containing custom properties associated with the event. ``` -------------------------------- ### Import PostHog and PostHogOptions Source: https://github.com/samhoque/convex-posthog/blob/main/_autodocs/MANIFEST.txt Import the necessary PostHog class and PostHogOptions type from the library. ```typescript import { PostHog } from "@samhoque/convex-posthog" import type { PostHogOptions } from "@samhoque/convex-posthog" ``` -------------------------------- ### Set Environment Variables for PostHog Source: https://github.com/samhoque/convex-posthog/blob/main/README.md Configure essential PostHog environment variables for your Convex deployment. The API key is mandatory, and the host is optional, defaulting to the US Cloud endpoint. ```bash POSTHOG_API_KEY=your_api_key_here POSTHOG_HOST=https://us.i.posthog.com # Optional, defaults to US Cloud # For EU Cloud use: https://eu.i.posthog.com ``` -------------------------------- ### Verify PostHog Configuration Source: https://github.com/samhoque/convex-posthog/blob/main/_autodocs/errors.md Log the PostHog configuration details, including the API key (partially masked) and host, to ensure they are set correctly in the environment. ```typescript console.log("PostHog Config:", { apiKey: process.env.POSTHOG_API_KEY?.substring(0, 10) + "...", host: process.env.POSTHOG_HOST, }); ``` -------------------------------- ### Set Environment Variables via Convex CLI Source: https://github.com/samhoque/convex-posthog/blob/main/README.md Use the Convex CLI to set environment variables for PostHog configuration. This is an alternative to setting them in the Convex dashboard. ```bash npx convex env set POSTHOG_API_KEY your_api_key_here npx convex env set POSTHOG_HOST https://us.i.posthog.com # Or https://eu.i.posthog.com for EU Cloud ``` -------------------------------- ### Per-Mutation PostHog Instances Source: https://github.com/samhoque/convex-posthog/blob/main/_autodocs/configuration.md Instantiate multiple PostHog clients with different configurations for use in separate mutations. This allows for distinct tracking instances per mutation. ```typescript import { mutation } from "./_generated/server"; import { components } from "./_generated/api"; import { PostHog } from "@samhoque/convex-posthog"; const analyticsPosthog = new PostHog(components.posthog, { apiKey: "phc_analytics_key", }); const productionPosthog = new PostHog(components.posthog, { apiKey: "phc_production_key", host: "https://eu.i.posthog.com", }); export const trackAnalytics = mutation({ handler: async (ctx, args) => { await analyticsPosthog.trackUserEvent(ctx, { userId: "user_123", event: "analytics_event", }); }, }); export const trackProduction = mutation({ handler: async (ctx, args) => { await productionPosthog.trackUserEvent(ctx, { userId: "user_123", event: "production_event", }); }, }); ``` -------------------------------- ### Import PostHog Class Source: https://github.com/samhoque/convex-posthog/blob/main/_autodocs/api-reference/PostHog.md Import the PostHog class from the SDK. ```typescript import { PostHog } from "@samhoque/convex-posthog"; ``` -------------------------------- ### Handling Network/Fetch Exception Source: https://github.com/samhoque/convex-posthog/blob/main/_autodocs/errors.md Shows the console output when a network exception occurs during a fetch request. The mutation continues normally. ```console Console: "PostHog tracking failed:" Error: Network request failed ``` -------------------------------- ### Stream Convex Backend Logs Source: https://github.com/samhoque/convex-posthog/blob/main/_autodocs/errors.md Use the Convex CLI to stream logs from your backend in real-time, which is useful for monitoring and debugging. ```bash npx convex logs --follow ``` -------------------------------- ### Set POSTHOG_API_KEY Environment Variable Source: https://github.com/samhoque/convex-posthog/blob/main/_autodocs/configuration.md Set the `POSTHOG_API_KEY` environment variable to authenticate PostHog API requests. If not set, tracking is skipped and a warning is logged. ```bash npx convex env set POSTHOG_API_KEY your_api_key_here ``` -------------------------------- ### PostHog Class Methods Source: https://github.com/samhoque/convex-posthog/blob/main/_autodocs/INDEX.md This section details the methods available on the PostHog class for tracking user events within your Convex application. ```APIDOC ## PostHog Class ### `new PostHog(component: PostHogComponent, options?: PostHogOptions)` Initializes a new PostHog instance. ### `async trackUserEvent(ctx: RunMutationCtx, data: { userId: string; event: string; properties?: Record; setProperties?: Record; setOnceProperties?: Record; }): Promise` Tracks a user event with optional properties. This method is asynchronous and returns a Promise that resolves when the event has been processed. ```