Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 5 additions & 0 deletions .changeset/calm-otters-listen.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
'@posthog/nuxt': minor
---

Add optional server request context and access to the existing server client for OpenTelemetry span enrichment.
5 changes: 5 additions & 0 deletions .changeset/tidy-cups-trace.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
'@posthog/next': minor
---

Add an optional Node.js App Router span context bridge that reuses the configured PostHog client and request identity.
4 changes: 4 additions & 0 deletions packages/next/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -7,3 +7,7 @@ SDK usage examples and code snippets live in the official documentation so they
## Documentation

- [Next.js library docs](https://posthog.com/docs/libraries/next-js)

The optional `@posthog/next/otel` entry point links Node.js App Router work to existing OpenTelemetry spans. Reuse your `createPostHog` configuration and add its processor to your existing tracer provider. Work that the callback starts keeps the request context after `withPostHogContext` returns or throws. It does not cover later component rendering, streamed response bodies, or the Edge runtime.

Server span enrichment follows parent spans observed by the processor. If the application sampler drops an intermediate span, the helper cannot prove the earlier server ancestor and leaves it unchanged. Recording spans created inside the callback still receive context. The integration does not change the sampler or guess ancestry from trace IDs.
18 changes: 17 additions & 1 deletion packages/next/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -43,6 +43,15 @@
"react-server": "./dist/pages.js",
"node": "./dist/pages.js",
"default": "./dist/pages.client.js"
},
"./otel": {
"types": "./dist/otel.d.ts",
"edge-light": "./dist/otel.unsupported.js",
"edge": "./dist/otel.unsupported.js",
"worker": "./dist/otel.unsupported.js",
"browser": "./dist/otel.unsupported.js",
"node": "./dist/otel.js",
"default": "./dist/otel.unsupported.js"
}
},
"main": "./dist/index.client.js",
Expand Down Expand Up @@ -74,6 +83,9 @@
"server-only": "^0.0.1"
},
"devDependencies": {
"@opentelemetry/api": "^1.9.0",
"@opentelemetry/context-async-hooks": "^2.10.0",
"@opentelemetry/sdk-trace-base": "^2.10.0",
"@posthog-tooling/tsconfig-base": "workspace:*",
"@testing-library/jest-dom": "^6.6.3",
"@testing-library/react": "^16.1.0",
Expand All @@ -91,11 +103,15 @@
"@vercel/functions": ">=1.0.0",
"next": ">=13.0.0",
"react": ">=18.0.0",
"react-dom": ">=18.0.0"
"react-dom": ">=18.0.0",
"@opentelemetry/api": "^1.9.0"
},
"peerDependenciesMeta": {
"@vercel/functions": {
"optional": true
},
"@opentelemetry/api": {
"optional": true
}
},
"packageManager": "pnpm@10.23.0"
Expand Down
46 changes: 46 additions & 0 deletions packages/next/src/otel.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,46 @@
import type { IPostHog } from 'posthog-node'
import { PostHogContextSpanProcessor, enrichCurrentSpan } from 'posthog-node/otel'
import type { CreatePostHogConfig } from './server/createPostHog.js'
import { getConfiguredPostHogClient, resolvePostHogRequest } from './server/getPostHog.js'

export interface PostHogSpanContext {
/** Add this processor to the application's existing Node.js tracer provider before it handles requests. */
createContextSpanProcessor(): Promise<PostHogContextSpanProcessor>
/**
* Scope Node.js App Router work. Context ends when the callback settles, including on error.
* Earlier server spans are enriched only through parent links observed by the processor;
* a sampler-dropped intermediate span breaks that chain. New recording child spans still receive context.
*/
withPostHogContext<T>(work: (posthog: IPostHog) => T | Promise<T>): Promise<T>
}

/** Reuse the same configuration as createPostHog; this entry point requires the Node.js runtime and OpenTelemetry. */
export function createPostHogSpanContext(config: CreatePostHogConfig = {}): PostHogSpanContext {
let pendingProcessor: Promise<PostHogContextSpanProcessor> | undefined

return {
createContextSpanProcessor() {
pendingProcessor ??= getConfiguredPostHogClient(config.apiKey, config.options).then(
({ client }) => new PostHogContextSpanProcessor(client)
Comment thread
pauldambra marked this conversation as resolved.
Resolved
)
return pendingProcessor
},
async withPostHogContext(work) {
const { client, contextData } = await resolvePostHogRequest(
config.apiKey,
config.options,
config.getDistinctId
)
return client.withContext(
contextData ?? {},
async () => {
if (contextData) {
enrichCurrentSpan(client)
}
return await work(client)
},
{ fresh: true }
)
},
}
}
3 changes: 3 additions & 0 deletions packages/next/src/otel.unsupported.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
export function createPostHogSpanContext(): never {
throw new Error('PostHog span context requires the Next.js Node.js server runtime.')
}
9 changes: 8 additions & 1 deletion packages/next/src/server/clientCache.node.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,14 @@ import { PostHog } from 'posthog-node'
import type { PostHogOptions } from 'posthog-node'
import { getOrCreatePostHogClient } from './clientCache.js'

