Skip to content
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
We provide a helper package that will hook into the Next.js build process and upload sourcemaps for your client and server code. This process is enabled by default for production builds but you can disable it by setting `enabled` to `false` in the `sourcemaps` object.
We provide a helper package that will hook into the Next.js build process and upload source maps for your client and server code. This process is enabled by default for production builds but you can disable it by setting `enabled` to `false` in the `sourcemaps` object.

#### 1. Install package

Expand Down
97 changes: 97 additions & 0 deletions contents/docs/error-tracking/installation/nuxt-3-6.mdx
Original file line number Diff line number Diff line change
@@ -0,0 +1,97 @@
---
title: Nuxt error tracking installation (v3.6 and below)
showStepsToc: true
---

import { Steps, Step } from 'components/Docs/Steps'

import CLIUpload from "../_snippets/cli/upload.mdx"
import CLIAuthenticate from "../_snippets/cli/authenticate.mdx"
import CLIDownload from "../_snippets/cli/download.mdx"
import InstallNuxt from "../../integrate/_snippets/install-nuxt.mdx"
import StepVerifyErrorTracking from "./_snippets/step-verify-error-tracking.mdx"
import StepUploadSourceMaps from "./_snippets/step-upload-source-maps.tsx"

For older versions of Nuxt, you'll need to manually set up error tracking and source map uploads.

<Steps>
<Step title="Installing PostHog SDK" subtitle="Your goal in this step: Install the PostHog SDK." badge="required">

<InstallNuxt />

</Step>

<Step checkpoint title="Verify PostHog is initialized" subtitle="Confirm you can capture events with PostHog">

