:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.
Python ab-testingai-analyticsanalyticscdpdata-warehouseexperimentsfeature-flagsjavascriptproduct-analyticspythonreactsession-replaysurveystypescriptweb-analytics
fix(api): stop handing callers a null response body they crash on (#73412)
posthog[bot]0c978962f30d
diff --git a/frontend/src/lib/api.test.ts b/frontend/src/lib/api.test.tsindex 8f20b41010ec..aef1ff293181 100644--- a/frontend/src/lib/api.test.ts+++ b/frontend/src/lib/api.test.ts@@ -1,7 +1,6 @@import posthog from 'posthog-js'-import api, { ApiConfig, ApiRequest } from 'lib/api'-import type { ApiError } from 'lib/api'+import api, { ApiConfig, ApiError, ApiRequest } from 'lib/api'import { NodeKind } from '~/queries/schema/schema-general'import { PropertyFilterType, PropertyOperator } from '~/types'@@ -16,7 +15,12 @@ describe('API helper', () => {beforeEach(() => {fakeFetch = jest.fn()- fakeFetch.mockResolvedValue({ ok: true, json: () => Promise.resolve(FAKE_FETCH_RESULT) })+ fakeFetch.mockResolvedValue({+ ok: true,+ status: 200,+ json: () => Promise.resolve(FAKE_FETCH_RESULT),+ text: () => Promise.resolve(JSON.stringify(FAKE_FETCH_RESULT)),+ })window.fetch = fakeFetchjest.spyOn(posthog, 'capture').mockImplementation(() => {@@ -203,6 +207,62 @@ describe('API helper', () => {})})+ describe('successful response body parsing', () => {+ const fakeResponse = ({ status = 200, text }: { status?: number; text: () => Promise<string> }): any => ({+ ok: true,+ status,+ text,+ })+ const bodyOf =+ (body: string): (() => Promise<string>) =>+ (): Promise<string> =>+ Promise.resolve(body)++ it.each([+ ['an HTML error page from a proxy/CDN', '<html><body>Bad gateway</body></html>'],+ // No content-length header involved: detection must work for chunked/compressed responses+ ['truncated JSON from a response cut mid-stream', '{"results": [1, 2'],+ ])('rejects with a status-less, request-scoped ApiError when the body is %s', async (_desc, body) => {+ fakeFetch.mockResolvedValue(fakeResponse({ text: bodyOf(body) }))+ const error = await api.get('api/environments/2/insights').catch((e) => e)+ expect(error).toBeInstanceOf(ApiError)+ // Method + path so occurrences are triageable in error tracking+ expect(error.message).toContain('[GET /api/environments/2/insights]')+ expect(error.message).toContain('status 200')+ // No `status`: a 2xx on an ApiError would make retry/recovery checks+ // (`status === undefined || status >= 500`) treat this transient failure as a client error+ expect(error.status).toBeUndefined()+ })++ it('carries the actual request method in the malformed-body error', async () => {+ fakeFetch.mockResolvedValue(fakeResponse({ text: bodyOf('<html></html>') }))+ const error = await api.create('api/environments/2/insights', {}).catch((e) => e)+ expect(error.message).toContain('[POST /api/environments/2/insights]')+ })++ it('surfaces a body stream that fails mid-read as an ApiError instead of null', async () => {+ fakeFetch.mockResolvedValue(fakeResponse({ text: () => Promise.reject(new TypeError('network error')) }))+ const error = await api.get('api/environments/2/insights').catch((e) => e)+ expect(error).toBeInstanceOf(ApiError)+ expect(error.status).toBeUndefined()+ })++ it.each([+ ['a 204 No Content response', 204, ''],+ ['an empty 200 body', 200, ''],+ ['a whitespace-only body', 200, ' \n '],+ ])('resolves to null for %s', async (_desc, status, body) => {+ fakeFetch.mockResolvedValue(fakeResponse({ status, text: bodyOf(body) }))+ await expect(api.get('api/environments/2/insights')).resolves.toBeNull()+ })++ it('propagates an AbortError instead of masquerading as a null result', async () => {+ const abortError = new DOMException('The operation was aborted', 'AbortError')+ fakeFetch.mockResolvedValue(fakeResponse({ text: () => Promise.reject(abortError) }))+ await expect(api.get('api/environments/2/insights')).rejects.toBe(abortError)+ })+ })+describe('organizationFeatureFlags', () => {it('builds correct URL for organization feature flags', () => {const apiRequest = new ApiRequest()diff --git a/frontend/src/lib/api.ts b/frontend/src/lib/api.tsindex d421c0766ecc..ec9b964cb1f5 100644--- a/frontend/src/lib/api.ts+++ b/frontend/src/lib/api.ts@@ -361,12 +361,64 @@ export function getCookie(name: string): string | null {return cookieValue}+function isAbortError(error: unknown): boolean {+ return (error as { name?: string } | null)?.name === 'AbortError'+}+export async function getJSONOrNull(response: Response): Promise<any> {try {return await response.json()- } catch {+ } catch (error) {+ // A body read cancelled mid-stream (navigation, superseded request) surfaces here as an+ // AbortError. Propagate it so it flows through the normal cancellation path instead of+ // masquerading as a successful `null` — otherwise callers dereference it (`.results`,+ // `.count`, …) and blow up with a `Cannot read properties of null` TypeError.+ if (isAbortError(error)) {+ throw error+ }+ return null+ }+}++/**+ * Parse the body of a *successful* response, which is expected to be JSON.+ *+ * Unlike getJSONOrNull (best-effort parsing of error bodies, where callers opt into handling+ * null), a non-empty body that isn't valid JSON is treated as a failure rather than silently+ * yielding null. Handing null back where callers expect the documented JSON shape is what turns+ * a transient backend/proxy hiccup (a non-JSON 2xx body) into a+ * `Cannot read properties of null (reading 'results')` crash deep inside loaders across the app.+ * An empty body (e.g. 204 No Content) still resolves to null, and aborts propagate as AbortError.+ *+ * The body is read as text first so the decision rests on actual content, not on headers —+ * chunked/compressed responses carry no content-length, and a truncated `application/json` body+ * must still surface as a failure. The thrown ApiError deliberately carries no `status`: the+ * HTTP status was 2xx, and recovery paths keyed on `status === undefined || status >= 500`+ * should classify a garbled body like the fetch-level network failure it effectively is. The+ * real status stays in the message for triage.+ */+async function getJSONFromSuccessResponse(response: Response, method: string, url: string): Promise<any> {+ const requestContext = (): string =>+ `[${method} ${new URL(url, location.origin).pathname}] (status ${response.status})`+ let text: string+ try {+ text = await response.text()+ } catch (error) {+ if (isAbortError(error)) {+ throw error+ }+ // The body stream failed mid-read (e.g. a network drop truncating a chunked response) —+ // the response is unusable, so surface it instead of handing callers a null.+ throw new ApiError(`Failed to read response body ${requestContext()}`)+ }+ if (!text.trim()) {return null}+ try {+ return JSON.parse(text)+ } catch {+ throw new ApiError(`Malformed JSON response ${requestContext()}`)+ }}export class ApiConfig {@@ -7176,7 +7228,7 @@ const api = {/** Fetch data from specified URL. The result already is JSON-parsed. */async get<T = any>(url: string, options?: ApiMethodOptions): Promise<T> {const res = await api.getResponse(url, options)- return await getJSONOrNull(res)+ return await getJSONFromSuccessResponse(res, 'GET', url)},async getResponse(url: string, options?: ApiMethodOptions): Promise<Response> {@@ -7229,7 +7281,7 @@ const api = {})})- return await getJSONOrNull(response)+ return await getJSONFromSuccessResponse(response, method, url)},async update<T = any, P = any>(url: string, data: P, options?: ApiMethodOptions): Promise<T> {@@ -7242,7 +7294,7 @@ const api = {async create<T = any, P = any>(url: string, data?: P, options?: ApiMethodOptions): Promise<T> {const res = await api.createResponse(url, data, options)- return await getJSONOrNull(res)+ return await getJSONFromSuccessResponse(res, 'POST', url)},async createResponse(url: string, data?: any, options?: ApiMethodOptions): Promise<Response> {diff --git a/frontend/src/scenes/data-management/events/eventInsightsLogic.ts b/frontend/src/scenes/data-management/events/eventInsightsLogic.tsindex e888575cdf7f..0a6e62013177 100644--- a/frontend/src/scenes/data-management/events/eventInsightsLogic.ts+++ b/frontend/src/scenes/data-management/events/eventInsightsLogic.ts@@ -119,7 +119,7 @@ export const eventInsightsLogic = kea<eventInsightsLogicType>([return {...response,filters,- results: response.results.map((rawInsight: any) => getQueryBasedInsightModel(rawInsight)),+ results: (response?.results ?? []).map((rawInsight: any) => getQueryBasedInsightModel(rawInsight)),} as InsightsResult},},diff --git a/frontend/src/scenes/notebooks/NotebookSelectButton/notebookSelectButtonLogic.ts b/frontend/src/scenes/notebooks/NotebookSelectButton/notebookSelectButtonLogic.tsindex e31d6212f5ab..33e399b1a599 100644--- a/frontend/src/scenes/notebooks/NotebookSelectButton/notebookSelectButtonLogic.ts+++ b/frontend/src/scenes/notebooks/NotebookSelectButton/notebookSelectButtonLogic.ts@@ -159,7 +159,7 @@ export const notebookSelectButtonLogic = kea<notebookSelectButtonLogicType>([order: '-last_modified_at',limit: NOTEBOOK_DROPDOWN_LIMIT,})- return response.results+ return response?.results ?? []},},],@@ -191,7 +191,7 @@ export const notebookSelectButtonLogic = kea<notebookSelectButtonLogicType>([order: '-last_modified_at',limit: NOTEBOOK_DROPDOWN_LIMIT,})- return response.results+ return response?.results ?? []},},],