Vue web analytics installation

Start by installing posthog-js using your package manager:

npm install --save posthog-js

Next, depending on your Vue version, we recommend initializing PostHog using the composition API or as a plugin.

We use the Composition API as it provides better accessibility, maintainability, and type safety.

Start by creating a composables folder as well as a usePosthog.js file to that folder. In usePosthog.js, initialize PostHog as a composable with your project API key and host. You can find these in your project settings.

JavaScript
// src/composables/usePostHog.ts
import posthog from 'posthog-js'
export function usePostHog() {
posthog.init('<ph_project_api_key>', {
api_host: 'https://us.i.posthog.com',
defaults: '2025-11-30',
})
return { posthog }
}

Next, in router/index.js, import the usePostHog composable and call it.

JavaScript
// src/router/index.js
import { createRouter, createWebHistory } from 'vue-router'
import HomeView from '../views/HomeView.vue'
import { usePostHog } from '@/composables/usePostHog'
const router = createRouter({
history: createWebHistory(import.meta.env.BASE_URL),
routes: [
{
path: '/',
name: 'home',
component: HomeView,
},
{
path: '/about',
name: 'about',
component: () => import('../views/AboutView.vue'),
},
],
})
const { posthog } = usePostHog()
export default router

Once done, PostHog will begin autocapturing events and pageviews (if enabled) and is ready to use throughout your app.

Next steps

After installing PostHog and ensuring autocapture is enabled, head to your web analytics dashboard to see your data. And then check out our getting started guide.

PostHog tip: Web analytics works with anonymous events. This means if you are primarily using PostHog for web analytics, it can be significantly cheaper for you.

Community questions

Was this page useful?

Questions about this page? or post a community question.