How to send custom events on PostHog
Custom events in PostHog are sent using the posthog.capture() method with an event name and optional properties. You can track user interactions, business metrics, or any custom behavior by implementing the capture function in your code.
Prerequisites
- PostHog account with active project
- Basic understanding of JavaScript or your preferred programming language
- Application or website where you want to track events
- PostHog SDK installed in your project
Step-by-Step Instructions
Install and Initialize PostHog SDK
npm install posthog-jsInitialize PostHog in your application with your project API key:
import posthog from 'posthog-js'
posthog.init('YOUR_API_KEY', {
api_host: 'https://app.posthog.com'
})Define Your Custom Event Structure
- Event name: describes the action (e.g.,
button_clicked,purchase_completed) - Properties: additional context as key-value pairs
- User properties: attributes about the user performing the action
Example event structure:
{
event: 'product_purchased',
properties: {
product_name: 'Premium Plan',
price: 29.99,
currency: 'USD'
}
}Send Basic Custom Events
posthog.capture() method to send your custom events. The basic syntax is:posthog.capture('event_name', {
property1: 'value1',
property2: 'value2'
})Real example for tracking a button click:
document.getElementById('signup-button').addEventListener('click', function() {
posthog.capture('signup_button_clicked', {
button_location: 'header',
page_url: window.location.href,
user_type: 'visitor'
})
})Add User Identification
posthog.identify():posthog.identify('user_12345', {
email: 'user@example.com',
name: 'John Doe',
plan: 'premium'
})After identification, all subsequent events will be associated with this user. You can also set user properties separately:
posthog.people.set({
subscription_status: 'active',
last_login: new Date().toISOString()
})Implement Event Tracking for Key Actions
Form Submissions:
posthog.capture('form_submitted', {
form_name: 'contact_form',
form_fields: ['name', 'email', 'message']
})Feature Usage:
posthog.capture('feature_used', {
feature_name: 'advanced_search',
search_query: searchTerm,
results_count: resultsFound
})Error Tracking:
posthog.capture('error_occurred', {
error_type: 'validation_error',
error_message: errorMsg,
page_section: 'checkout'
})Test Events in PostHog Dashboard
- Event names appear correctly
- Properties contain expected values
- User identification is working
- Timestamps are accurate
You can also check the Events tab to see aggregated event data and create insights. Use the search function to filter for your specific custom events by typing the event name in the search bar.
Set Up Event Validation and Monitoring
Add Event Validation:
function trackCustomEvent(eventName, properties) {
if (!eventName || typeof eventName !== 'string') {
console.error('Invalid event name');
return;
}
posthog.capture(eventName, {
...properties,
timestamp: new Date().toISOString(),
source: 'web_app'
});
}Set up alerts in PostHog by going to Insights > create a trend for your custom event > click Alerts to monitor event volume changes.
Common Issues & Troubleshooting
Events not appearing in PostHog dashboard
Check that your API key is correct and that PostHog is properly initialized. Verify network requests in browser dev tools under Network tab for POST requests to PostHog endpoints. Ensure you're looking in the correct project.
Event properties showing as undefined or null
Verify that variables contain values before passing them to posthog.capture(). Add console logging to debug property values: console.log('Properties:', properties) before the capture call.
Duplicate events being sent
Check for multiple event listeners or rapid-fire function calls. Implement debouncing for user interactions: setTimeout(() => posthog.capture(eventName, props), 100) or use flags to prevent duplicate sends.
Events not linking to identified users
Ensure posthog.identify() is called before sending custom events. Check that the user ID is consistent across sessions. Verify user identification in PostHog by checking the Persons tab to see if events are properly attributed.