I usually use posthog for all my analytics needs, it is a great solution to track all the web analytics and also the product analytics. I also really like the ability to easily make custom dashboards.
For this reason when I want to track errors in the backend API of one of my projects I turned also to posthog. There is no information on how to integrate these two so that is why I wrote this guide.
Usually posthog is run on the client side. And for the server side, the posthog team has created posthog-node
for nodejs, hence the name. This github project is an easy way to create a client and send events from your node.js server.
However since I was running my nuxt site on cloudflare
this does not work. Because cloudflare
does not run your code on nodejs
. It instead runs your code with cloudflare workers, cloudflare’s own javascript runtime.
So in this article we will see how to make a simple client for posthog from scratch which runs like a well oiled machine on cloudflare
.
The Solution
Create a new file server/utils/posthog.ts
.
Then we can create a server composable called usePosthog()
. The only critical API request is sending events to posthog.
interface Payload {
api_key: string;
event: string;
timestamp?: string;
distinct_id: string;
properties?: any;
}
export async function usePosthog() {
}