// @vitest-environment node import { PostHog } from 'posthog-node' import { PostHog as EdgePostHog } from 'posthog-node/edge' import type { PostHogOptions } from 'posthog-node' import { captureNextRequestError } from '../src/server/captureRequestError' const UUID_V7_REGEX = /^[0-9a-f]{8}-[0-9a-f]{4}-7[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i type CapturedRequest = { url: string; init?: RequestInit } function createMockFetch(requests: CapturedRequest[]): NonNullable { return async (url, init) => { requests.push({ url, init }) return { status: 200, text: async () => '{"results":{}}', json: async () => ({ results: {} }) } } } describe('captureNextRequestError with real posthog-node v6 client', () => { const errorPaths = [ { name: 'route error via captureExceptionImmediate', context: { routerKind: 'App Router', routePath: '/api/orders', routeType: 'route' }, expectedMechanism: { type: 'generic', handled: true }, expectedExceptionSource: undefined, }, { name: 'proxy error via captureImmediate', context: { routerKind: 'Pages Router', routePath: '/proxy', routeType: 'proxy' }, expectedMechanism: { type: 'middleware', handled: false }, expectedExceptionSource: 'nextjs.proxy', }, ] as const it.each(errorPaths)( 'captures a $name on capture v1 without deprecation errors', async ({ context, expectedMechanism, expectedExceptionSource }) => { const requests: CapturedRequest[] = [] const fetch = createMockFetch(requests) let client: PostHog | undefined const errorSpy = vi.spyOn(console, 'error').mockImplementation(() => undefined) try { await captureNextRequestError( new Error('boom'), { method: 'POST', path: '/api/orders?secret=1#frag', headers: { host: 'shop.example.com', 'x-posthog-distinct-id': 'user_v6', 'x-posthog-session-id': 'session_v6', }, }, context, { projectToken: 'phc_real_v6', serverOptions: { disableCaptureUrlHashes: true }, }, async (projectToken, serverOptions) => { client = new PostHog(projectToken, { ...serverOptions, disableCompression: true, fetch, }) return client } ) expect(errorSpy).not.toHaveBeenCalled() expect(requests).toHaveLength(1) expect(requests[0].url).toBe('https://us.i.posthog.com/i/v1/analytics/events') expect(requests[0].init?.headers).toEqual( expect.objectContaining({ Authorization: 'Bearer phc_real_v6' }) ) const body = JSON.parse(String(requests[0].init?.body)) expect(body.batch).toHaveLength(1) expect(body.batch[0]).toMatchObject({ event: '$exception', distinct_id: 'user_v6', session_id: 'session_v6', properties: expect.objectContaining({ $pathname: '/api/orders', ...(expectedExceptionSource ? { $exception_source: expectedExceptionSource } : {}), $exception_list: [ expect.objectContaining({ mechanism: expect.objectContaining(expectedMechanism) }), ], }), }) if (!expectedExceptionSource) { expect(body.batch[0].properties).not.toHaveProperty('$exception_source') } } finally { errorSpy.mockRestore() await client?.shutdown() } } ) it('prevents beforeCapture return values from overwriting reserved exception properties on proxy errors', async () => { const requests: CapturedRequest[] = [] const fetch = createMockFetch(requests) let client: PostHog | undefined const errorSpy = vi.spyOn(console, 'error').mockImplementation(() => undefined) try { await captureNextRequestError( new Error('proxy boom'), { method: 'GET', path: '/proxy-target', headers: { host: 'shop.example.com', 'x-posthog-distinct-id': 'user_v6', }, }, { routerKind: 'Pages Router', routePath: '/proxy', routeType: 'proxy' }, { projectToken: 'phc_real_v6', beforeCapture: () => ({ $exception_list: [{ type: 'SpoofedError', value: 'spoofed' }], $exception_level: 'info', $exception_source: 'spoofed.source', $debug_images: [{ type: 'spoofed' }], $cymbal_errors: ['spoofed'], $exception_fingerprint: ['custom-fingerprint'], custom_tag: 'kept', }), }, async (projectToken, serverOptions) => { client = new PostHog(projectToken, { ...serverOptions, disableCompression: true, fetch, }) return client } ) expect(errorSpy).not.toHaveBeenCalled() expect(requests).toHaveLength(1) const body = JSON.parse(String(requests[0].init?.body)) expect(body.batch).toHaveLength(1) const props = body.batch[0].properties expect(props).toMatchObject({ $exception_level: 'error', $exception_source: 'nextjs.proxy', $exception_fingerprint: ['custom-fingerprint'], custom_tag: 'kept', $exception_list: [ expect.objectContaining({ type: 'Error', value: 'proxy boom', mechanism: expect.objectContaining({ type: 'middleware', handled: false }), }), ], }) expect(props).not.toHaveProperty('$debug_images') expect(props).not.toHaveProperty('$cymbal_errors') } finally { errorSpy.mockRestore() await client?.shutdown() } }) it('prevents beforeCapture mutations from overwriting reserved exception properties on proxy errors', async () => { const requests: CapturedRequest[] = [] const fetch = createMockFetch(requests) let client: PostHog | undefined const errorSpy = vi.spyOn(console, 'error').mockImplementation(() => undefined) try { await captureNextRequestError( new Error('proxy mutated'), { method: 'GET', path: '/proxy-target', headers: { host: 'shop.example.com', 'x-posthog-distinct-id': 'user_v6', }, }, { routerKind: 'Pages Router', routePath: '/middleware', routeType: 'middleware' }, { projectToken: 'phc_real_v6', beforeCapture: ({ properties }) => { properties.$exception_source = 'spoofed.source' properties.$exception_list = [{ type: 'SpoofedError' }] properties.$exception_level = 'info' properties.$debug_images = [{ type: 'spoofed' }] properties.$cymbal_errors = ['spoofed'] properties.$exception_fingerprint = ['mutated-fingerprint'] properties.custom_tag = 'mutated' }, }, async (projectToken, serverOptions) => { client = new PostHog(projectToken, { ...serverOptions, disableCompression: true, fetch, }) return client } ) expect(errorSpy).not.toHaveBeenCalled() expect(requests).toHaveLength(1) const body = JSON.parse(String(requests[0].init?.body)) const props = body.batch[0].properties expect(props).toMatchObject({ $exception_level: 'error', $exception_source: 'nextjs.middleware', $exception_fingerprint: ['mutated-fingerprint'], custom_tag: 'mutated', $exception_list: [ expect.objectContaining({ type: 'Error', value: 'proxy mutated', mechanism: expect.objectContaining({ type: 'middleware', handled: false }), }), ], }) expect(props).not.toHaveProperty('$debug_images') expect(props).not.toHaveProperty('$cymbal_errors') } finally { errorSpy.mockRestore() await client?.shutdown() } }) it.each(errorPaths)( 'captures a personless $name with a generated UUIDv7 distinct_id and process_person_profile: false', async ({ context, expectedMechanism, expectedExceptionSource }) => { const requests: CapturedRequest[] = [] const fetch = createMockFetch(requests) let client: PostHog | undefined const errorSpy = vi.spyOn(console, 'error').mockImplementation(() => undefined) try { await captureNextRequestError( new Error('anonymous boom'), { method: 'GET', path: '/anonymous', headers: { host: 'shop.example.com', }, }, context, { projectToken: 'phc_real_v6', serverOptions: { disableCaptureUrlHashes: true }, }, async (projectToken, serverOptions) => { client = new PostHog(projectToken, { ...serverOptions, disableCompression: true, fetch, }) return client } ) expect(errorSpy).not.toHaveBeenCalled() expect(requests).toHaveLength(1) expect(requests[0].url).toBe('https://us.i.posthog.com/i/v1/analytics/events') const body = JSON.parse(String(requests[0].init?.body)) expect(body.batch).toHaveLength(1) expect(body.batch[0]).toMatchObject({ event: '$exception', distinct_id: expect.stringMatching(UUID_V7_REGEX), options: { process_person_profile: false }, properties: expect.objectContaining({ $pathname: '/anonymous', ...(expectedExceptionSource ? { $exception_source: expectedExceptionSource } : {}), $exception_list: [ expect.objectContaining({ mechanism: expect.objectContaining(expectedMechanism) }), ], }), }) expect(body.batch[0].properties).not.toHaveProperty('$process_person_profile') } finally { errorSpy.mockRestore() await client?.shutdown() } } ) it.each(errorPaths)( 'captures a $name with posthog-node/edge on capture v1 with $lib: posthog-edge and zero deprecation errors', async ({ context, expectedMechanism, expectedExceptionSource }) => { const requests: CapturedRequest[] = [] const fetch = createMockFetch(requests) let client: EdgePostHog | undefined const errorSpy = vi.spyOn(console, 'error').mockImplementation(() => undefined) try { await captureNextRequestError( new Error('edge boom'), { method: 'POST', path: '/edge-route?secret=1#frag', headers: { host: 'shop.example.com', 'x-posthog-distinct-id': 'user_edge', }, }, context, { projectToken: 'phc_real_edge_v6', serverOptions: { disableCaptureUrlHashes: true }, }, async (projectToken, serverOptions) => { client = new EdgePostHog(projectToken, { ...serverOptions, disableCompression: true, fetch, }) return client } ) expect(errorSpy).not.toHaveBeenCalled() expect(requests).toHaveLength(1) expect(requests[0].url).toBe('https://us.i.posthog.com/i/v1/analytics/events') expect(requests[0].init?.headers).toEqual( expect.objectContaining({ Authorization: 'Bearer phc_real_edge_v6' }) ) const body = JSON.parse(String(requests[0].init?.body)) expect(body.batch).toHaveLength(1) expect(body.batch[0]).toMatchObject({ event: '$exception', distinct_id: 'user_edge', properties: expect.objectContaining({ $lib: 'posthog-edge', $pathname: '/edge-route', ...(expectedExceptionSource ? { $exception_source: expectedExceptionSource } : {}), $exception_list: [ expect.objectContaining({ mechanism: expect.objectContaining(expectedMechanism) }), ], }), }) } finally { errorSpy.mockRestore() await client?.shutdown() } } ) })