const cache = new Map<string, PostHog>()
// With default Next.js bundling, instrumentation and App Router request handlers
// run in separate webpack layers, each loading its own copy of this module. Share
// the cache through globalThis so every layer reuses the same client — otherwise
// the OTel span processor and withPostHogContext can read and write different
// clients' context for the same request.
const CACHE_KEY = Symbol.for('posthog-nextjs.node-client-cache')
const cacheHolder = globalThis as typeof globalThis & { [CACHE_KEY]?: Map<string, PostHog> }
const cache = (cacheHolder[CACHE_KEY] ??= new Map<string, PostHog>())

export async function getOrCreateNodeClient(apiKey: string, options?: Partial<PostHogOptions>): Promise<PostHog> {
return getOrCreatePostHogClient(cache, PostHog, apiKey, options)
Expand Down
34 changes: 26 additions & 8 deletions packages/next/src/server/getPostHog.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import { isFunction } from '@posthog/core'
import type { PostHogOptions, IPostHog } from 'posthog-node'
import type { PostHog, PostHogOptions, IPostHog } from 'posthog-node'
import { cookies, headers } from 'next/headers.js'
import { getOrCreateNodeClient } from './clientCache.node.js'
import { readPostHogCookie, isOptedOut } from '../shared/cookie.js'
Expand Down Expand Up @@ -60,24 +60,33 @@ function resolveServerDistinctIdOncePerRequest(
return result
}

export async function getRequestScopedPostHog(
export async function getConfiguredPostHogClient(
apiKey?: string,
options?: Partial<PostHogOptions>,
getDistinctId?: PostHogDistinctIdResolver
): Promise<IPostHog> {
options?: Partial<PostHogOptions>
): Promise<{ client: PostHog; resolvedApiKey?: string }> {
const resolvedApiKey = resolveApiKey(apiKey)
const host = resolveHostOrDefault(options?.host)
const resolvedOptions = { ...options, host }
const client = await getOrCreateNodeClient(resolvedApiKey ?? '', resolvedOptions)

return { client, resolvedApiKey }
}

export async function resolvePostHogRequest(
apiKey?: string,
options?: Partial<PostHogOptions>,
getDistinctId?: PostHogDistinctIdResolver
): Promise<{ client: PostHog; contextData?: Parameters<IPostHog['withContext']>[0] }> {
const { client, resolvedApiKey } = await getConfiguredPostHogClient(apiKey, options)

if (!resolvedApiKey) {
return client
return { client }
}

const cookieStore = await cookies()

if (isOptedOut(cookieStore, resolvedApiKey)) {
return client
return { client }
}

const state = readPostHogCookie(cookieStore, resolvedApiKey)
Expand All @@ -92,5 +101,14 @@ export async function getRequestScopedPostHog(
}
}

return withRequestContext(client, contextData)
return { client, contextData }
}

export async function getRequestScopedPostHog(
apiKey?: string,
options?: Partial<PostHogOptions>,
getDistinctId?: PostHogDistinctIdResolver
): Promise<IPostHog> {
const { client, contextData } = await resolvePostHogRequest(apiKey, options, getDistinctId)
return contextData ? withRequestContext(client, contextData) : client
}
43 changes: 43 additions & 0 deletions packages/next/tests/clientCache.node.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,43 @@
vi.mock('server-only', () => ({}))

const { mockPostHogConstructor } = vi.hoisted(() => ({
mockPostHogConstructor: vi.fn(() => ({})),
}))

vi.mock('posthog-node', () => ({
PostHog: mockPostHogConstructor,
}))

async function loadTwoModuleCopies() {
vi.resetModules()
const first = await import('../src/server/clientCache.node')
vi.resetModules()
const second = await import('../src/server/clientCache.node')
return { first, second }
}

describe('clientCache.node cache sharing', () => {
beforeEach(() => {
vi.clearAllMocks()
vi.resetModules()
})

// With default Next.js bundling, instrumentation and App Router handlers load
// their own copy of this module (separate webpack layers). Without a shared
// cache, each copy creates its own PostHog client for the same key, so the
// OTel span processor (reading one client's context) and withPostHogContext
// (writing another's) can disagree about the current request context.
it.each([
['the first copy created the client', 'first', 'second', 'phc_test_a'],
['the second copy created the client', 'second', 'first', 'phc_test_b'],
] as const)('reuses the client across module copies when %s', async (_, creator, reader, apiKey) => {
const copies = await loadTwoModuleCopies()
expect(copies.second).not.toBe(copies.first)

const created = await copies[creator].getOrCreateNodeClient(apiKey, { host: 'https://test.com' })
const read = await copies[reader].getOrCreateNodeClient(apiKey, { host: 'https://test.com' })

expect(read).toBe(created)
expect(mockPostHogConstructor).toHaveBeenCalledTimes(1)
})
})
Loading
Loading