nuxt-posthog icon indicating copy to clipboard operation
nuxt-posthog copied to clipboard

How to use posthog in Nitro Server Handlers?

Open davidboom95 opened this issue 5 months ago • 3 comments

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
})

davidboom95 avatar Sep 04 '24 03:09 davidboom95