PostHog / posthog-js

Send usage data from your web app or site to PostHog, with autocapture.
https://posthog.com/docs/libraries/js
Other
235 stars 103 forks source link

Using the Sentry Posthog integration on the server with NextJS in Vercel #1175

Open osdiab opened 2 months ago

osdiab commented 2 months ago

I was wondering what is the right way to use the Sentry integration with Posthog in the Vercel environment. Basically:

https://posthog.com/docs/libraries/node#example-implementation

  Sentry.captureException(err, {
    tags: {
      [PostHogSentryIntegration.POSTHOG_ID_TAG]: request.user.id,
    },
  })

If I do this, still not sure how to handle the shutdown() function, should I be calling it perhaps by listening for events like SIGINT and calling it then or something?

Some guidance on the proper way to set this up so that server logs can also be tagged with Posthog would make tracking a user's journey across the backend and frontend much smoother, as it's clear how to set it up on the client side. Thanks!

mason-os commented 1 week ago

@osdiab did you end up getting this setup? I'm facing the same questions you had, I'm looking at setting up a Sentry/Posthog/Next/Vercel project with the integration.

mason-os commented 1 week ago

I ended up finding this posthog community discussion (I'm guessing that is you based on the user names!).

The solution at the end of that thread worked for me, specifically adding this block after I initialize posthog:


import * as Sentry from "@sentry/nextjs";
import posthog from "posthog-js";

posthog.init(process.env.NEXT_PUBLIC_POSTHOG_KEY, {
  api_host: process.env.NEXT_PUBLIC_POSTHOG_HOST,
});

Sentry.addIntegration(
  new posthog.SentryIntegration(posthog, sentryOrganization, sentryProjectId)
);

This doesn't handle the shutdown issue, but seems to setup the integration in a nice way at least. I'd still be interesting in learning the best practice here!