@akson/cortex-posthog
v0.5.0
Published
PostHog API client and MCP server for analytics and event tracking
Maintainers
Readme
@akson/cortex-posthog
TypeScript client for PostHog analytics platform, enabling event tracking, user analytics, feature flags, session recordings, and cohort management.
User Stories
Event Tracking Stories
As a Product Manager, I want to track custom events with properties, so that I can analyze user behavior and feature adoption.
As a Growth Marketing Manager, I want to capture conversion events with revenue data, so that I can measure marketing campaign effectiveness.
As a UX Researcher, I want to track user interactions across different page sections, so that I can optimize user experience based on behavior data.
As a Developer, I want to batch event tracking for performance, so that I can minimize API calls while maintaining data accuracy.
User Analytics Stories
As a Customer Success Manager, I want to identify and track individual users across sessions, so that I can understand user journey and lifecycle.
As a Marketing Analyst, I want to set user properties and traits, so that I can segment users for targeted campaigns.
As a Product Analyst, I want to group users by company or organization, so that I can analyze B2B customer behavior patterns.
As a Data Scientist, I want to track user cohorts and retention, so that I can measure product stickiness and churn.
Analytics & Insights Stories
As a Business Analyst, I want to execute custom queries on event data, so that I can generate specific reports for business stakeholders.
As a Marketing Director, I want to create conversion funnels, so that I can identify drop-off points in the customer journey.
As a Product Owner, I want to analyze user trends over time, so that I can measure feature impact and user engagement.
As a Growth Hacker, I want to track retention cohorts, so that I can optimize user onboarding and engagement strategies.
Feature Flag Management Stories
As a Product Manager, I want to manage feature flags remotely, so that I can control feature rollouts without code deployments.
As a Developer, I want to check feature flag status for users, so that I can conditionally show features based on user segments.
As a QA Engineer, I want to enable features for specific test users, so that I can validate functionality before public release.
As a Growth Product Manager, I want to run A/B tests using feature flags, so that I can measure feature impact on key metrics.
Dashboard & Reporting Stories
As a Marketing Operations Manager, I want to create automated dashboards, so that I can monitor campaign performance in real-time.
As a Executive Stakeholder, I want to access pre-built insights and summaries, so that I can quickly understand business performance.
As a Data Analyst, I want to export raw event data, so that I can perform advanced analysis in external tools.
As a Product Marketing Manager, I want to track specific conversion paths, so that I can optimize messaging and positioning.
Session & User Behavior Stories
As a UX Designer, I want to access session recordings, so that I can understand how users interact with the interface.
As a Customer Support Manager, I want to track user actions before support tickets, so that I can provide more contextual assistance.
As a Conversion Optimization Specialist, I want to analyze user heatmaps and click patterns, so that I can improve page layouts and CTAs.
Cohort & Segmentation Stories
As a Lifecycle Marketing Manager, I want to create user cohorts based on behavior, so that I can send targeted email campaigns.
As a Customer Success Analyst, I want to identify power users and at-risk segments, so that I can personalize retention strategies.
As a Product Marketing Manager, I want to segment users by feature usage, so that I can create targeted onboarding flows.
Integration & Automation Stories
As a Marketing Technology Manager, I want to sync PostHog data with CRM systems, so that I can enrich customer profiles with behavioral data.
As a Developer, I want to trigger automations based on user events, so that I can create dynamic user experiences.
As a Data Engineer, I want to export PostHog data to data warehouses, so that I can combine it with other business data for analysis.
Installation
npm install @akson/cortex-posthogQuick Start
import { PostHogClient } from "@akson/cortex-posthog";
const client = new PostHogClient({
config: {
apiKey: "phc_your_api_key",
host: "https://us.i.posthog.com",
projectId: "your-project-id",
},
});
// Track an event
await client.capture("user-123", "button_click", {
button_name: "signup_cta",
page: "homepage",
campaign: "summer_sale",
});
// Identify a user
await client.identify("user-123", {
email: "[email protected]",
plan: "premium",
signup_date: new Date().toISOString(),
});
// Check feature flag
const flagResult = await client.getFeatureFlag("user-123", "new_dashboard");
if (flagResult.success && flagResult.data.enabled) {
console.log("New dashboard enabled for user");
}
// Query analytics data
const trendsResult = await client.getTrends({
events: ["button_click"],
dateFrom: "2025-01-01",
dateTo: "2025-01-31",
});Configuration
Environment Variables
POSTHOG_API_KEY=phc_your_api_key
POSTHOG_HOST=https://us.i.posthog.com
POSTHOG_PROJECT_ID=your-project-idConfiguration File
Create posthog-config.json:
{
"apiKey": "phc_your_api_key",
"host": "https://us.i.posthog.com",
"projectId": "your-project-id",
"flushAt": 20,
"flushInterval": 10000
}API Reference
Event Tracking
// Capture event with properties
await client.capture(
"user-123",
"purchase_completed",
{
product_id: "prod-456",
revenue: 99.99,
currency: "USD",
category: "electronics",
},
{
timestamp: new Date(),
personProperties: {
customer_type: "premium",
},
}
);
// Batch capture multiple events
await client.batchCapture([
{
distinctId: "user-123",
event: "page_view",
properties: { page: "/home" },
},
{
distinctId: "user-123",
event: "button_click",
properties: { button: "cta_primary" },
},
]);
// Track page views
await client.pageView("user-123", {
page: "/product/123",
title: "Amazing Product",
category: "electronics",
});User Management
// Identify user with properties
await client.identify("user-123", {
email: "[email protected]",
name: "John Doe",
plan: "premium",
signup_date: "2025-01-15",
total_orders: 5,
ltv: 450.0,
});
// Update user properties
await client.setPersonProperties("user-123", {
last_login: new Date().toISOString(),
feature_beta_access: true,
});
// Group users (for B2B)
await client.group("company", "company-456", {
name: "Acme Corp",
plan: "enterprise",
employees: 100,
industry: "technology",
});Feature Flags
// Get feature flag for user
const flagResult = await client.getFeatureFlag("user-123", "new_checkout");
if (flagResult.success && flagResult.data.enabled) {
console.log("New checkout flow enabled");
}
// Get all feature flags for user
const allFlags = await client.getAllFeatureFlags("user-123");
if (allFlags.success) {
Object.entries(allFlags.data).forEach(([flag, enabled]) => {
console.log(`${flag}: ${enabled}`);
});
}
// Get feature flag with payload
const flagWithPayload = await client.getFeatureFlagPayload(
"user-123",
"experiment_config"
);
if (flagWithPayload.success) {
console.log("Experiment config:", flagWithPayload.data.payload);
}Analytics Queries
// Get trends analysis
const trends = await client.getTrends({
events: ["signup", "purchase"],
dateFrom: "2025-01-01",
dateTo: "2025-01-31",
interval: "day",
breakdownBy: "utm_source",
});
// Create funnel analysis
const funnel = await client.getFunnel({
events: [
{ name: "page_view", properties: { page: "/signup" } },
{ name: "form_submit", properties: { form: "signup" } },
{ name: "signup_completed" },
],
dateFrom: "2025-01-01",
dateTo: "2025-01-31",
});
// Retention analysis
const retention = await client.getRetention({
targetEvent: "signup_completed",
returningEvent: "session_start",
dateFrom: "2025-01-01",
dateTo: "2025-01-31",
period: "week",
});
// Custom query
const customQuery = await client.query({
query: `
SELECT
properties.$current_url as page,
count() as page_views
FROM events
WHERE event = 'page_view'
AND timestamp >= '2025-01-01'
GROUP BY page
ORDER BY page_views DESC
LIMIT 10
`,
});Cohorts
// Create cohort
const cohortResult = await client.createCohort({
name: "Power Users",
description: "Users who completed more than 10 actions",
filters: {
events: [
{
name: "any_event",
properties: [],
count_operator: "gte",
count: 10,
},
],
},
});
// Get cohort members
const members = await client.getCohortMembers(cohortResult.data.id);
// Update cohort
await client.updateCohort(cohortResult.data.id, {
name: "Super Power Users",
filters: {
events: [
{
name: "any_event",
count_operator: "gte",
count: 25,
},
],
},
});Dashboards
// Create dashboard
const dashboard = await client.createDashboard({
name: "Marketing Performance",
description: "Key marketing metrics and KPIs",
pinned: true,
});
// Add insight to dashboard
await client.addInsightToDashboard(dashboard.data.id, {
name: "Daily Signups",
query: {
kind: "TrendsQuery",
events: ["signup_completed"],
interval: "day",
},
});
// Get dashboard data
const dashboardData = await client.getDashboard(dashboard.data.id);Error Handling
All methods return PostHogOperationResult<T>:
const result = await client.capture("user-123", "test_event", { value: 1 });
if (result.success) {
console.log("Event tracked successfully");
} else {
console.error("Event tracking failed:", result.error);
if (result.details) {
console.error("Details:", result.details);
}
}Advanced Usage
Real-time Event Streaming
class PostHogStreamer {
constructor(private client: PostHogClient) {}
async streamEvents(userId: string) {
// Track user session start
await this.client.capture(userId, "session_start", {
timestamp: Date.now(),
user_agent: "browser",
});
// Stream page views
const pages = ["/home", "/products", "/checkout"];
for (const page of pages) {
await this.client.pageView(userId, { page });
await new Promise((resolve) => setTimeout(resolve, 2000));
}
// Track conversion
await this.client.capture(userId, "purchase_completed", {
revenue: 99.99,
currency: "USD",
});
}
}A/B Testing Integration
class ABTestManager {
constructor(private client: PostHogClient) {}
async assignVariant(userId: string, experimentName: string) {
const flag = await this.client.getFeatureFlag(userId, experimentName);
if (flag.success) {
const variant = flag.data.enabled ? "treatment" : "control";
// Track assignment
await this.client.capture(userId, "experiment_assigned", {
experiment: experimentName,
variant: variant,
});
return variant;
}
return "control";
}
async trackConversion(
userId: string,
experimentName: string,
conversionEvent: string
) {
await this.client.capture(userId, conversionEvent, {
experiment: experimentName,
});
}
}User Journey Analysis
async function analyzeUserJourney(userId: string) {
// Get user events
const events = await client.getPersonEvents(userId, {
limit: 100,
orderBy: "timestamp",
});
if (events.success) {
const journey = events.data.map((event) => ({
event: event.event,
timestamp: event.timestamp,
page: event.properties.$current_url,
properties: event.properties,
}));
// Analyze patterns
const pages = journey.map((e) => e.page).filter(Boolean);
const uniquePages = [...new Set(pages)];
console.log("User journey:");
console.log("- Pages visited:", uniquePages.length);
console.log("- Total events:", journey.length);
console.log(
"- Session duration:",
new Date(journey[journey.length - 1].timestamp) -
new Date(journey[0].timestamp)
);
return journey;
}
}Performance Monitoring
class PostHogMonitor {
constructor(private client: PostHogClient) {}
async checkAPIHealth() {
try {
const testEvent = await this.client.capture("health-check", "api_test", {
timestamp: Date.now(),
});
if (testEvent.success) {
console.log("✅ PostHog API is healthy");
return true;
} else {
console.error("❌ PostHog API health check failed:", testEvent.error);
return false;
}
} catch (error) {
console.error("❌ PostHog API unreachable:", error);
return false;
}
}
async getEventVolume(dateFrom: string, dateTo: string) {
const volume = await this.client.query({
query: `
SELECT
date(timestamp) as date,
count() as events
FROM events
WHERE timestamp >= '${dateFrom}'
AND timestamp <= '${dateTo}'
GROUP BY date
ORDER BY date
`,
});
return volume;
}
}Integration Examples
Marketing Attribution
async function trackMarketingAttribution(userId: string, utmParams: any) {
// Set marketing properties
await client.identify(userId, {
utm_source: utmParams.utm_source,
utm_medium: utmParams.utm_medium,
utm_campaign: utmParams.utm_campaign,
first_touch_source: utmParams.utm_source,
acquisition_date: new Date().toISOString(),
});
// Track marketing events
await client.capture(userId, "marketing_touch", {
source: utmParams.utm_source,
medium: utmParams.utm_medium,
campaign: utmParams.utm_campaign,
touch_type: "first_touch",
});
}
async function trackConversion(
userId: string,
conversionType: string,
value: number
) {
await client.capture(userId, `${conversionType}_conversion`, {
conversion_value: value,
currency: "USD",
});
// Update user LTV
const user = await client.getPersonProperties(userId);
if (user.success) {
const currentLTV = user.data.ltv || 0;
await client.setPersonProperties(userId, {
ltv: currentLTV + value,
last_conversion_date: new Date().toISOString(),
});
}
}E-commerce Tracking
class EcommerceTracker {
constructor(private client: PostHogClient) {}
async trackAddToCart(userId: string, product: any) {
await this.client.capture(userId, "add_to_cart", {
product_id: product.id,
product_name: product.name,
price: product.price,
currency: product.currency,
category: product.category,
});
}
async trackPurchase(userId: string, order: any) {
await this.client.capture(userId, "purchase_completed", {
order_id: order.id,
total: order.total,
currency: order.currency,
items: order.items.length,
payment_method: order.paymentMethod,
});
// Update customer lifetime value
await this.client.identify(userId, {
total_orders: (order.customerTotalOrders || 0) + 1,
ltv: order.customerLTV + order.total,
last_order_date: new Date().toISOString(),
});
}
}TypeScript Support
Full TypeScript definitions included:
import type {
PostHogEvent,
PostHogFeatureFlag,
PostHogInsight,
PostHogDashboard,
PostHogCohort,
PostHogTrendsResult,
PostHogFunnelsResult,
PostHogRetentionResult,
PostHogOperationResult,
PostHogListResult,
} from "@akson/cortex-posthog";Requirements
- Node.js ≥18.0.0
- PostHog account and API key
- PostHog project access
License
MIT
