6 min read

How to Set Up Alerts for Unique Users in PostHog

If you're not watching your unique user count, you're flying blind. Sudden drops could mean a broken signup flow; spikes might signal product growth or a viral moment. PostHog doesn't have built-in alerts like some tools, but you can trigger notifications using insights, webhooks, and the API to catch issues fast.

Create an Insight to Track Unique Users

The foundation for any alert is a reliable metric. You'll create an insight that counts distinct users over your chosen time window.

Navigate to Insights and create a new event metric

Go to Data > Insights and click New insight. You'll land in the Events query builder, where you define what to measure.

javascript
// Verify PostHog is initialized on your page
import posthog from 'posthog-js';

posthog.init('phc_your_key', {
  api_host: 'https://app.posthog.com',
});

// No additional setup needed—PostHog auto-tracks events once initialized
Initialize PostHog SDK to start capturing user events

Set the metric to Count unique users

In the Events query builder, change the metric from Count to Count unique. This tells PostHog to count each distinct user only once, regardless of how many events they trigger.

javascript
// Query unique users via PostHog API
const projectId = 'YOUR_PROJECT_ID';
const apiKey = 'phc_your_personal_api_key';

const response = await fetch(
  `https://app.posthog.com/api/projects/${projectId}/insights/`,
  {
    headers: {
      'Authorization': `Bearer ${apiKey}`,
      'Content-Type': 'application/json',
    },
  }
);

const insights = await response.json();
const uniqueUserInsight = insights.results.find(i => i.name === 'Unique Users');
console.log('Unique users:', uniqueUserInsight.result);
Fetch saved insights via API to access unique user counts programmatically

Set your time window and save

Choose a time range that matches your alert cadence—24 hours for daily checks, 7 days to smooth out spikes. Click Save and name it 'Unique Users'. PostHog will now track this metric continuously.

Set Up Webhooks for Real-Time Notifications

Once your insight is saved, PostHog can send webhook payloads to your backend whenever the metric updates. Use this to trigger Slack messages, emails, or escalations to PagerDuty.

Create a subscription in PostHog

Open your 'Unique Users' insight and click the three-dot menu (...). Select Create subscription. This opens the webhook configuration panel where you'll paste your endpoint URL.

javascript
// Example webhook receiver (Node.js/Express)
const express = require('express');
const app = express();

app.post('/posthog-webhook', express.json(), (req, res) => {
  const { insight, data } = req.body;
  const uniqueUserCount = data.result?.[0]?.[0]?.value || 0;
  
  console.log(`Unique users: ${uniqueUserCount}`);
  
  // Alert if count drops below threshold
  const threshold = 1000;
  if (uniqueUserCount < threshold) {
    sendSlackAlert(`⚠️ Warning: unique users dropped to ${uniqueUserCount}`);
  }
  
  res.sendStatus(200);
});

app.listen(3000);
Build a webhook receiver to process PostHog insight updates

Configure the webhook URL and frequency

Paste your publicly accessible endpoint URL (e.g., https://your-domain.com/posthog-webhook). Choose delivery frequency: Immediately for real-time alerts, or On schedule (daily/weekly) for daily digests. Most teams prefer daily to reduce noise.

Poll the API for Custom Alert Logic

If webhooks don't fit your workflow, query the PostHog API directly on a schedule. This gives you full control over alert thresholds and integrations.

Get your project ID and generate a personal API key

Find your Project ID in Settings > Project. Generate a Personal API Key in your user settings (Workspace admin > API keys). Save both—you'll need them for every API request.

javascript
// Query unique users for a specific date range
const projectId = 'YOUR_PROJECT_ID';
const apiKey = 'phc_your_personal_api_key';
const insightId = 'YOUR_INSIGHT_ID'; // Get this from the insight URL

const response = await fetch(
  `https://app.posthog.com/api/projects/${projectId}/insights/${insightId}/?date_from=-7d&date_to=today`,
  {
    headers: {
      'Authorization': `Bearer ${apiKey}`,
    },
  }
);

const insight = await response.json();
const latestValue = insight.result?.[0]?.[0]?.value;
console.log('Latest unique user count:', latestValue);

Set up a scheduled job to check unique users

Use a cron job or cloud function (AWS Lambda, Vercel cron, etc.) to call the API hourly or daily. Store the previous count, compare the new count against a baseline, and alert if it deviates beyond your threshold.

javascript
// Cron job to check unique users every hour
const cron = require('node-cron');

async function checkUniqueUsers() {
  const uniqueUserCount = await queryPostHogAPI();
  const previousCount = await getStoredCount();
  const percentChange = ((uniqueUserCount - previousCount) / previousCount) * 100;
  
  // Alert if drop exceeds 15%
  if (percentChange < -15) {
    await sendAlert(`Critical: Unique users dropped ${Math.abs(percentChange).toFixed(1)}% to ${uniqueUserCount}`);
  }
  
  await storeCount(uniqueUserCount);
}

// Run every hour at :00
cron.schedule('0 * * * *', checkUniqueUsers);

Common Pitfalls

  • Confusing unique users with total events. PostHog counts distinct users, not event occurrences—if one user triggers 100 events, they count as 1 unique user.
  • Forgetting idempotency in webhook receivers. PostHog retries failed webhooks up to 5 times; if your endpoint isn't idempotent, you'll get duplicate alerts.
  • Setting alert thresholds too tight. Alerting on every user fluctuation creates alert fatigue. Set thresholds based on your actual baseline and expected variance.
  • Ignoring webhook payload structure. PostHog wraps results in nested arrays; if you don't handle the structure correctly, you'll parse undefined values.

Wrapping Up

You now have three ways to monitor unique user counts in PostHog: via the insight UI, automated webhooks, or scheduled API polling. Start with webhooks for simplicity—they're reliable and require minimal setup. If you want to track this automatically across tools, Product Analyst can help.

Track these metrics automatically

Product Analyst connects to your stack and surfaces the insights that matter.

Try Product Analyst — Free