Setting Up Error Tracking with Sentry and PostHog
#sentry
#posthog
#error-tracking
#frontend
Introduction
Error monitoring and analytics are essential for delivering reliable, user-friendly web applications. Sentry helps you capture and triage errors in production, while PostHog provides lightweight analytics and event telemetry that you can customize to fit your workflow. When used together, you can quickly surface crash reports alongside user behavior data, making it easier to reproduce and fix issues.
Why combine Sentry and PostHog?
- Sentry excels at error capture, grouping, and long-term crash analysis.
- PostHog shines in flexible event tracking, funnels, and product analytics.
- Correlating an error with user context and a unique event heartbeat helps you diagnose issues faster.
Prerequisites
- A web application (vanilla JS or a framework like React, Vue, or Svelte).
- Sentry project setup and a DSN key.
- PostHog project setup and a frontend API key.
- Basic familiarity with npm/yarn or your preferred package manager.
Step 1: Install and configure Sentry
Install the browser SDK and initialize Sentry in your app. Replace the DSN with your actual project DSN or environment variable.
# Using npm
npm install @sentry/browser
// src/sentry.config.js
import * as Sentry from "@sentry/browser";
export function initSentry(dsn) {
Sentry.init({
dsn: dsn || process.env.SENTRY_DSN,
tracesSampleRate: 0.2, // adjust sampling as needed
environment: process.env.NODE_ENV || "development",
});
}
// src/main.js (or your entry point)
import { initSentry } from "./sentry.config";
const dsn = process.env.SENTRY_DSN; // or a hard-coded string for testing
initSentry(dsn);
Step 2: Capture errors client-side
Catch errors and forward them to Sentry. You can augment this with a global error handler for uncaught exceptions.
// Example: manual error capture
try {
// your code that may throw
potentiallyFailingFunction();
} catch (err) {
// Capture the exception in Sentry
const eventId = Sentry.captureException(err);
// Optionally log the event ID somewhere for correlation
console.log("Sentry event ID:", eventId);
}
// Global error handler (optional)
window.onerror = function (message, source, lineno, colno, error) {
const eventId = Sentry.captureException(error || new Error(message));
// Forward to PostHog with correlation
posthog.track("error_occurred", {
message,
source,
line: lineno,
column: colno,
event_id: eventId,
});
return false;
};
Step 3: Install and initialize PostHog
Install the PostHog JavaScript library and initialize it with your frontend API key. This enables you to track custom events and user interactions.
# Using npm
npm install posthog-js
// src/posthog.config.js
import posthog from 'posthog-js';
export function initPostHog(apiKey) {
posthog.init(apiKey, {
api_host: "https://app.posthog.com",
capture_pageview: true,
});
}
export default posthog;
// src/main.js
import { initPostHog } from "./posthog.config";
const apiKey = process.env.POSTHOG_FRONTEND_API_KEY;
initPostHog(apiKey);
Step 4: Correlate Sentry errors with PostHog events
Linking an error to a user session or event in PostHog helps you investigate context. Capture the Sentry event ID and pass it through PostHog when reporting an error.
function reportErrorWithCorrelation(err) {
// Capture in Sentry and obtain the event ID
const eventId = Sentry.captureException(err);
// Track a correlated event in PostHog
posthog.track("error_occurred", {
error_message: err && err.message ? err.message : String(err),
event_id: eventId
});
}
// Example usage
try {
someRiskyOperation();
} catch (err) {
reportErrorWithCorrelation(err);
}
Tips:
- If your app uses a framework-specific SDK (React, Vue, etc.), you can apply the same pattern within components or error boundaries.
- Avoid sending PII in PostHog events. Use user IDs or anonymized identifiers.
Step 5: Testing and monitoring
- Trigger a controlled error in your environment and verify that Sentry receives the error with a recognizable event ID.
- Check PostHog to confirm that the corresponding event was tracked and includes the event_id from Sentry.
- Use Sentry’s issue view to review error counts and stack traces; use PostHog to explore user flows preceding the error.
Best practices
- Environment separation: Use distinct DSNs and API keys for development, staging, and production.
- Data minimization: Do not send sensitive user data; sanitize inputs where possible.
- Sampling: Configure tracesSampleRate to balance data volume and insight.
- User context: Add non-identifying context to Sentry and PostHog, such as app version and feature flags.
- Correlation discipline: Keep a consistent approach to linking Sentry events with PostHog events, so you can reproduce issues quickly.
Troubleshooting
- Sentry not receiving events: verify DSN, network requests, and build configuration. Check Sentry’s DSN in environment variables.
- PostHog events missing: confirm API key and host URL; verify that posthog.init is executed before tracking calls.
- Correlation IDs not appearing: ensure captureException returns an eventId and that it is passed to PostHog.
Conclusion
Setting up error tracking with Sentry and PostHog gives you a holistic view of both failures and user behavior. By correlating a Sentry error with a PostHog event, you can quickly identify root causes and the contexts in which issues occur, accelerating your debugging and product improvement cycles. Keep refining your contexts and sampling to maintain signal quality without overwhelming your monitoring tools.