mitjans / nuxt-posthog

Posthog module for Nuxt
https://nuxt-posthog.cmitjans.dev
MIT License
27 stars 3 forks source link

How to use posthog in Nitro Server Handlers? #43

Open davidboom95 opened 2 months ago

davidboom95 commented 2 months ago

Is it possible?

Appending vanilla implementation:

import { PostHog } from 'posthog-node'

declare module 'h3' {
  interface H3EventContext {
    posthog?: PostHog
    posthogDistinctId?: string
  }
}

export default defineEventHandler(async (event) => {
  const runtimeConfig = useRuntimeConfig()
  const pk = runtimeConfig.public.posthog.publicKey
  const cookieMatch = getCookie(event, `ph_${pk}_posthog`)

  let distinctId
  let posthog

  if (cookieMatch) {
    const parsedValue = JSON.parse(decodeURIComponent(cookieMatch))
    if (parsedValue && parsedValue.distinct_id) {
      distinctId = parsedValue.distinct_id
      posthog = new PostHog(
        pk,
        { host: runtimeConfig.public.posthog.host },
      )
    }
  }

  event.context.posthog = posthog
  event.context.posthogDistinctId = distinctId
})
andrei-vintila commented 2 months ago

Out of pure curiosity what do you want to achieve with this? Especially curios about the getting the distinct id part.

mitjans commented 2 months ago

If you are trying to identify the user in the server, it's something that I wanted to add at some point. I will have to check again now since it's been a while.

Can you confirm this is what you are trying to achieve @davidboom95 ?

davidboom95 commented 2 months ago

That is what I'm trying to achieve, yes.

The main purpose of this particular implementation is to track server events like welcome_event_sent, althought these type of events are triggered by the client in some point, that does not mean the server task is called right away, as some of these events could by run by background tasks.

mitjans commented 1 week ago

Hi @davidboom95! I haven't forgotten about this issue. I've had some busy weeks, but I would like to continue working on it shortly.

Let me know if you have some ideas in mind!