Before proceeding, confirm that you can [capture events](/docs/libraries/nuxt-js#capture-custom-events) using `posthog.capture('test_event')`.

</Step>

<Step title="Manually capturing exceptions" subtitle="Your goal in this step: Manually capture exceptions in your Nuxt application." badge="required">

To send errors directly using the PostHog client, import it and use the `captureException` method like this:

```vue component.vue
<script>
const { $posthog } = useNuxtApp()

if ($posthog) {
const posthog = $posthog()
posthog.captureException(new Error("Important error message"))
}
</script>
```

On the server side, you can use the `posthog` object directly.

```js file=server/api/example.js focusOnLines=4-21
export default defineEventHandler(async (event) => {
const distinctId = getCookie(event, 'distinct_id')

const { PostHog } = await import('posthog-node');
const runtimeConfig = useRuntimeConfig()

const posthog = new PostHog(
runtimeConfig.public.posthogPublicKey,
{
host: runtimeConfig.public.posthogHost,
}
);

try {
const results = await DB.query.users.findMany()
return results
} catch (error) {
posthog.captureException(error)
}
})
```

</Step>

<Step title="Configuring exception autocapture" subtitle="Your goal in this step: Enable automatic exception tracking for your Nuxt application." badge="required">

Update your `posthog.client.js` to add an error hook.

```js
export default defineNuxtPlugin((nuxtApp) => {
...
nuxtApp.hook('vue:error', (error) => {
posthogClient.captureException(error)
})
...
})
```

</Step>

<StepVerifyErrorTracking />


<Step title="Upload source maps" badge="required">

<StepUploadSourceMaps urlPath="nuxt" framework="Nuxt" />

</Step>

</Steps>
106 changes: 84 additions & 22 deletions contents/docs/error-tracking/installation/nuxt.mdx
Original file line number Diff line number Diff line change
Expand Up @@ -12,22 +12,83 @@ import InstallNuxt from "../../integrate/_snippets/install-nuxt.mdx"
import StepVerifyErrorTracking from "./_snippets/step-verify-error-tracking.mdx"
import StepUploadSourceMaps from "./_snippets/step-upload-source-maps.tsx"

For Nuxt v3.7 and above, we recommend using the official `@posthog/nuxt` module which provides automatic error tracking with built-in source map support.

<Steps>
<Step title="Installing PostHog Nuxt SDK" subtitle="Your goal in this step: Install the PostHog Nuxt.js SDK." badge="required">
<Step title="Install the PostHog Nuxt module" subtitle="Your goal in this step: Install and configure the PostHog Nuxt module." badge="required">

<InstallNuxt />
Install the PostHog Nuxt module using your package manager:

</Step>
<MultiLanguage>

```bash file=npm
npm install @posthog/nuxt
```

```bash file=Yarn
yarn add @posthog/nuxt
```

```bash file=pnpm
pnpm add @posthog/nuxt
```

```bash file=Bun
bun add @posthog/nuxt
```

<Step checkpoint title="Verify PostHog is initialized" subtitle="Confirm you can capture events with PostHog">
</MultiLanguage>

Add the module to your `nuxt.config.ts` file:

```typescript file=nuxt.config.ts
export default defineNuxtConfig({
modules: ['@posthog/nuxt'],

// Enable source maps generation in both vue and nitro
sourcemap: {
client: 'hidden'
},
nitro: {
rollupConfig: {
output: {
sourcemapExcludeSources: false,
},
},
},

posthogConfig: {
publicKey: '<ph_project_api_key>', // Find it in project settings https://app.posthog.com/settings/project
host: '<ph_client_api_host>', // Optional: defaults to https://us.i.posthog.com. Use https://eu.i.posthog.com for EU region
clientConfig: {
capture_exceptions: true, // Enables automatic exception capture on the client side (Vue)
},
serverConfig: {
enableExceptionAutocapture: true, // Enables automatic exception capture on the server side (Nitro)
},
sourcemaps: {
enabled: true,
envId: '<ph_environment_id>', // Your environment ID from PostHog settings https://app.posthog.com/settings/environment#variables
personalApiKey: '<ph_personal_api_key>', // Your personal API key from PostHog settings https://app.posthog.com/settings/user-api-keys
project: 'my-application', // Optional: defaults to git repository name
version: '1.0.0', // Optional: defaults to current git commit
},
},
})
```

Before proceeding, confirm that you can [capture events](/docs/libraries/nuxt-js#capture-custom-events) using `posthog.capture('test_event')`.
The module will automatically:
- Initialize PostHog on both Vue (client side) and Nitro (server side)
- Capture exceptions on both client and server
- Generate and upload source maps during build

</Step>

<Step title="Manually capturing exceptions" subtitle="Your goal in this step: Manually capture exceptions in your Nuxt application." badge="required">
<Step title="Manually capturing exceptions" subtitle="Your goal in this step: Manually capture exceptions in your Nuxt application." badge="optional">

To send errors directly using the PostHog client, import it and use the `captureException` method like this:
Our module if set up as shown above already captures both client and server side exceptions automatically.

To send errors manually on the client side, import it and use the `captureException` method like this:

```vue component.vue
<script>
Expand All @@ -40,7 +101,7 @@ To send errors directly using the PostHog client, import it and use the `capture
</script>
```

On the server side, you can use the `posthog` object directly.
On the server side instantiate PostHog using:

```js file=server/api/example.js focusOnLines=4-21
export default defineEventHandler(async (event) => {
Expand All @@ -67,29 +128,30 @@ export default defineEventHandler(async (event) => {

</Step>

<Step title="Configuring exception autocapture" subtitle="Your goal in this step: Enable automatic exception tracking for your Nuxt application." badge="required">
<Step title="Build your project for production" badge="required">

Update your `posthog.client.js` to add an error hook
Build your project for production by running the following command:

```js
export default defineNuxtPlugin((nuxtApp) => {
...
nuxtApp.hook('vue:error', (error) => {
posthogClient.captureException(error)
})
...
})
```bash
nuxt build
```

The PostHog module will automatically generate and upload source maps to PostHog during the build process.

</Step>

<StepVerifyErrorTracking />
<Step checkpoint title="Verify source map upload" subtitle="Confirm source maps are being properly uploaded">

Before proceeding, confirm that source maps are being properly uploaded.

<Step title="Upload source maps" badge="required">
You can verify the injection is successful by checking your `.mjs.map` source map files for `//# chunkId=` comments. Make sure to serve these injected files in production, PostHog will check for the `//# chunkId` comments to display the correct stack traces.

<StepUploadSourceMaps urlPath="nuxt" framework="Nuxt" />
<CallToAction type="secondary" className="my-2" size="sm" to="https://app.posthog.com/settings/project-error-tracking#error-tracking-symbol-sets" external={true}>
Check symbol sets in PostHog
</CallToAction>

</Step>

</Steps>
<StepVerifyErrorTracking />

</Steps>
18 changes: 14 additions & 4 deletions contents/docs/error-tracking/upload-source-maps/nuxt.mdx
Original file line number Diff line number Diff line change
Expand Up @@ -7,14 +7,24 @@ import CLIDownload from '../_snippets/cli/download.mdx'
import CLIAuthenticate from '../_snippets/cli/authenticate.mdx'
import StepVerifySourceMapUpload from './_snippets/step-verify-source-map-upload.mdx'

## Nuxt v3.7 and above

For Nuxt v3.7 and above, the `@posthog/nuxt` module automatically handles source map generation and upload during the build process.

No manual configuration is needed - follow the [Nuxt error tracking installation guide](/docs/error-tracking/installation/nuxt) to set up the module, and source maps are automatically generated and uploaded when you build your project.

## Nuxt v3.6 and below

For older versions of Nuxt, you'll need to manually configure source map generation and upload using the PostHog CLI.

<Steps>
<Step title="Install the PostHog CLI" badge="required">
<CLIDownload />
</Step>
<Step title="Authenticate the PostHog CLI" badge="required">
<CLIAuthenticate />
</Step>
<Step title="Generate sourcemaps during build" badge="required">
<Step title="Generate source maps during build" badge="required">

You can hook into the `close` event to generate and upload source maps for your Nuxt application like this:

Expand Down Expand Up @@ -53,13 +63,13 @@ Build your project for production by running the following command:
nuxt build
```

Post-build scripts should automatically generate and upload sourcemaps to PostHog.
Post-build scripts should automatically generate and upload source maps to PostHog.

</Step>

<Step checkpoint title="Verify source map upload" subtitle="Confirm sourcemaps are being properly uploaded">
<Step checkpoint title="Verify source map upload" subtitle="Confirm source maps are being properly uploaded">

Before proceeding, confirm that sourcemaps are being properly uploaded.
Before proceeding, confirm that source maps are being properly uploaded.

You can verify the injection is successful by checking your `.mjs.map` source map files for `//# chunkId=` comments. Make sure to serve these injected files in production, PostHog will check for the `//# chunkId` comments to display the correct stack traces.

Expand Down
97 changes: 97 additions & 0 deletions contents/docs/libraries/nuxt-js-2.mdx
Original file line number Diff line number Diff line change
@@ -0,0 +1,97 @@
---
title: Nuxt.js (v2.16 and below)
icon: >-
https://res.cloudinary.com/dmukukwp6/image/upload/posthog.com/contents/images/docs/integrate/frameworks/nuxt.svg
---

PostHog makes it easy to get data about usage of your [Nuxt.js](https://nuxt.com/) 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](https://nuxtjs.org/docs/2.x/directory-structure/plugins) 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](/docs/integrate/client/js) in your project - so add it using your package manager:

import InstallWebPackageManagers from "../integrate/_snippets/install-web-package-managers.mdx"

<InstallWebPackageManagers />

After that we want to create an app in `plugins/posthog/index.js`

```javascript
import posthog from 'posthog-js'
import Vue from 'vue'

export default function({ app: { router } }, inject) {
// Init PostHog
posthog.init('<ph_project_api_key>', {
api_host: '<ph_client_api_host>',
defaults: '<ph_posthog_js_defaults>',
capture_pageview: false,
loaded: () => posthog.identify('unique_id') // If you can already identify your user
})

// Inject PostHog into the application and make it available via this.$posthog (or app.$posthog)
inject('posthog', posthog)

// Make sure that pageviews are captured with each route change
router.afterEach(to => {
Vue.nextTick(() => {
/* Note: this might also be a good place to call posthog.register(...) in order to update your properties
on each page view
*/
posthog.capture('$pageview', {
$current_url: to.fullPath
})
})
})
}

```

Finally, we need to activate it on the client side in our `nuxt.config.js`

```js
plugins: [
...
{ src: './plugins/posthog', mode: 'client' }
],
```

## 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](https://nuxtjs.org/docs/2.x/directory-structure/plugins#inject-in-root--context) 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:

```js-web
<template>
<button @click="purchase">Buy</button>
</template>

<script>
...
methods: {
purchase() {
this.$posthog.capture('purchase')
}
}
...
</script>
```

## 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](/docs/libraries/js) and [Node](/docs/libraries/node) SDK docs.

Alternatively, the following tutorials can help you get started:

- [How to set up analytics in Nuxt](/tutorials/nuxt-analytics)
- [How to set up feature flags in Nuxt](/tutorials/nuxt-feature-flags)
- [How to set up A/B tests in Nuxt](/tutorials/nuxtjs-ab-tests)
- [How to set up surveys in Nuxt](/tutorials/nuxt-surveys)

Loading