---
title: "PostHog Setup for Nuxt · Nuxt Scripts"
description: "Add PostHog to a Nuxt app with the official posthog-js SDK. Use feature flags, EU hosting, a first-party proxy, and opt-in or opt-out controls."
canonical_url: "https://scripts.nuxt.com/scripts/posthog"
meta:
  "og:description": "Add PostHog to a Nuxt app with the official posthog-js SDK. Use feature flags, EU hosting, a first-party proxy, and opt-in or opt-out controls."
  "og:image": "https://scripts.nuxt.com/_og/s/o_1e829c03191eef3c.png"
  "og:image:height": "600"
  "og:image:type": image/png
  "og:image:width": "1200"
  "og:title": "PostHog Setup for Nuxt · Nuxt Scripts"
  "twitter:image": "https://scripts.nuxt.com/_og/s/o_1e829c03191eef3c.png"
---

> Index of every page on this site: [llms.txt](https://scripts.nuxt.com/llms.txt)

**Scripts**

# **PostHog**

[Copy for LLMs](https://scripts.nuxt.com/scripts/posthog.md)

[**PostHog**](https://posthog.com) is an open-source product analytics platform with session replay, feature flags, and experiments. Nuxt Scripts loads PostHog's official [`**posthog-js**`** browser SDK**](https://posthog.com/docs/libraries/js) from [**npm**](https://www.npmjs.com/).

Use [`**useScriptPostHog()**`](https://scripts.nuxt.com/scripts/posthog) to load the SDK and access the PostHog client.

**PostHog**

[**View source **](https://github.com/nuxt/scripts/blob/main/packages/script/src/runtime/registry/posthog.ts)

## Nuxt Config Setup

Add this to your `**nuxt.config.ts**` to load PostHog globally. Alternatively you can use the **useScriptPostHog** composable for more control.

```
export default defineNuxtConfig({
  scripts: {
    registry: {
      posthog: {
        apiKey: 'phc_xxxxxxxxxxxxxxxxx',
        trigger: 'onNuxtReady',
      }
    }
  }
})
```

This config automatically enables **first-party mode ** (proxy). See below to customise.

## useScriptPostHog()

The `**useScriptPostHog**` composable lets you have fine-grain control over when and how PostHog is loaded on your site.

```
const { proxy } = useScriptPostHog()

proxy.posthog.capture('conversion', { value: 1 })
```

Please follow the [**Registry Scripts **](https://scripts.nuxt.com/docs/guides/registry-scripts) guide to learn more about advanced usage.

## First-Party Mode: Privacy Focused Proxy

No extra config needed. Runtime requests are reverse-proxied through your server instead of going directly to PostHog. User IPs are anonymised and requests work with ad blockers. [**Learn more. **](https://scripts.nuxt.com/docs/guides/first-party)

**Mode**

~~Bundle ~~ Proxy

**Privacy**

User IP addresses are anonymised. Other request data passes through.

```
export default defineNuxtConfig({
  scripts: {
    // ✅ First-party mode: proxied
    registry: {
      posthog: {
        apiKey: 'phc_xxxxxxxxxxxxxxxxx',
        trigger: 'onNuxtReady',
      },
    },
  },
})
```

## Example

Using PostHog in a component with the proxy to send events .

ConversionButton.vue

```
<script setup lang="ts">
const { proxy } = useScriptPostHog()

// noop in development, ssr
// just works in production, client
function handleAction() {
  proxy.posthog.capture('conversion', { value: 1 })
}
</script>

<template>
  <div>
    <button @click="handleAction">
      Send Event
    </button>
  </div>
</template>
```

## Installation

You must install the `**posthog-js**` dependency:

```bash
pnpm add posthog-js
```

## EU Hosting

To use PostHog's EU cloud:

```ts
export default defineNuxtConfig({
  scripts: {
    registry: {
      posthog: {
        apiKey: 'YOUR_API_KEY',
        region: 'eu'
      }
    }
  }
})
```

## First-Party Proxy

When [**first-party mode**](https://scripts.nuxt.com/docs/guides/first-party) is active (auto-enabled for scripts that support it), your server automatically proxies PostHog requests. PostHog [**recommends a reverse proxy**](https://posthog.com/docs/advanced/proxy) for more reliable event capture because ad blockers can reject requests to known analytics domains. Nuxt anonymizes the client IP address to subnet level; other data passes through so features such as session replay and feature flags continue to work.

The module sets `**apiHost**` to your server's proxy endpoint:

```ts
export default defineNuxtConfig({
  scripts: {
    registry: {
      posthog: {
        apiKey: 'YOUR_API_KEY',
        // apiHost is auto-set to '/_scripts/p/ph' (or '/_scripts/p/ph-eu' for EU region)
      }
    }
  }
})
```

The proxy handles API requests and static assets, including the session recording SDK.

## Custom API Host

To use a custom reverse proxy or self-hosted PostHog instance, set `**apiHost**` directly:

```ts
export default defineNuxtConfig({
  scripts: {
    registry: {
      posthog: {
        apiKey: 'YOUR_API_KEY',
        apiHost: '/my-proxy'
      }
    }
  }
})
```

The `**apiHost**` option accepts any URL or relative path, overriding both the `**region**` default and the first-party proxy auto-configuration. For additional PostHog SDK options like `**ui_host**`, use the `**config**` passthrough.

## Feature Flags

Feature flag methods return values, so you need to wait for PostHog to load first:

```ts
const { onLoaded } = useScriptPostHog()

onLoaded(({ posthog }) => {
  // Check a feature flag
  if (posthog.isFeatureEnabled('new-dashboard')) {
    // Show new dashboard
  }

  // Get flag payload
  const payload = posthog.getFeatureFlagPayload('experiment-config')
})
```

## Consent Mode

PostHog exposes [`**opt_in_capturing**`** / **`**opt_out_capturing**`](https://posthog.com/docs/libraries/js#opt-out-of-data-capture). Set the boot-time default with `**defaultConsent**` and call `**consent.optIn()**` / `**consent.optOut()**` at runtime.

### `**defaultConsent**`

| **Value** | **Behavior** |
| --- | --- |
| `**'opt-in'**` | Calls `**posthog.opt_in_capturing()**` immediately after init. |
| `**'opt-out'**` | Calls `**posthog.init(..., { opt_out_capturing_by_default: true })**` so the SDK boots opted out. |

Use `**defaultConsent: 'opt-out'**` when you need the SDK to boot opted out. The runtime `**consent.optOut()**` calls `**opt_out_capturing()**` **after** init, which is weaker than the boot-time flag; any events captured between init and the opt-out call are still sent.

### Example

```vue
<script setup lang="ts">
const { consent } = useScriptPostHog({
  apiKey: 'YOUR_API_KEY',
  defaultConsent: 'opt-out',
})

function onAccept() {
  consent.optIn()
}
function onRevoke() {
  consent.optOut()
}
</script>
```

Configuring PostHog globally in `**nuxt.config**`:

```ts
export default defineNuxtConfig({
  scripts: {
    registry: {
      posthog: {
        apiKey: 'YOUR_API_KEY',
        defaultConsent: 'opt-out',
      }
    }
  }
})
```

## Disabling Session Recording

```ts
export default defineNuxtConfig({
  scripts: {
    registry: {
      posthog: {
        apiKey: 'YOUR_API_KEY',
        disableSessionRecording: true
      }
    }
  }
})
```

`**apiKey**``string`** required **

Your PostHog project API key.

`**region**``'us' | 'eu'` = 'us'

Your PostHog data region.

`**apiHost**``string`

Custom API host URL. Overrides the default derived from \`region\`. Useful for self-hosted instances or reverse proxies.

`**autocapture**``boolean` = true

Enable autocapture of clicks, form submissions, and page views.

`**capturePageview**``boolean | 'history_change'` = true

Capture page views automatically. Set to \`'history\_change'\` to only capture on history changes.

`**capturePageleave**``boolean` = true

Capture page leave events automatically.

`**disableSessionRecording**``boolean`

Disable session recording.

`**config**``Record<string, any>`

Additional PostHog configuration options passed directly to \`posthog.init()\`.

`**defaultConsent**``'opt-in' | 'opt-out'`

Default capture-consent state for PostHog. - \`'opt-out'\`: passed as \`opt\_out\_capturing\_by\_default: true\` to \`posthog.init\`, so capturing is suppressed from the first event. - \`'opt-in'\`: applied after \`posthog.init\` via \`posthog.opt\_in\_capturing()\` on the returned instance.

[Edit this page](https://github.com/nuxt/scripts/edit/main/docs/content/posthog.md)

[Markdown For LLMs](https://scripts.nuxt.com/scripts/posthog.md)

[**Plausible Analytics** Load Plausible's site-specific tracker, including custom self-hosted endpoints.](https://scripts.nuxt.com/scripts/plausible-analytics) [**Pulse Analytics** Load the Pulse tracker and record custom events.](https://scripts.nuxt.com/scripts/pulse-analytics)

**On this page **

- [Installation](#installation)
- [EU Hosting](#eu-hosting)
- [First-Party Proxy](#first-party-proxy)
- [Custom API Host](#custom-api-host)
- [Feature Flags](#feature-flags)
- [Consent Mode](#consent-mode)
- [Disabling Session Recording](#disabling-session-recording)

```json
{"@context":"https://schema.org","@graph":[{"@id":"https://scripts.nuxt.com/#website","@type":"WebSite","description":"Nuxt Scripts lets you load third-party scripts with better performance, privacy, security and DX. It includes many popular third-parties out of the box.","name":"Nuxt Scripts","url":"https://scripts.nuxt.com/","publisher":{"@id":"https://scripts.nuxt.com/#identity"}},{"@id":"https://scripts.nuxt.com/scripts/posthog#webpage","@type":"WebPage","description":"Add PostHog to a Nuxt app with the official posthog-js SDK. Use feature flags, EU hosting, a first-party proxy, and opt-in or opt-out controls.","name":"PostHog Setup for Nuxt","url":"https://scripts.nuxt.com/scripts/posthog","breadcrumb":{"@id":"https://scripts.nuxt.com/scripts/posthog#breadcrumb"},"isPartOf":{"@id":"https://scripts.nuxt.com/#website"},"potentialAction":[{"@type":"ReadAction","target":["https://scripts.nuxt.com/scripts/posthog"]}],"primaryImageOfPage":{"@id":"https://scripts.nuxt.com/#logo"}},{"@id":"https://scripts.nuxt.com/#identity","@type":"Organization","name":"Nuxt Scripts","url":"https://scripts.nuxt.com","logo":{"@id":"https://scripts.nuxt.com/#logo"}},{"@id":"https://scripts.nuxt.com/scripts/posthog#breadcrumb","@type":"BreadcrumbList","itemListElement":[{"@type":"ListItem","name":"Nuxt Scripts","item":"https://scripts.nuxt.com/","position":1},{"@type":"ListItem","name":"Scripts","item":"https://scripts.nuxt.com/scripts","position":2},{"@type":"ListItem","name":"PostHog","item":"https://scripts.nuxt.com/scripts/posthog","position":3}]},{"@id":"https://scripts.nuxt.com/#logo","@type":"ImageObject","caption":"Nuxt Scripts","contentUrl":"https://scripts.nuxt.com/logo.svg","inLanguage":"en","url":"https://scripts.nuxt.com/logo.svg"}]}
```

## Sitemap

See the full [sitemap](https://scripts.nuxt.com/sitemap.md) for all pages.
