We had never really tracked events properly. We had some basic tracking in place, but it was not very useful. It is time to improve that with OpenPanel.
After some research, we finally settled on leveraging tRPC and Hono middlewares. Shoutout to Midday for the (tRPC) inspiration. They use a similar approach with next-safe-action for their server actions.
This post is not a step-by-step guide but instead presents the core concepts and ideas behind the implementation. Please refer to the Hono or tRPC documentation for more detailed information and our GitHub repository for the full implementation.
First, let's start with the basics. We need to define the events we want to track, like page_created, user_created, etc.
Now that we have the basic setup in place, we can start implementing the tracking in our application. We will use the tRPC middleware and metadata to track events. Below, we define the trackEvent middleware that will track the event after the procedure has been executed. An enforceUserSession middleware can be added to include the user's ID for tracking.
Voilà! Each time you want to add tracking to a new procedure, you only need to add the meta property with the event you want to track. The middleware handles the rest.
Now, how do we track the events within our API? Let's start by adding the trackMiddleware function and only track the event if the response has been finalized.
Depending on where you are running the server, you might want to replace setTimeout with waitUntil (cf workers, Vercel) or other functions that extend the lifetime of the request without blocking the response.
And again, we check if there was an error before tracking the event. We don't want to track unsuccessful events.
The @hono/zod-openapi routes have a middleware property that allows you to add middleware to the route. This is where we will add the tracking middleware.
And that's it. With minimal code changes and the help of middlewares, we have implemented event tracking in our application. You can swap OpenPanel with any other analytics provider like PostHog, but give it a try, it's an amazing tool!
By the way, this approach can be used for audit log tracking for example as well.
Check out our GitHub repository for the full implementation and don't forget to leave a star if you found this helpful.