# Vercel

#### Contents

- Vercel Functions
- Error tracking
- AI SDK and AI Observability
- Vercel Flags SDK
- Further reading

This doc focuses on features unique to the Vercel platform like Vercel Functions, the AI SDK, and the Flags SDK. If you're looking for details on frameworks like [Next.js](/content/docs/libraries/next-js/index.html), [Svelte](/content/docs/libraries/svelte/index.html), [Astro](/content/docs/libraries/astro/index.html), and [Nuxt](/content/docs/libraries/nuxt-js/index.html), see their framework-specific docs.

**PostHog MCP server for v0**

If you're building with v0, you can connect to the PostHog MCP server to interact with PostHog's products. See the [PostHog MCP server documentation](/content/docs/model-context-protocol?tab=v0/index.html) for more details.

## Vercel Functions

To use PostHog in Vercel Functions, first install the `posthog-node` library:

```bash
npm i posthog-node
```

Afterwards, set up a PostHog instance:

```javascript
// app/posthog.js
import { PostHog } from 'posthog-node'

export default function PostHogClient() {
  const posthogClient = new PostHog('<ph_project_token>', {
    host: 'https://us.i.posthog.com',
    flushAt: 1, // flush immediately in serverless environment
    flushInterval: 0 // same
  })
  return posthogClient
}
```

Finally, import and add PostHog to your function. We use the `captureImmediate` method to ensure data is captured before the serverless function shuts down.

```javascript
// app/api/hello/route.js
import PostHogClient from '../../posthog'

export async function GET(request) {
  const posthogClient = PostHogClient()
  await posthogClient.captureImmediate({
    distinctId: 'ian@posthog.com',
    event: 'vercel_function_called',
    properties: {
      message: 'Hello from Vercel!'
    }
  })
  return new Response('Hello from Vercel!');
}
```

We use `captureImmediate` with `await` because it guarantees the HTTP request finishes before your function continues (or shuts downs). `flushAt` and `flushInterval` mean events are sent immediately, but `capture` is still async and serverless environments can freeze or terminate before it completes.

Finally, to ensure all your requests complete you can combine PostHog's `shutdown()` method with Next.js's [`after`](https://nextjs.org/docs/app/api-reference/functions/after) function for Next.js 15.1 and above, or Vercel's [`waitUntil`](https://vercel.com/docs/functions/functions-api-reference/vercel-functions-package#waituntil) helper method for older versions.

This ensures your events get sent to PostHog and no background processes are left running. The function doesn't hang forever if something goes wrong.

```javascript
// app/api/after/route.js
import { after } from 'next/server'
import PostHogClient from '../../posthog'

export async function POST(request) {
  const posthogClient = PostHogClient()

// ... other code ...

after(() => posthogClient.shutdown())

return new Response('Good job!')
}
```

```javascript
// app/api/wait/route.js
import { waitUntil } from '@vercel/functions';
import PostHogClient from '../../posthog'

export async function POST(request) {
  const posthogClient = PostHogClient()

// ... your code ...

waitUntil(posthogClient.shutdown())

return new Response('Good job!');
}
```

**What about the pages router?**

[Vercel recommends](https://vercel.com/docs/functions?framework=nextjs) using route handlers in the app router when using Vercel Functions.

### Error tracking

You can capture errors in Vercel Functions like you would in other Node applications using `posthog.captureException()`.

For more details and a method for automatically capturing errors from Vercel Functions, see our [error tracking installation docs](/content/docs/error-tracking/installation/nextjs#capturing-server-errors/index.html).

## AI SDK and AI Observability

PostHog can automatically capture generations, traces, spans, and more for Vercel's AI SDK. You can find out how to install it in [the AI Observability docs](/content/docs/ai-observability/installation/vercel-ai/index.html).

## Vercel Flags SDK

You can use the native PostHog adapter for the Vercel Flags SDK to implement and manage feature flags.

> Vercel provides an [example app](https://vercel.com/templates/edge-middleware/posthog-with-flags-sdk-and-next-js) you can deploy if you want to try this out faster.

To set it up, start by installing the Flags SDK PostHog adapter:

```bash
npm i flags @flags-sdk/posthog
```

Next, set up the required environment variables. The adapter uses these values as defaults. You can get both of them in [your project settings](https://us.posthog.com/settings/project).

```file=.env.local
NEXT_PUBLIC_POSTHOG_PROJECT_TOKEN=<ph_project_token>
NEXT_PUBLIC_POSTHOG_HOST=<ph_api_client_host>
```

You can then set up the adapter and flags in a `flags.js|ts` file. You will need to have already created a feature flag in PostHog (I did `example-flag`) and use its key like this:

```javascript
// flags.js|ts
import { flag } from 'flags/next'
import { postHogAdapter } from '@flags-sdk/posthog'

export const exampleFlag = flag({
  key: 'example-flag',
  defaultValue: false,
  adapter: postHogAdapter.isFeatureEnabled(),
  identify: {
    distinctId: 'user_distinct_id', // Replace with real ID
  },
})
```

You can use it in your pages like this:

```jsx
// app/page.jsx
import { exampleFlag } from "@/flags";

export default async function Page() {
  const exampleValue = await exampleFlag();

return <div>Example Flag: {String(exampleValue)}</div>;
}
```
