API Reference
Complete API documentation for HydrateBeer
CLI Commands
init
Initialize HydrateBeer in your project with PostHog integration.
npx hydrate-beer-cli initInteractive Setup:
- Select PostHog instance (US Cloud, EU Cloud, or Self-hosted)
- Enter your PostHog Project API Key
- Creates
hydrate-beer.config.tsand.env.local - Auto-installs
hydrate-beerpackage
Generated Files:
hydrate-beer.config.ts:
import type { HydrateBeerConfig } from 'hydrate-beer';
const config: HydrateBeerConfig = {
posthogApiKey: process.env.NEXT_PUBLIC_HYDRATE_BEER_POSTHOG_API_KEY!,
posthogHost: 'https://us.posthog.com',
};
export default config;.env.local:
NEXT_PUBLIC_HYDRATE_BEER_POSTHOG_API_KEY=phc_your_api_key_hereReact Provider
HydrateBeerProvider
Root provider component that initializes PostHog event tracking.
function HydrateBeerProvider(props: {
config: HydrateBeerConfig;
children: React.ReactNode;
}): JSX.ElementProps:
| Prop | Type | Required | Description |
|---|---|---|---|
config | HydrateBeerConfig | Yes | PostHog configuration object |
children | React.ReactNode | Yes | Your app components |
Example:
'use client';
import { HydrateBeerProvider } from "hydrate-beer/react";
export default function RootLayout({ children }) {
return (
<html lang="en">
<body>
<HydrateBeerProvider
config={{
posthogApiKey: process.env.NEXT_PUBLIC_HYDRATE_BEER_POSTHOG_API_KEY!,
posthogHost: 'https://us.posthog.com',
}}
>
{children}
</HydrateBeerProvider>
</body>
</html>
);
}import { HydrateBeerProvider } from "hydrate-beer/react";
import type { AppProps } from 'next/app';
export default function App({ Component, pageProps }: AppProps) {
return (
<HydrateBeerProvider
config={{
posthogApiKey: process.env.NEXT_PUBLIC_HYDRATE_BEER_POSTHOG_API_KEY!,
}}
>
<Component {...pageProps} />
</HydrateBeerProvider>
);
}import { HydrateBeerProvider } from "hydrate-beer/react";
function App() {
return (
<HydrateBeerProvider
config={{
posthogApiKey: process.env.REACT_APP_HYDRATE_BEER_POSTHOG_API_KEY!,
}}
>
{/* Your app */}
</HydrateBeerProvider>
);
}The provider automatically tracks page views, navigation, component performance, and errors. All events are sent to PostHog with the prefix hydratebeer_.
React Hooks
useHydrateBeer()
Access HydrateBeer tracking functions from any component within the provider.
function useHydrateBeer(): {
trackCustomEvent: (name: string, metadata?: Record<string, any>) => void;
trackError: (error: Error, metadata?: Record<string, any>) => void;
sessionId: string;
}Returns:
| Property | Type | Description |
|---|---|---|
trackCustomEvent | Function | Track custom events to PostHog |
trackError | Function | Track errors with stack traces |
sessionId | string | Current user session ID |
Example:
'use client';
import { useHydrateBeer } from "hydrate-beer/react";
export default function MyComponent() {
const { trackCustomEvent, trackError, sessionId } = useHydrateBeer();
const handlePurchase = () => {
trackCustomEvent("product_purchased", {
productId: "123",
price: 29.99,
currency: "USD",
});
};
const handleError = (error: Error) => {
trackError(error, {
context: "checkout_flow",
userId: sessionId,
});
};
return (
<div>
<button onClick={handlePurchase}>Buy Now</button>
</div>
);
}PostHog Event Name: Custom events are sent as hydratebeer_custom with your event name in the properties.
Configuration Types
HydrateBeerConfig
Configuration object for PostHog integration.
interface HydrateBeerConfig {
// Required
posthogApiKey: string; // Your PostHog Project API Key
// Optional
posthogHost?: string; // Default: 'https://us.posthog.com'
debug?: boolean; // Default: false
batchSize?: number; // Default: 10
flushInterval?: number; // Default: 5000 (ms)
autoTrackRoutes?: boolean; // Default: true
trackComponentPerformance?: boolean; // Default: true
trackErrors?: boolean; // Default: true
trackSessions?: boolean; // Default: true
}Configuration Options:
| Option | Type | Default | Description |
|---|---|---|---|
posthogApiKey | string | - | Required. Your PostHog Project API Key |
posthogHost | string | 'https://us.posthog.com' | PostHog instance URL |
debug | boolean | false | Enable console logging |
batchSize | number | 10 | Events per batch |
flushInterval | number | 5000 | Milliseconds between flushes |
autoTrackRoutes | boolean | true | Track navigation automatically |
trackComponentPerformance | boolean | true | Track component render times |
trackErrors | boolean | true | Track errors automatically |
trackSessions | boolean | true | Track user sessions |
Example:
const config: HydrateBeerConfig = {
posthogApiKey: process.env.NEXT_PUBLIC_HYDRATE_BEER_POSTHOG_API_KEY!,
posthogHost: 'https://eu.posthog.com',
debug: process.env.NODE_ENV === 'development',
batchSize: 15,
flushInterval: 3000,
autoTrackRoutes: true,
trackComponentPerformance: true,
trackErrors: true,
trackSessions: true,
};Event Types
All events sent to PostHog are prefixed with hydratebeer_ to namespace them from other analytics.
Automatic Events
These events are tracked automatically when enabled:
hydratebeer_page_view
Triggered on page navigation.
{
event: 'hydratebeer_page_view',
properties: {
path: string; // Current route path
referrer: string; // Previous page
sessionId: string; // Session identifier
timestamp: string; // ISO timestamp
}
}hydratebeer_navigation
Triggered on route changes.
{
event: 'hydratebeer_navigation',
properties: {
from: string; // Previous route
to: string; // New route
duration: number; // Navigation time (ms)
sessionId: string;
timestamp: string;
}
}hydratebeer_component_render
Triggered when components render (if trackComponentPerformance: true).
{
event: 'hydratebeer_component_render',
properties: {
componentName: string; // Component display name
duration: number; // Render time (ms)
phase: 'mount' | 'update';
isSlow: boolean; // Duration > 16ms
sessionId: string;
timestamp: string;
}
}hydratebeer_error
Triggered when errors occur (if trackErrors: true).
{
event: 'hydratebeer_error',
properties: {
message: string; // Error message
stack: string; // Stack trace
componentStack?: string; // React component stack
sessionId: string;
timestamp: string;
}
}hydratebeer_session_start
Triggered when a new session begins.
{
event: 'hydratebeer_session_start',
properties: {
sessionId: string;
userAgent: string;
timestamp: string;
}
}Custom Events
hydratebeer_custom
Your custom tracked events.
trackCustomEvent('button_clicked', { buttonId: 'submit' });
// Sends to PostHog:
{
event: 'hydratebeer_custom',
properties: {
customEventName: 'button_clicked',
buttonId: 'submit',
sessionId: string;
timestamp: string;
}
}Viewing Events in PostHog
All events appear in your PostHog dashboard:
- Navigate to Activity → Events
- Filter by event names starting with
hydratebeer_ - Create insights and dashboards from your events
- Set up alerts for errors or performance issues
Common Queries:
-- Page views by path
SELECT properties.path, count()
FROM events
WHERE event = 'hydratebeer_page_view'
GROUP BY properties.path
-- Average component render times
SELECT properties.componentName, avg(properties.duration)
FROM events
WHERE event = 'hydratebeer_component_render'
GROUP BY properties.componentName
-- Error rate
SELECT count()
FROM events
WHERE event = 'hydratebeer_error'Best Practices
1. Use Environment Variables
Never hardcode your PostHog API key. Always use environment variables.
// ✅ Good
config={{
posthogApiKey: process.env.NEXT_PUBLIC_HYDRATE_BEER_POSTHOG_API_KEY!,
}}
// ❌ Bad
config={{
posthogApiKey: 'phc_abc123...', // Don't hardcode!
}}2. Enable Debug Mode in Development
const config: HydrateBeerConfig = {
posthogApiKey: process.env.NEXT_PUBLIC_HYDRATE_BEER_POSTHOG_API_KEY!,
debug: process.env.NODE_ENV === 'development',
};3. Optimize Batch Configuration
// High-traffic app: larger batches, less frequent flushes
const config: HydrateBeerConfig = {
posthogApiKey: process.env.NEXT_PUBLIC_HYDRATE_BEER_POSTHOG_API_KEY!,
batchSize: 20,
flushInterval: 10000,
};
// Real-time monitoring: smaller batches, frequent flushes
const config: HydrateBeerConfig = {
posthogApiKey: process.env.NEXT_PUBLIC_HYDRATE_BEER_POSTHOG_API_KEY!,
batchSize: 5,
flushInterval: 2000,
};4. Track Meaningful Custom Events
// ✅ Good - Business-relevant events
trackCustomEvent('product_added_to_cart', {
productId: '123',
price: 29.99,
});
trackCustomEvent('checkout_completed', {
orderId: 'ord_456',
total: 99.97,
});
// ❌ Bad - Too granular
trackCustomEvent('mouse_moved'); // Too noisy
trackCustomEvent('div_rendered'); // Not actionable5. Add Context to Errors
try {
await processPayment();
} catch (error) {
trackError(error as Error, {
context: 'checkout',
paymentMethod: 'stripe',
amount: total,
});
}TypeScript Support
HydrateBeer is fully typed with TypeScript.
import type { HydrateBeerConfig } from 'hydrate-beer';
// Full autocomplete and type checking
const config: HydrateBeerConfig = {
posthogApiKey: '...', // Type: string
debug: true, // Type: boolean
batchSize: 10, // Type: number
};Next Steps
- Configuration Guide - Detailed configuration options
- Quick Start - Get up and running quickly
- PostHog Dashboard - View your analytics