Install and configure PostHog SDK/CLI authentication.
Use when setting up a new PostHog integration, configuring API keys,
or initializing PostHog in your project.
Trigger with phrases like "install posthog", "setup posthog",
"posthog auth", "configure posthog API key".
Install PostHog SDKs and configure authentication. PostHog uses two key types: Project API Key (phc_...) for event capture (public, safe for frontend) and Personal API Key (phx_...) for private API endpoints (never expose to clients).
# .env (add to .gitignore — never commit)
NEXT_PUBLIC_POSTHOG_KEY=phc_your_project_api_key # Safe for frontend
POSTHOG_HOST=https://us.i.posthog.com # US Cloud (or eu.i.posthog.com)
POSTHOG_PERSONAL_API_KEY=phx_your_personal_key # Server-only, never expose
POSTHOG_PROJECT_ID=12345 # From project URL
Step 3: Initialize Browser SDK (posthog-js)
// lib/posthog.ts
import posthog from 'posthog-js';
export function initPostHog() {
if (typeof window === 'undefined') return;
posthog.init(process.env.NEXT_PUBLIC_POSTHOG_KEY!, {
api_host: process.env.NEXT_PUBLIC_POSTHOG_HOST || 'https://us.i.posthog.com',
capture_pageview: true, // Auto-capture $pageview
capture_pageleave: true, // Auto-capture $pageleave
autocapture: true, // Auto-capture clicks, inputs, form submits
persistence: 'localStorage+cookie',
loaded: (ph) => {
if (process.env.NODE_ENV === 'development') {
ph.debug(); // Logs all events to console
}
},
});
}
Step 4: Initialize Server SDK (posthog-node)
// lib/posthog-server.ts
import { PostHog } from 'posthog-node';
let client: PostHog | null = null;
export function getPostHog(): PostHog {
if (!client) {
client = new PostHog(process.env.NEXT_PUBLIC_POSTHOG_KEY!, {
host: process.env.POSTHOG_HOST || 'https://us.i.posthog.com',
flushAt: 20, // Send batch when 20 events queued
flushInterval: 10000, // Or every 10 seconds
personalApiKey: process.env.POSTHOG_PERSONAL_API_KEY, // Enables local flag eval
});
}
return client;
}
// CRITICAL: Flush before process exits (especially in serverless)
export async function shutdownPostHog() {
if (client) {
await client.shutdown();
client = null;
}
}