Nuxt.js (v2.16 and below)
Contents
PostHog makes it easy to get data about usage of your Nuxt.js app. Integrating PostHog into your app enables analytics about user behavior, custom events capture, session replays, feature flags, and more.
These docs are for Nuxt v2.16 and below.
We are going to implement PostHog as a Nuxt.js integration which gives us the possibility to inject
the posthog object and make it available across our application.
Installation
The first thing you want to do is to install the posthog-js library in your project - so add it using your package manager:
After that we want to create an app in plugins/posthog/index.js
Anything shipped to the browser – the token you pass to posthog.init(), anything under Nuxt's runtimeConfig.public, or the @posthog/nuxt module's posthogConfig – ends up in your client-side JavaScript and is visible to anyone who visits your site. This is fine for your project token (<ph_project_token>), which is designed to be public.
Your personal API key is different. It can grant full access to your PostHog account, so it must never reach the browser. If you need it – for example, for source map uploads or server-side local evaluation – read it from a server-only environment variable (or top-level runtimeConfig, never runtimeConfig.public) and only use it in server code.
Either way, prefer reading keys from environment variables rather than hard-coding them in nuxt.config, so you can keep them out of source control and use different values per environment.
Finally, we need to activate it on the client side in our nuxt.config.js
Usage
By using the example code above you can now use PostHog across your app with this.$posthog or app.$posthog - depending on the context.
Compare with the Nuxt.js docs on further details when to use app.$posthog or this.$posthog.
Let's say for example the user makes a purchase you could track an event like that:
Next steps
For any technical questions for how to integrate specific PostHog features into Nuxt (such as analytics, feature flags, A/B testing, surveys, etc.), have a look at our JavaScript Web and Node SDK docs.
Alternatively, the following tutorials can help you get started: