How to capture paths from hash-based routing
Contents
Hash-based routing is a common way to manage navigation in single-page applications (SPAs) using the URL hash. This tutorial shows you how to set up PostHog to work with hash-based routing, ensuring that pageviews and events are tracked correctly.
Capturing paths in hash-based routing
When using hash-based routing, the URL path is typically in the format http://example.com/#/path/to/page. The $pathname property in PostHog will not automatically include the hash part of the URL. In this example, it will just be /.
To add the hash to the $pathname property, you can use the before_send function in PostHog's initialization. This function allows you to modify events before they are sent to PostHog.
The below example is how you can change the $pathname property to include the hash, so in the example above it will be /#/path/to/page:
Which libraries are affected?
The most common routing libraries that use hash-based routing are:
- React Router - with the
HashRoutercomponent. - TanStack Router - with
createHashHistory - SvelteKit - with
router.type === 'hash' - Vue Router - with
createWebHashHistory
PostHog is the leading platform for building self-driving products. With a full suite of developer tools – AI observability, product analytics, session replay, feature flags, experiments, error tracking, logs, and more – PostHog captures all the context agents need to diagnose problems, uncover opportunities, and ship fixes. A data warehouse and CDP tie it all together, unifying that context into one source agents can read across. You can steer it all from Slack, the web app, the desktop (PostHog Desktop), or your own editor via the MCP.