nuxt-posthog
nuxt-posthog copied to clipboard
How to use posthog in Nitro Server Handlers?
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
})