T
TanStack2y ago
afraid-scarlet

How to track page views?

Hi, I'm using posthog-js (similar to Google Analytics) to track page views, since tanstack router navigates on the client side, I need to manually trigger the tracking method.
const rootRoute = new RootRoute({
beforeLoad: () => {
posthog.capture('$pageview')
},
})
const rootRoute = new RootRoute({
beforeLoad: () => {
posthog.capture('$pageview')
},
})
I'm currently using the above code, but since the page may not navigate when beforeLoad run, the captured url is not the one that is loading. So what's the best practice to track page views in tanstack router? Thanks
3 Replies
unwilling-turquoise
unwilling-turquoise2y ago
You could also subscribe to the onLoad event from the Router instance, and perform your tracking calls there.
No description
unwilling-turquoise
unwilling-turquoise2y ago
const unsubscribe = router.subscribe("onLoad", ({ toLocation }) => {
const href = toLocation.href
// perform stuff here
})
const unsubscribe = router.subscribe("onLoad", ({ toLocation }) => {
const href = toLocation.href
// perform stuff here
})
afraid-scarlet
afraid-scarletOP2y ago
Nice! That's exactly what I need.

Did you find this page helpful?