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.
This guide walks you through integrating PostHog into your app for both Nuxt.js major versions 2 and 3. We'll use the JavaScript SDK.
This tutorial is aimed at Nuxt.js users which run Nuxt in spa or universal mode. You can see a working example of the Nuxt v3.0 integration in our Nuxt.js demo app
Nuxt v3.0 and above
Prerequisites
To follow this guide along, you need:
- A PostHog instance (signup for free])
- a running Nuxt.js application running version 3.0or above.
Setting up PostHog
- Install posthog-js using your package manager:
- Add your PostHog API key and host to your nuxt.config.jsfile. You can find your project API key in the PostHog app under Project Settings > Project Variables.
- Create a new plugin by creating a new file posthog.client.jsin your plugins directory.
PostHog can then be accessed throughout your Nuxt.js using the provider accessor, for example:
See the JavaScript SDK docs for all usable functions, such as:
- Capture custom event capture, identify users, and more.
- Feature flags including variants and payloads.
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.
The first thing you want to do is to install the posthog-js library in your project - so add it using your package manager:
or
After that we want to create a app in plugins/posthog/index.js
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: