Intermediate
How to send custom events on PostHog
Quick Answer
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
1
Install and Initialize PostHog SDK
First, install the PostHog SDK for your platform. For JavaScript/web applications, add the PostHog snippet to your HTML or install via npm:
Initialize PostHog in your application with your project API key:
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'
})Tip
You can find your API key in PostHog under Project Settings > Project API Key
2
Define Your Custom Event Structure
Before sending events, plan your event naming convention and properties. Use descriptive names in snake_case format:
Example 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'
}
}Tip
Keep event names consistent and avoid special characters or spaces
3
Send Basic Custom Events
Use the
Real example for tracking a button click:
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'
})
})Tip
Always include relevant context in your event properties to make analysis easier later
4
Add User Identification
Identify users to connect events across sessions using
After identification, all subsequent events will be associated with this user. You can also set user properties separately:
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()
})Tip
Call identify() as early as possible after user login or signup for accurate user tracking
5
Implement Event Tracking for Key Actions
Add custom events for important user actions throughout your application:
Form Submissions:
Feature Usage:
Error Tracking:
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'
})Tip
Focus on tracking events that align with your business goals and user journey milestones
6
Test Events in PostHog Dashboard
Navigate to your PostHog dashboard and go to Events > Live Events to see your custom events in real-time. Verify that:
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.
- 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.
Tip
Use PostHog's debug mode by adding ?posthog_debug=1 to your URL to see detailed logging in browser console
7
Set Up Event Validation and Monitoring
Create validation rules and monitoring for your custom events:
Add Event Validation:
Set up alerts in PostHog by going to Insights > create a trend for your custom event > click Alerts to monitor event volume changes.
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.
Tip
Consider implementing a wrapper function for consistent event tracking across your application
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.Ready to get started with PostHog?
Put this tutorial into practice. Visit PostHog and follow the steps above.
Visit PostHog →