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.

PostHog initializes as a singleton, so you can initialize it in your main.ts file before you mount your app. This ensures PostHog is initialized before any other code runs.

src/main.ts
// src/main.ts
import { createApp } from 'vue'
import { createPinia } from 'pinia'
import App from './App.vue'
import router from './router'
import posthog from "posthog-js";
const app = createApp(App);
posthog.init(import.meta.env.VITE_POSTHOG_KEY || '<ph_project_api_key>', {
api_host: import.meta.env.VITE_POSTHOG_HOST || 'https://us.i.posthog.com',
defaults: '2025-11-30',
});
app.use(createPinia())
app.use(router)
app.config.errorHandler = (err, instance, info) => {
posthog.captureException(err)
}
app.mount('#app')

Then, you can access PostHog throughout your app just by importing it from posthog-js.

TypeScript
// src/App.vue
<script setup>
import posthog from 'posthog-js'
const handleClick = () => {
posthog.capture('button_clicked')
}
</script>

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.