Repository navigation
feat: add next.js and nuxt server span context #5315
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Merged
pauldambra
merged 10 commits into
posthog/node-framework-span-context
from
posthog/nextjs-otel-span-context
Oct 28, 2026
Merged
Changes from all commits
Commits
Show all changes
10 commits
Select commit
Hold shift + click to select a range
f621296
feat(next): add optional server span context bridge
pauldambra b28c852
test(next): define sampler gap context boundary
pauldambra 41e2383
feat(nuxt): add optional server request span context
pauldambra 7f85d0b
fix(nuxt): enrich incoming spans at request entry
pauldambra ff990d6
fix: share framework span enrichment without optional imports
pauldambra 645e43c
chore(nuxt): use enabled clients in span context tests
pauldambra 5dd1049
fix(next): keep nested context in span context callbacks
pauldambra bfa0ee9
fix(nuxt): keep application context in request scopes and errors
pauldambra 916660e
fix(next,nuxt): keep request context for work after the handler
pauldambra 7dc2d42
fix(next): share the Node.js client cache across webpack layers
pauldambra File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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. |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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. |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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) | ||
| ) | ||
| 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 } | ||
| ) | ||
| }, | ||
| } | ||
| } | ||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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.') | ||
| } |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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) | ||
| }) | ||
| }) |
Oops, something went wrong.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.