Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

How to use posthog in Nitro Server Handlers? #43

Open
davidboom95 opened this issue Sep 4, 2024 · 4 comments
Open

How to use posthog in Nitro Server Handlers? #43

davidboom95 opened this issue Sep 4, 2024 · 4 comments

Comments

@davidboom95
Copy link

davidboom95 commented Sep 4, 2024

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
Copy link
Contributor

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

@mitjans
Copy link
Owner

mitjans commented Sep 12, 2024

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
Copy link
Author

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
Copy link
Owner

mitjans commented Nov 17, 2024

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!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

3 participants