Create a minimal working PostHog example.
Use when starting a new PostHog integration, testing your setup,
or learning basic PostHog API patterns.
Trigger with phrases like "posthog hello world", "posthog example",
"posthog quick start", "simple posthog code".
Minimal working examples demonstrating the three core PostHog operations: capturing events, identifying users, and evaluating feature flags. Covers both browser (posthog-js) and server (posthog-node) SDKs.
Prerequisites
Completed posthog-install-auth setup
Project API key (phc_...) configured
posthog-js and/or posthog-node installed
Instructions
Step 1: Capture Your First Event (Node.js)
// hello-posthog.ts
import { PostHog } from 'posthog-node';
const posthog = new PostHog(process.env.NEXT_PUBLIC_POSTHOG_KEY!, {
host: 'https://us.i.posthog.com',
});
async function main() {
// 1. Capture a custom event
posthog.capture({
distinctId: 'user-123',
event: 'hello_posthog',
properties: {
greeting: 'Hello from posthog-node!',
source: 'hello-world-skill',
timestamp: new Date().toISOString(),
},
});
console.log('Event captured: hello_posthog');
// 2. Identify a user with properties
posthog.identify({
distinctId: 'user-123',
properties: {
email: '[email protected]',
name: 'Dev User',
plan: 'free',
},
});
console.log('User identified: user-123');
// 3. Check a feature flag
const flagValue = await posthog.getFeatureFlag('my-feature-flag', 'user-123');
console.log(`Feature flag "my-feature-flag": ${flagValue}`);
// 4. Flush and shutdown (required in scripts/serverless)
await posthog.shutdown();
console.log('Done — check app.posthog.com Activity tab');
}
main().catch(console.error);
Step 2: Browser Hello World (posthog-js)
// In a React component or vanilla JS
import posthog from 'posthog-js';
// Initialize (call once at app startup)
posthog.init('phc_your_project_key', {
api_host: 'https://us.i.posthog.com',
loaded: () => console.log('PostHog loaded'),
});
// Capture a custom event
posthog.capture('button_clicked', {
button_name: 'signup',
page: window.location.pathname,
});
// Identify the user after login
posthog.identify('user-123', {
email: '[email protected]',
plan: 'pro',
});
// Check a feature flag
if (posthog.isFeatureEnabled('new-checkout')) {
console.log('New checkout flow is enabled');
}
// Associate user with a company (group analytics)
posthog.group('company', 'company-456', {
name: 'Acme Corp',
plan: 'enterprise',
});