PostHog makes it easy to get data about usage of your Vue.js app. Integrating PostHog into your app enables analytics about user behavior, custom events capture, session replays, feature flags, and more.
This guide walks you through integrating PostHog into your app for both Vue.js major versions 2
and 3
. We'll use the JavaScript Web SDK for this.
For integrating PostHog into a Nuxt.js app, see our Nuxt guide.
Prerequisites
To follow this guide along, you need:
- A PostHog account (either Cloud or self-hosted)
- A running Vue.js app
Setting up PostHog
Start by installing posthog-js
using your package manager:
yarn add posthog-js# ornpm 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:
// src/composables/usePostHog.tsimport posthog from 'posthog-js'export function usePostHog() {posthog.init('<ph_project_api_key>', {api_host: 'https://us.i.posthog.com'})return {posthog}}
Next, in router/index.js
, import the usePostHog
composable and call it.
// src/router/index.jsimport { 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 (if enabled) and is ready to use throughout your app.
Capturing pageviews
PostHog captures pageviews on page load, and since Vue creates a single-page app, this only happens once. This means if we want to capture every route change, we must write code to capture pageviews that integrates with the router.
First, disable autocaptured pageviews by setting capture_pageview
to false
in the PostHog initialization config:
// src/composables/usePostHog.tsimport posthog from 'posthog-js'export function usePostHog() {posthog.init('<ph_project_api_key>', {api_host: 'https://us.i.posthog.com',capture_pageview: false})return {posthog}}
Next, in router/index.js
, set up PostHog to capture pageviews in the router.afterEach
function.
// src/router/index.jsimport { 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()router.afterEach((to) => {posthog.capture('$pageview')})export default router
Capturing pageleaves
Pageleaves are similar to pageviews, they need to be manually captured.
To capture pageleaves, we can simply use the beforeEach
hook in the router.
// src/router/index.js//... rest of your codeconst { posthog } = usePostHog()router.beforeEach((to, from) => {if (from.path !== to.path) {posthog.capture('$pageleave')}})//... rest of your code
Capturing custom events, using feature flags, and more
Once you have PostHog initialized, there is a lot more you can do with it beyond autocapture, pageviews, and pageleaves. You can find the full details in our JavaScript SDK docs, but we'll cover a few examples here.
To capture custom events, evaluate feature flags, and use any of the other PostHog features, you can use the posthog
object returned from the usePostHog
composable like this:
// src/App.vue<script setup>import { RouterView } from 'vue-router'import { usePostHog } from './composables/usePostHog'const { posthog } = usePostHog()const handleClick = () => {posthog.capture('button_clicked', { location: 'homepage' })}const isFeatureEnabled = posthog.isFeatureEnabled('test-flag')</script><template><div><button @click="handleClick">Click me!</button><p>Is feature flag enabled? {{ isFeatureEnabled ? 'Yes' : 'No' }}</p></div><RouterView /></template>
Other setup options
With Vue 3, developers can use provide()
and inject()
to pipe global values into any component without prop drilling. And if you don't know what prop drilling is, good for you.
While this method is more declarative, as you need to inject PostHog into every component, it avoids “polluting” globals (like the plugins can do). Some engineers prefer this approach, while others include PostHog in globals since it doesn't need to be reactive and will be called throughout your application.
Step 1: Initialize Vue
Prior to mounting the app, you must:
- Import PostHog
- Initialize it
- Provide it to your app.
This must be done before you mount your app. If you provide PostHog after mounting it, PostHog will not be predictably available.
//app.jsimport posthog from "posthog-js";const app = createApp(App);posthog.init("<ph_project_api_key>", {api_host: "https://us.i.posthog.com",});app.provide("posthog", posthog);
Step 2: Inject into any Vue file
//component.vueexport default {data() {return {greeting: "How are you!",};},inject: ["posthog"], //grab the injection from app-wide providercreated() {console.log("Created", this.posthog); //posthog accessible!},};
Next steps
For any technical questions for how to integrate specific PostHog features into Vue (such as analytics, feature flags, A/B testing, or surveys), have a look at our JavaScript Web SDK docs.
Alternatively, the following tutorials can help you get started: