Skip to content

: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.

refactor(toolbar): standardize API fetching through toolbarApi (#65089)

Rafael Audibertc151397bacda
diff --git a/frontend/src/lib/components/HedgehogMode/hedgehogModeLogic.ts b/frontend/src/lib/components/HedgehogMode/hedgehogModeLogic.ts
index f1c469b5fc82..edecb88f33f8 100644
--- a/frontend/src/lib/components/HedgehogMode/hedgehogModeLogic.ts
+++ b/frontend/src/lib/components/HedgehogMode/hedgehogModeLogic.ts
@@ -7,7 +7,8 @@ import api from 'lib/api'
import { membersLogic } from 'scenes/organization/membersLogic'
import { userLogic } from 'scenes/userLogic'
-import { toolbarConfigLogic, toolbarFetch } from '~/toolbar/toolbarConfigLogic'
+import { toolbarConfigLogic } from '~/toolbar/toolbarConfigLogic'
+import { toolbarFetch } from '~/toolbar/toolbarFetch'
import { HedgehogConfig, MinimalHedgehogConfig } from '~/types'
import { sanitizeHedgehogConfig } from './hedgehog-mode-utils'
diff --git a/frontend/src/lib/components/heatmaps/heatmapDataLogic.ts b/frontend/src/lib/components/heatmaps/heatmapDataLogic.ts
index 2f55c356eb38..a1fff35be69f 100644
--- a/frontend/src/lib/components/heatmaps/heatmapDataLogic.ts
+++ b/frontend/src/lib/components/heatmaps/heatmapDataLogic.ts
@@ -24,7 +24,8 @@ import { lemonToast } from 'lib/lemon-ui/LemonToast/LemonToast'
import { dateFilterToText } from 'lib/utils/dateFilters'
import { getAppContext } from 'lib/utils/getAppContext'
-import { toolbarConfigLogic, toolbarFetch } from '~/toolbar/toolbarConfigLogic'
+import { toolbarConfigLogic } from '~/toolbar/toolbarConfigLogic'
+import { toolbarFetch } from '~/toolbar/toolbarFetch'
import { HeatmapElement, HeatmapResponseType } from '~/toolbar/types'
import { FilterType } from '~/types'
diff --git a/frontend/src/toolbar/actions/actionsLogic.ts b/frontend/src/toolbar/actions/actionsLogic.ts
index e41c001b42c2..ce1508adee85 100644
--- a/frontend/src/toolbar/actions/actionsLogic.ts
+++ b/frontend/src/toolbar/actions/actionsLogic.ts
@@ -4,7 +4,7 @@ import { loaders } from 'kea-loaders'
import { createFuse } from 'lib/utils/fuseSearch'
import { permanentlyMount } from 'lib/utils/kea-logic-builders'
-import { toolbarConfigLogic, toolbarFetch } from '~/toolbar/toolbarConfigLogic'
+import { toolbarApi } from '~/toolbar/toolbarApi'
import { ActionType } from '~/types'
import type { actionsLogicType } from './actionsLogicType'
@@ -20,21 +20,16 @@ export const actionsLogic = kea<actionsLogicType>([
{
// oxlint-disable-next-line @typescript-eslint/no-unused-vars
getActions: async (_ = null, breakpoint: () => void) => {
- const response = await toolbarFetch('/api/projects/@current/actions/')
- const results = await response.json()
-
- if (response.status === 403) {
- toolbarConfigLogic.actions.authenticate()
- return []
- }
-
+ const result = await toolbarApi.actions.list({
+ context: 'load_actions',
+ reauthenticateOnForbidden: true,
+ })
breakpoint()
- if (!Array.isArray(results?.results)) {
- throw new Error('Error loading actions!')
+ if (!result.ok || !Array.isArray(result.data.results)) {
+ return values.allActions
}
-
- return results.results
+ return result.data.results
},
updateAction: ({ action }: { action: ActionType }) => {
return values.allActions.filter((r) => r.id !== action.id).concat([action])
diff --git a/frontend/src/toolbar/actions/actionsTabLogic.tsx b/frontend/src/toolbar/actions/actionsTabLogic.tsx
index 4763eb73dac9..36a2888dbdce 100644
--- a/frontend/src/toolbar/actions/actionsTabLogic.tsx
+++ b/frontend/src/toolbar/actions/actionsTabLogic.tsx
@@ -7,9 +7,9 @@ import { urls } from 'scenes/urls'
import { actionsLogic } from '~/toolbar/actions/actionsLogic'
import { toolbarLogic } from '~/toolbar/bar/toolbarLogic'
-import { toolbarConfigLogic, toolbarFetch } from '~/toolbar/toolbarConfigLogic'
-import { toolbarLogger } from '~/toolbar/toolbarLogger'
-import { captureToolbarException, toolbarPosthogJS } from '~/toolbar/toolbarPosthogJS'
+import { toolbarApi } from '~/toolbar/toolbarApi'
+import { toolbarConfigLogic } from '~/toolbar/toolbarConfigLogic'
+import { toolbarPosthogJS } from '~/toolbar/toolbarPosthogJS'
import { ActionDraftType, ActionForm } from '~/toolbar/types'
import {
actionStepToActionStepFormItem,
@@ -224,46 +224,38 @@ export const actionsTabLogic = kea<actionsTabLogicType>([
actionToSave.name = findUniqueActionName(values.newActionName)
}
- try {
- let res: Response
- if (selectedActionId && selectedActionId !== 'new') {
- res = await toolbarFetch(
- `/api/projects/@current/actions/${selectedActionId}/`,
- 'PATCH',
- actionToSave
- )
- } else {
- res = await toolbarFetch(`/api/projects/@current/actions/`, 'POST', actionToSave)
- }
- if (!res.ok) {
- const errorData = await res.json().catch(() => ({}))
- throw new Error(errorData.detail || `Request failed: ${res.status}`)
- }
- const response: ActionType = await res.json()
- breakpoint() // guard against stale async after unmount
+ const isUpdate = selectedActionId && selectedActionId !== 'new'
+ const result = isUpdate
+ ? await toolbarApi.actions.update(selectedActionId, actionToSave, {
+ context: 'save_action',
+ toastOnError: 'Failed to save action',
+ })
+ : await toolbarApi.actions.create(actionToSave, {
+ context: 'save_action',
+ toastOnError: 'Failed to save action',
+ })
- actions.selectAction(null)
- actionsLogic.actions.updateAction({ action: response })
+ if (!result.ok) {
+ actions.submitActionFormFailure(new Error(result.error.detail), {})
+ return
+ }
+ const response = result.data
+ breakpoint() // guard against stale async after unmount
- if (!values.automaticActionCreationEnabled) {
- lemonToast.success('Action saved', {
- button: {
- label: 'Open in PostHog',
- action: () =>
- window.open(joinWithUiHost(values.uiHost, urls.action(response.id)), '_blank'),
- },
- })
- }
+ actions.selectAction(null)
+ actionsLogic.actions.updateAction({ action: response })
- actions.actionCreatedSuccess(response)
- } catch (e) {
- toolbarLogger.error('actions', 'Failed to save action', { actionId: selectedActionId })
- captureToolbarException(e, 'action_save')
- if (e instanceof Error) {
- lemonToast.error(`Action save failed: ${e.message}`)
- }
- actions.submitActionFormFailure(e instanceof Error ? e : new Error(String(e)), {})
+ if (!values.automaticActionCreationEnabled) {
+ lemonToast.success('Action saved', {
+ button: {
+ label: 'Open in PostHog',
+ action: () =>
+ window.open(joinWithUiHost(values.uiHost, urls.action(response.id)), '_blank'),
+ },
+ })
}
+
+ actions.actionCreatedSuccess(response)
},
// whether we show errors after touch (true) or submit (false)
diff --git a/frontend/src/toolbar/elements/heatmapToolbarMenuLogic.ts b/frontend/src/toolbar/elements/heatmapToolbarMenuLogic.ts
index 6a056e4b00ea..ebf93250d223 100644
--- a/frontend/src/toolbar/elements/heatmapToolbarMenuLogic.ts
+++ b/frontend/src/toolbar/elements/heatmapToolbarMenuLogic.ts
@@ -1,6 +1,5 @@
import { actions, afterMount, beforeUnmount, connect, kea, listeners, path, reducers, selectors } from 'kea'
import { loaders } from 'kea-loaders'
-import { encodeParams } from 'kea-router'
import { subscriptions } from 'kea-subscriptions'
import { windowValues } from 'kea-window-values'
import { PostHog } from 'posthog-js'
@@ -13,12 +12,13 @@ import { createVersionChecker } from 'lib/utils/semver'
import { DOMIndex, buildDOMIndex, matchEventToElementUsingIndex } from '~/toolbar/elements/domElementIndex'
import { currentPageLogic } from '~/toolbar/stats/currentPageLogic'
-import { toolbarConfigLogic, toolbarFetch } from '~/toolbar/toolbarConfigLogic'
+import { toolbarApi } from '~/toolbar/toolbarApi'
+import { toolbarConfigLogic } from '~/toolbar/toolbarConfigLogic'
import { toolbarLogger } from '~/toolbar/toolbarLogger'
import { toolbarPosthogJS } from '~/toolbar/toolbarPosthogJS'
import { CountedHTMLElement, ElementsEventType } from '~/toolbar/types'
import { elementIsVisible, invalidateZoomCache, trimElement } from '~/toolbar/utils'
-import { FilterType, PropertyFilterType, PropertyOperator } from '~/types'
+import { PropertyFilterType, PropertyOperator } from '~/types'
import type { heatmapToolbarMenuLogicType } from './heatmapToolbarMenuLogicType'
@@ -233,51 +233,50 @@ export const heatmapToolbarMenuLogic = kea<heatmapToolbarMenuLogicType>([
await breakpoint(150)
const { href, wildcardHref } = values
- let defaultUrl: string = ''
- if (!url) {
- const params: Partial<FilterType> = {
- properties: [
- wildcardHref === href
- ? {
- key: '$current_url',
- value: href,
- operator: PropertyOperator.Exact,
- type: PropertyFilterType.Event,
- }
- : {
- key: '$current_url',
- value: `^${wildcardHref.split('*').map(escapeUnescapedRegex).join('.*')}$`,
- operator: PropertyOperator.Regex,
- type: PropertyFilterType.Event,
- },
- ],
- date_from: values.commonFilters.date_from,
- date_to: values.commonFilters.date_to,
- }
-
- defaultUrl = `/api/element/stats/${encodeParams(
- { ...params, paginate_response: true, sampling_factor: values.samplingFactor },
- '?'
- )}`
+ // We re-raise below to drive getElementStatsFailure; let the global
+ // loader handler report it once rather than capturing twice.
+ const options = {
+ context: 'load_heatmap_stats',
+ reauthenticateOnForbidden: true,
+ captureOnError: false,
}
-
- // toolbar fetch collapses queryparams but this URL has multiple with the same name
- const response = await toolbarFetch(
- url || defaultUrl,
- 'GET',
- undefined,
- url ? 'use-as-provided' : 'full'
- )
+ const result = url
+ ? // Paginating — the URL came from a previous response body.
+ await toolbarApi.elementStats.page(url, options)
+ : await toolbarApi.elementStats.list(
+ {
+ properties: [
+ wildcardHref === href
+ ? {
+ key: '$current_url',
+ value: href,
+ operator: PropertyOperator.Exact,
+ type: PropertyFilterType.Event,
+ }
+ : {
+ key: '$current_url',
+ value: `^${wildcardHref
+ .split('*')
+ .map(escapeUnescapedRegex)
+ .join('.*')}$`,
+ operator: PropertyOperator.Regex,
+ type: PropertyFilterType.Event,
+ },
+ ],
+ date_from: values.commonFilters.date_from,
+ date_to: values.commonFilters.date_to,
+ paginate_response: true,
+ sampling_factor: values.samplingFactor,
+ },
+ options
+ )
breakpoint()
- if (response.status === 403) {
- toolbarConfigLogic.actions.authenticate()
+ if (result.status === 403) {
return emptyElementsStatsPages
}
- const paginatedResults = await response.json()
-
- if (!Array.isArray(paginatedResults.results)) {
+ if (!result.ok || !Array.isArray(result.data.results)) {
throw new Error('Error loading HeatMap data!')
}
@@ -285,10 +284,10 @@ export const heatmapToolbarMenuLogic = kea<heatmapToolbarMenuLogicType>([
results: [
// if url is present we are paginating and merge results, otherwise we only use the new results
...(url ? values.elementStats?.results || [] : []),
- ...(paginatedResults.results || []),
+ ...(result.data.results || []),
],
- next: paginatedResults.next,
- previous: paginatedResults.previous,
+ next: result.data.next,
+ previous: result.data.previous,
} as PaginatedResponse<ElementsEventType>
},
},
diff --git a/frontend/src/toolbar/experiments/experimentsLogic.test.ts b/frontend/src/toolbar/experiments/experimentsLogic.test.ts
index 1dfc0fcc011c..4ed06d014384 100644
--- a/frontend/src/toolbar/experiments/experimentsLogic.test.ts
+++ b/frontend/src/toolbar/experiments/experimentsLogic.test.ts
@@ -66,35 +66,26 @@ describe('experimentsLogic', () => {
})
it.each([
- [
- 'a non-2xx response',
- { ok: false, status: 404, json: () => Promise.resolve({}) },
- ['HTTP 404', '/api/projects/@current/web_experiments/'],
- ],
+ ['a non-2xx response', { ok: false, status: 404, json: () => Promise.resolve({}) }],
[
'the body is not valid JSON',
{ ok: true, status: 200, json: () => Promise.reject(new Error('Unexpected token')) },
- ['not valid JSON'],
],
[
'results is not an array',
{ ok: true, status: 200, json: () => Promise.resolve({ results: { unexpected: true } }) },
- ['expected an array', 'got object'],
],
- ] as [string, Partial<Response> & { json?: () => Promise<unknown> }, string[]][])(
- 'throws a descriptive error when %s',
- async (_name, fetchResponse, expectedSubstrings) => {
+ ] as [string, Partial<Response> & { json?: () => Promise<unknown> }][])(
+ 'soft-fails to an empty list when %s',
+ async (_name, fetchResponse) => {
mockFetch(fetchResponse)
mountLogic()
await expectLogic(logic, () => {
logic.actions.getExperiments()
- }).toDispatchActions([
- 'getExperiments',
- (action) =>
- action.type === logic.actionTypes.getExperimentsFailure &&
- expectedSubstrings.every((s) => action.payload.error.includes(s)),
- ])
+ })
+ .toDispatchActions(['getExperiments', 'getExperimentsSuccess'])
+ .toMatchValues({ allExperiments: [] })
}
)
})
diff --git a/frontend/src/toolbar/experiments/experimentsLogic.ts b/frontend/src/toolbar/experiments/experimentsLogic.ts
index ca584b46df3b..0e831447578f 100644
--- a/frontend/src/toolbar/experiments/experimentsLogic.ts
+++ b/frontend/src/toolbar/experiments/experimentsLogic.ts
@@ -4,23 +4,11 @@ import { loaders } from 'kea-loaders'
import { createFuse } from 'lib/utils/fuseSearch'
import { permanentlyMount } from 'lib/utils/kea-logic-builders'
-import { toolbarConfigLogic, toolbarFetch } from '~/toolbar/toolbarConfigLogic'
-import { toolbarLogger } from '~/toolbar/toolbarLogger'
+import { toolbarApi } from '~/toolbar/toolbarApi'
import { WebExperiment } from '~/toolbar/types'
import type { experimentsLogicType } from './experimentsLogicType'
-/** Short, PII-free description of an unexpected value's shape for error messages. */
-function describeShape(value: unknown): string {
- if (value === null) {
- return 'null'
- }
- if (Array.isArray(value)) {
- return 'array'
- }
- return typeof value
-}
-
export const experimentsLogic = kea<experimentsLogicType>([
path(['toolbar', 'experiments', 'experimentsLogic']),
actions({
@@ -32,53 +20,18 @@ export const experimentsLogic = kea<experimentsLogicType>([
{
// oxlint-disable-next-line @typescript-eslint/no-unused-vars
getExperiments: async (_ = null, breakpoint: () => void) => {
- const url = '/api/projects/@current/web_experiments/'
- const response = await toolbarFetch(url)
-
- if (response.status === 403) {
- toolbarConfigLogic.actions.authenticate()
- return []
- }
-
- // toolbarFetch returns a stubbed 401 when there's no access token yet —
- // the toolbar simply isn't authenticated, so show an empty list, not an error.
- if (response.status === 401) {
- return []
- }
-
+ const result = await toolbarApi.webExperiments.list({
+ context: 'load_experiments',
+ reauthenticateOnForbidden: true,
+ })
breakpoint()
- // Transient server errors aren't actionable for the user — soft-fail to an
- // empty list and let them retry rather than surfacing a scary error panel.
- if (response.status >= 500) {
- toolbarLogger.warn('experiments', 'Server error loading experiments, returning empty list', {
- status: response.status,
- url,
- })
- return []
+ // Any failure (unauthenticated, server error, malformed body) soft-fails to
+ // the existing list — toolbarApi has already logged/reported it as needed.
+ if (!result.ok || !Array.isArray(result.data.results)) {
+ return values.allExperiments
}
-
- if (!response.ok) {
- throw new Error(`Failed to load experiments: HTTP ${response.status} from ${url}`)
- }
-
- let results: unknown
- try {
- results = await response.json()
- } catch {
- throw new Error(`Failed to load experiments: response from ${url} was not valid JSON`)
- }
-
- const resultsList = (results as { results?: unknown } | null)?.results
- if (!Array.isArray(resultsList)) {
- throw new Error(
- `Failed to load experiments: expected an array at "results" from ${url}, got ${describeShape(
- resultsList
- )}`
- )
- }
-
- return resultsList as WebExperiment[]
+ return result.data.results
},
updateExperiment: ({ experiment }: { experiment: WebExperiment }) => {
return values.allExperiments.filter((r) => r.id !== experiment.id).concat([experiment])
diff --git a/frontend/src/toolbar/experiments/experimentsTabLogic.test.ts b/frontend/src/toolbar/experiments/experimentsTabLogic.test.ts
index d09229487360..1e98a1b121b3 100644
--- a/frontend/src/toolbar/experiments/experimentsTabLogic.test.ts
+++ b/frontend/src/toolbar/experiments/experimentsTabLogic.test.ts
@@ -303,7 +303,7 @@ describe('experimentsTabLogic', () => {
theExperimentsTabLogic.actions.submitExperimentForm()
}).delay(0)
- expect(lemonToast.error).toHaveBeenCalledWith('Experiment save failed: Invalid experiment config')
+ expect(lemonToast.error).toHaveBeenCalledWith('Invalid experiment config')
})
it('shows generic error when API returns error and json parsing fails', async () => {
@@ -324,7 +324,7 @@ describe('experimentsTabLogic', () => {
theExperimentsTabLogic.actions.submitExperimentForm()
}).delay(0)
- expect(lemonToast.error).toHaveBeenCalledWith('Experiment save failed: Request failed: 500')
+ expect(lemonToast.error).toHaveBeenCalledWith('Failed to save experiment')
})
it('handles network error gracefully', async () => {
@@ -339,7 +339,7 @@ describe('experimentsTabLogic', () => {
theExperimentsTabLogic.actions.submitExperimentForm()
}).delay(0)
- expect(lemonToast.error).toHaveBeenCalledWith('Experiment save failed: Network error')
+ expect(lemonToast.error).toHaveBeenCalledWith('Failed to save experiment')
})
})
diff --git a/frontend/src/toolbar/experiments/experimentsTabLogic.tsx b/frontend/src/toolbar/experiments/experimentsTabLogic.tsx
index 60cb42cb533c..ae8f38b4d7ba 100644
--- a/frontend/src/toolbar/experiments/experimentsTabLogic.tsx
+++ b/frontend/src/toolbar/experiments/experimentsTabLogic.tsx
@@ -16,9 +16,9 @@ import {
setSanitizedHTML,
setSanitizedStyle,
} from '~/toolbar/experiments/sanitize'
-import { toolbarConfigLogic, toolbarFetch } from '~/toolbar/toolbarConfigLogic'
-import { toolbarLogger } from '~/toolbar/toolbarLogger'
-import { captureToolbarException, toolbarPosthogJS } from '~/toolbar/toolbarPosthogJS'
+import { toolbarApi } from '~/toolbar/toolbarApi'
+import { toolbarConfigLogic } from '~/toolbar/toolbarConfigLogic'
+import { toolbarPosthogJS } from '~/toolbar/toolbarPosthogJS'
import { WebExperiment, WebExperimentDraftType, WebExperimentForm } from '~/toolbar/types'
import { elementToQuery, joinWithUiHost } from '~/toolbar/utils'
import { Experiment, ExperimentIdType } from '~/types'
@@ -193,45 +193,32 @@ export const experimentsTabLogic = kea<experimentsTabLogicType>([
const { uiHost } = values
const { selectedExperimentId } = values
- let response: WebExperiment
- try {
- let res: Response
- if (selectedExperimentId && selectedExperimentId !== 'new') {
- res = await toolbarFetch(
- `/api/projects/@current/web_experiments/${selectedExperimentId}/`,
- 'PATCH',
- experimentToSave
- )
- } else {
- res = await toolbarFetch(`/api/projects/@current/web_experiments/`, 'POST', experimentToSave)
- }
-
- if (!res.ok) {
- const errorData = await res.json().catch(() => ({}))
- throw new Error(errorData.detail || `Request failed: ${res.status}`)
- }
-
- response = await res.json()
+ const isUpdate = selectedExperimentId && selectedExperimentId !== 'new'
+ const result = isUpdate
+ ? await toolbarApi.webExperiments.update(selectedExperimentId, experimentToSave, {
+ context: 'save_experiment',
+ toastOnError: 'Failed to save experiment',
+ })
+ : await toolbarApi.webExperiments.create(experimentToSave, {
+ context: 'save_experiment',
+ toastOnError: 'Failed to save experiment',
+ })
+
+ if (!result.ok) {
+ return
+ }
+ const response = result.data
- experimentsLogic.actions.updateExperiment({ experiment: response })
- actions.selectExperiment(null)
+ experimentsLogic.actions.updateExperiment({ experiment: response })
+ actions.selectExperiment(null)
- lemonToast.success('Experiment saved', {
- button: {
- label: 'Open in PostHog',
- action: () => window.open(joinWithUiHost(uiHost, urls.experiment(response.id)), '_blank'),
- },
- })
- breakpoint()
- } catch (e) {
- toolbarLogger.error('experiments', 'Failed to save experiment', {
- experimentId: selectedExperimentId,
- })
- captureToolbarException(e, 'experiment_save')
- if (e instanceof Error) {
- lemonToast.error(`Experiment save failed: ${e.message}`)
- }
- }
+ lemonToast.success('Experiment saved', {
+ button: {
+ label: 'Open in PostHog',
+ action: () => window.open(joinWithUiHost(uiHost, urls.experiment(response.id)), '_blank'),
+ },
+ })
+ breakpoint()
},
// whether we show errors after touch (true) or submit (false)
diff --git a/frontend/src/toolbar/field-notes/fieldNotesLogic.ts b/frontend/src/toolbar/field-notes/fieldNotesLogic.ts
index 46a28ec42bfb..94d6e50850c5 100644
--- a/frontend/src/toolbar/field-notes/fieldNotesLogic.ts
+++ b/frontend/src/toolbar/field-notes/fieldNotesLogic.ts
@@ -4,7 +4,8 @@ import { loaders } from 'kea-loaders'
import { lemonToast } from 'lib/lemon-ui/LemonToast'
import { inferSelector } from '~/toolbar/product-tours/elementInference'
-import { toolbarConfigLogic, toolbarFetch } from '~/toolbar/toolbarConfigLogic'
+import { toolbarApi } from '~/toolbar/toolbarApi'
+import { toolbarConfigLogic } from '~/toolbar/toolbarConfigLogic'
import { toolbarLogger } from '~/toolbar/toolbarLogger'
import { captureToolbarException, toolbarPosthogJS } from '~/toolbar/toolbarPosthogJS'
import { ElementRect } from '~/toolbar/types'
@@ -77,12 +78,13 @@ export const fieldNotesLogic = kea<fieldNotesLogicType>([
[] as FieldNote[],
{
loadFieldNotes: async () => {
- const response = await toolbarFetch('/api/projects/@current/field_notes/?field_note_status=pending')
- if (!response.ok) {
+ const result = await toolbarApi.fieldNotes.listPending<{ results?: FieldNote[] } | FieldNote[]>({
+ context: 'load_field_notes',
+ })
+ if (!result.ok) {
return values.fieldNotes
}
- const data = await response.json()
- return data.results ?? data
+ return Array.isArray(result.data) ? result.data : (result.data.results ?? [])
},
},
],
@@ -211,30 +213,17 @@ export const fieldNotesLogic = kea<fieldNotesLogicType>([
...(screenshotUrl ? { screenshot_url: screenshotUrl } : {}),
}
- try {
- const response = await toolbarFetch('/api/projects/@current/field_notes/', 'POST', payload)
- if (!response.ok) {
- const error = await response.json().catch(() => ({}))
- toolbarLogger.error('field-notes', 'Save failed', {
- status: response.status,
- detail: error.detail,
- })
- lemonToast.error(
- `Failed to save field note (${response.status})${error.detail ? `: ${error.detail}` : ''}`
- )
- return null
- }
- const saved = await response.json()
- lemonToast.success('Field note saved')
- actions.clearSelection()
- actions.loadFieldNotes()
- return saved
- } catch (e: any) {
- toolbarLogger.error('field-notes', 'Failed to save field note')
- captureToolbarException(e, 'field_note_save')
- lemonToast.error('Failed to save field note')
+ const result = await toolbarApi.fieldNotes.create<FieldNote>(payload, {
+ context: 'save_field_note',
+ toastOnError: 'Failed to save field note',
+ })
+ if (!result.ok) {
return null
}
+ lemonToast.success('Field note saved')
+ actions.clearSelection()
+ actions.loadFieldNotes()
+ return result.data
},
},
],
@@ -259,10 +248,10 @@ export const fieldNotesLogic = kea<fieldNotesLogicType>([
}
},
deleteFieldNote: async ({ id }) => {
- const response = await toolbarFetch(`/api/projects/@current/field_notes/${id}/`, 'DELETE')
- if (!response.ok && response.status !== 204) {
- lemonToast.error(`Failed to delete field note (${response.status})`)
- }
+ await toolbarApi.fieldNotes.delete(id, {
+ context: 'delete_field_note',
+ toastOnError: 'Failed to delete field note',
+ })
actions.loadFieldNotes()
},
})),
diff --git a/frontend/src/toolbar/flags/flagsToolbarLogic.ts b/frontend/src/toolbar/flags/flagsToolbarLogic.ts
index 3a5a7da89036..826e265faee5 100644
--- a/frontend/src/toolbar/flags/flagsToolbarLogic.ts
+++ b/frontend/src/toolbar/flags/flagsToolbarLogic.ts
@@ -1,12 +1,12 @@
import { actions, connect, kea, listeners, path, reducers, selectors } from 'kea'
import { loaders } from 'kea-loaders'
-import { encodeParams } from 'kea-router'
import type { PostHog } from 'posthog-js'
import { createFuse } from 'lib/utils/fuseSearch'
import { permanentlyMount } from 'lib/utils/kea-logic-builders'
-import { toolbarConfigLogic, toolbarFetch } from '~/toolbar/toolbarConfigLogic'
+import { toolbarApi } from '~/toolbar/toolbarApi'
+import { toolbarConfigLogic } from '~/toolbar/toolbarConfigLogic'
import { toolbarLogger } from '~/toolbar/toolbarLogger'
import { captureToolbarException, toolbarPosthogJS } from '~/toolbar/toolbarPosthogJS'
import { CombinedFeatureFlagAndValueType } from '~/types'
@@ -63,18 +63,16 @@ export const flagsToolbarLogic = kea<flagsToolbarLogicType>([
[] as CombinedFeatureFlagAndValueType[],
{
getUserFlags: async (_, breakpoint) => {
- const params = {
- groups: getGroups(values.posthog),
- }
- const response = await toolbarFetch(
- `/api/projects/@current/feature_flags/my_flags${encodeParams(params, '?')}`
+ const result = await toolbarApi.featureFlags.myFlags(
+ { groups: getGroups(values.posthog) },
+ { context: 'load_user_flags' }
)
breakpoint()
- if (!response.ok) {
- return []
+ if (!result.ok) {
+ return values.userFlags
}
- return await response.json()
+ return result.data
},
},
],
@@ -301,17 +299,16 @@ export const flagsToolbarLogic = kea<flagsToolbarLogicType>([
}
},
loadFlagsForDistinctId: async ({ distinctId }, breakpoint) => {
- const params = { distinct_id: distinctId }
- const response = await toolbarFetch(
- `/api/projects/@current/feature_flags/evaluation_reasons${encodeParams(params, '?')}`
- )
+ const result = await toolbarApi.featureFlags.evaluationReasons<EvaluationReasonsResponse>(distinctId, {
+ context: 'load_flags_for_distinct_id',
+ })
breakpoint()
- if (!response.ok) {
+ if (!result.ok) {
return
}
- const data: EvaluationReasonsResponse = await response.json()
+ const data = result.data
const flagValues: Record<string, string | boolean> = {}
for (const [key, entry] of Object.entries(data)) {
flagValues[key] = entry.value
diff --git a/frontend/src/toolbar/product-tours/productToursLogic.ts b/frontend/src/toolbar/product-tours/productToursLogic.ts
index 6943db9cbd8a..099678490e87 100644
--- a/frontend/src/toolbar/product-tours/productToursLogic.ts
+++ b/frontend/src/toolbar/product-tours/productToursLogic.ts
@@ -20,7 +20,8 @@ import {
import { urls } from 'scenes/urls'
import { toolbarLogic } from '~/toolbar/bar/toolbarLogic'
-import { toolbarConfigLogic, toolbarFetch } from '~/toolbar/toolbarConfigLogic'
+import { toolbarApi } from '~/toolbar/toolbarApi'
+import { toolbarConfigLogic } from '~/toolbar/toolbarConfigLogic'
import { toolbarLogger } from '~/toolbar/toolbarLogger'
import { captureToolbarException, toolbarPosthogJS } from '~/toolbar/toolbarPosthogJS'
import { ElementRect } from '~/toolbar/types'
@@ -191,12 +192,11 @@ export const productToursLogic = kea<productToursLogicType>([
[] as ProductTour[],
{
loadTours: async () => {
- const response = await toolbarFetch('/api/projects/@current/product_tours/')
- if (!response.ok) {
+ const result = await toolbarApi.productTours.list({ context: 'load_product_tours' })
+ if (!result.ok) {
return []
}
- const data = await response.json()
- return data.results ?? data
+ return Array.isArray(result.data) ? result.data : (result.data.results ?? [])
},
},
],
@@ -339,12 +339,14 @@ export const productToursLogic = kea<productToursLogicType>([
if (!formValues.id) {
return
}
- const response = await toolbarFetch(
- `/api/projects/@current/product_tours/${formValues.id}/draft/`,
- 'PATCH',
- buildDraftPayload(formValues, values.tours)
+ // Re-raise on failure so kea-forms runs submitTourFormFailure (resets the
+ // draft-save status). toolbarApi already logged it, so don't double-report.
+ const result = await toolbarApi.productTours.updateDraft(
+ formValues.id,
+ buildDraftPayload(formValues, values.tours),
+ { context: 'save_product_tour_draft', captureOnError: false }
)
- if (!response.ok) {
+ if (!result.ok) {
throw new Error('Failed to save draft')
}
},
@@ -603,35 +605,30 @@ export const productToursLogic = kea<productToursLogicType>([
}
const isUpdate = !!tourForm.id
const payload = { ...buildDraftPayload(tourForm, tours), creation_context: 'toolbar' }
- const url = isUpdate
- ? `/api/projects/@current/product_tours/${tourForm.id}/draft/`
- : '/api/projects/@current/product_tours/'
- const method = isUpdate ? 'PATCH' : 'POST'
- try {
- const response = await toolbarFetch(url, method, payload)
- if (!response.ok) {
- const error = await response.json()
- lemonToast.error(error.detail || 'Failed to save tour')
- return
- }
- const savedTour = await response.json()
- const editUrl = joinWithUiHost(uiHost, urls.productTour(savedTour.id, 'edit=true'))
- if (launchedFromMainApp) {
- window.close()
- } else {
- lemonToast.success(isUpdate ? 'Tour saved' : 'Tour created', {
- button: {
- label: 'Open in PostHog',
- action: () => window.open(editUrl, '_blank'),
- },
- })
- actions.loadTours()
- actions.selectTour(null)
- }
- } catch (e: any) {
- toolbarLogger.error('product_tours', 'Failed to save tour', { tourId: tourForm?.id })
- captureToolbarException(e, 'product_tour_save')
- lemonToast.error(e.detail || 'Failed to save tour')
+ const result = tourForm.id
+ ? await toolbarApi.productTours.updateDraft(tourForm.id, payload, {
+ context: 'save_product_tour',
+ toastOnError: 'Failed to save tour',
+ })
+ : await toolbarApi.productTours.create(payload, {
+ context: 'save_product_tour',
+ toastOnError: 'Failed to save tour',
+ })
+ if (!result.ok) {
+ return
+ }
+ const editUrl = joinWithUiHost(uiHost, urls.productTour(result.data.id, 'edit=true'))
+ if (launchedFromMainApp) {
+ window.close()
+ } else {
+ lemonToast.success(isUpdate ? 'Tour saved' : 'Tour created', {
+ button: {
+ label: 'Open in PostHog',
+ action: () => window.open(editUrl, '_blank'),
+ },
+ })
+ actions.loadTours()
+ actions.selectTour(null)
}
},
draftAutoSave: async (_, breakpoint) => {
@@ -737,13 +734,14 @@ export const productToursLogic = kea<productToursLogicType>([
}
},
deleteTour: async ({ id }) => {
- const response = await toolbarFetch(`/api/projects/@current/product_tours/${id}/`, 'DELETE')
- if (response.ok) {
+ const result = await toolbarApi.productTours.delete(id, {
+ context: 'delete_product_tour',
+ toastOnError: 'Failed to delete tour',
+ })
+ if (result.ok) {
lemonToast.success('Tour deleted')
actions.loadTours()
actions.selectTour(null)
- } else {
- lemonToast.error('Failed to delete tour')
}
},
showButtonProductTours: () => {
diff --git a/frontend/src/toolbar/screenshot-upload/screenshotUploadLogic.ts b/frontend/src/toolbar/screenshot-upload/screenshotUploadLogic.ts
index 0d7e92c8e4a1..8f24880f3241 100644
--- a/frontend/src/toolbar/screenshot-upload/screenshotUploadLogic.ts
+++ b/frontend/src/toolbar/screenshot-upload/screenshotUploadLogic.ts
@@ -3,7 +3,7 @@ import { loaders } from 'kea-loaders'
import { lemonToast } from 'lib/lemon-ui/LemonToast'
-import { toolbarConfigLogic, toolbarFetch } from '~/toolbar/toolbarConfigLogic'
+import { toolbarApi } from '~/toolbar/toolbarApi'
import { toolbarPosthogJS } from '~/toolbar/toolbarPosthogJS'
import { captureElementScreenshot, uploadScreenshot } from '~/toolbar/utils/screenshot'
import { EventDefinition } from '~/types'
@@ -66,18 +66,16 @@ export const screenshotUploadLogic = kea<screenshotUploadLogicType>([
return []
}
await breakpoint(300)
- const response = await toolbarFetch(
- `/api/projects/@current/event_definitions/?search=${encodeURIComponent(query)}&limit=20&event_type=event_custom`
- )
+ const result = await toolbarApi.eventDefinitions.search(query, {
+ context: 'search_event_definitions',
+ reauthenticateOnForbidden: true,
+ })
- if (response.status === 403) {
- toolbarConfigLogic.actions.authenticate()
+ breakpoint()
+ if (!result.ok) {
return []
}
-
- breakpoint()
- const data = await response.json()
- return data.results ?? []
+ return result.data.results ?? []
},
},
],
@@ -95,11 +93,19 @@ export const screenshotUploadLogic = kea<screenshotUploadLogicType>([
const { mediaId } = await uploadScreenshot(blob)
breakpoint()
- await toolbarFetch('/api/projects/@current/object_media_previews/', 'POST', {
- uploaded_media_id: mediaId,
- event_definition_id: selectedDefinition.id,
- })
+ // Re-raise on failure so submitUploadFailure surfaces the toast; toolbarApi
+ // already logged it, so don't double-report via the global loader handler.
+ const result = await toolbarApi.objectMediaPreviews.create(
+ {
+ uploaded_media_id: mediaId,
+ event_definition_id: selectedDefinition.id,
+ },
+ { context: 'create_object_media_preview', captureOnError: false }
+ )
breakpoint()
+ if (!result.ok) {
+ throw new Error(result.error.detail)
+ }
return { success: true }
},
diff --git a/frontend/src/toolbar/surveys/surveysToolbarLogic.ts b/frontend/src/toolbar/surveys/surveysToolbarLogic.ts
index af5d35d6dece..45647c635f86 100644
--- a/frontend/src/toolbar/surveys/surveysToolbarLogic.ts
+++ b/frontend/src/toolbar/surveys/surveysToolbarLogic.ts
@@ -5,7 +5,8 @@ import { lemonToast } from 'lib/lemon-ui/LemonToast/LemonToast'
import { urls } from 'scenes/urls'
import { toolbarLogic } from '~/toolbar/bar/toolbarLogic'
-import { toolbarConfigLogic, toolbarFetch } from '~/toolbar/toolbarConfigLogic'
+import { toolbarApi } from '~/toolbar/toolbarApi'
+import { toolbarConfigLogic } from '~/toolbar/toolbarConfigLogic'
import { toolbarPosthogJS } from '~/toolbar/toolbarPosthogJS'
import { joinWithUiHost } from '~/toolbar/utils'
import {
@@ -329,46 +330,15 @@ async function patchAndRefreshSurvey(
payload: Record<string, unknown>,
successMessage: string
): Promise<boolean> {
- try {
- const response = await toolbarFetch(`/api/projects/@current/surveys/${surveyId}/`, 'PATCH', payload)
- if (!response.ok) {
- const error = await response.json().catch(() => ({}))
- lemonToast.error(formatApiError(error, response.status, 'Failed to update survey'))
- return false
- }
- lemonToast.success(successMessage)
- return true
- } catch (e) {
- // eslint-disable-next-line no-console
- console.warn('[Toolbar] survey lifecycle update failed', e)
- lemonToast.error('Failed to update survey')
+ const result = await toolbarApi.surveys.update(surveyId, payload, {
+ context: 'update_survey',
+ toastOnError: 'Failed to update survey',
+ })
+ if (!result.ok) {
return false
}
-}
-
-function formatApiError(error: unknown, status: number, fallback: string): string {
- if (status === 401 || status === 403) {
- return 'Your toolbar session lacks permission. Please re-authenticate the toolbar from PostHog.'
- }
- if (error && typeof error === 'object') {
- const errObj = error as Record<string, unknown>
- if (typeof errObj.detail === 'string' && errObj.detail) {
- return errObj.detail
- }
- // Surface DRF field-level errors: { name: ["..."], questions: [...] }.
- const fieldMessages: string[] = []
- for (const [key, value] of Object.entries(errObj)) {
- if (Array.isArray(value) && value.length > 0 && typeof value[0] === 'string') {
- fieldMessages.push(`${key}: ${value[0]}`)
- } else if (typeof value === 'string') {
- fieldMessages.push(`${key}: ${value}`)
- }
- }
- if (fieldMessages.length > 0) {
- return fieldMessages.join('; ')
- }
- }
- return fallback
+ lemonToast.success(successMessage)
+ return true
}
export const surveysToolbarLogic = kea<surveysToolbarLogicType>([
@@ -402,27 +372,21 @@ export const surveysToolbarLogic = kea<surveysToolbarLogicType>([
{
loadSurveys: async () => {
const search = values.searchTerm
- const params = new URLSearchParams()
- params.set('archived', 'false')
- params.set('limit', String(SURVEYS_PAGE_SIZE))
- params.set('offset', '0')
- if (search) {
- params.set('search', search)
- }
- const url = `/api/projects/@current/surveys/?${params}`
- const response = await toolbarFetch(url)
+ const result = await toolbarApi.surveys.list(
+ { limit: SURVEYS_PAGE_SIZE, offset: 0, search: search || undefined },
+ { context: 'load_surveys' }
+ )
// If the search term changed while we were awaiting,
// abandon this result to avoid clobbering newer state.
if (search !== values.searchTerm) {
return values.allSurveys
}
- if (!response.ok) {
+ if (!result.ok) {
actions.setHasMoreSurveys(false)
return []
}
- const data = await response.json().catch(() => ({}))
- actions.setHasMoreSurveys(!!data.next)
- return data.results ?? data ?? []
+ actions.setHasMoreSurveys(!!result.data.next)
+ return result.data.results ?? []
},
loadMoreSurveys: async () => {
if (!values.hasMoreSurveys || values.allSurveysLoading) {
@@ -430,25 +394,19 @@ export const surveysToolbarLogic = kea<surveysToolbarLogicType>([
}
const search = values.searchTerm
const previousIds = new Set(values.allSurveys.map((s) => s.id))
- const params = new URLSearchParams()
- params.set('archived', 'false')
- params.set('limit', String(SURVEYS_PAGE_SIZE))
- params.set('offset', String(values.allSurveys.length))
- if (search) {
- params.set('search', search)
- }
- const url = `/api/projects/@current/surveys/?${params}`
- const response = await toolbarFetch(url)
+ const result = await toolbarApi.surveys.list(
+ { limit: SURVEYS_PAGE_SIZE, offset: values.allSurveys.length, search: search || undefined },
+ { context: 'load_more_surveys' }
+ )
// Search changed while we were paging — drop the result.
if (search !== values.searchTerm) {
return values.allSurveys
}
- if (!response.ok) {
+ if (!result.ok) {
return values.allSurveys
}
- const data = await response.json().catch(() => ({}))
- actions.setHasMoreSurveys(!!data.next)
- const newRows: Survey[] = (data.results ?? data ?? []).filter((s: Survey) => !previousIds.has(s.id))
+ actions.setHasMoreSurveys(!!result.data.next)
+ const newRows: Survey[] = (result.data.results ?? []).filter((s: Survey) => !previousIds.has(s.id))
return [...values.allSurveys, ...newRows]
},
},
@@ -681,62 +639,51 @@ export const surveysToolbarLogic = kea<surveysToolbarLogicType>([
} else if (editingId) {
delete payload.start_date
}
- try {
- const response = await toolbarFetch(
- editingId ? `/api/projects/@current/surveys/${editingId}/` : '/api/projects/@current/surveys/',
- editingId ? 'PATCH' : 'POST',
- payload
- )
- // If the user cancelled while we were awaiting, drop the result
- // silently — they explicitly threw the work away.
- if (!values.isCreating) {
- return
- }
- if (!response.ok) {
- const error = await response.json().catch(() => ({}))
- lemonToast.error(
- formatApiError(
- error,
- response.status,
- editingId ? 'Failed to save survey' : 'Failed to create survey'
- )
- )
- actions.submitQuickCreateFailure()
- return
- }
- const saved = await response.json().catch(() => ({}))
- toolbarPosthogJS.capture(editingId ? 'toolbar survey edited' : 'toolbar survey created', {
- question_type: values.quickForm.questionType,
- has_url_targeting: values.quickForm.targetingMode === 'specific',
- frequency: values.quickForm.frequency,
- trigger_mode: values.quickForm.triggerMode,
- launched: launch,
- })
- const { uiHost } = toolbarConfigLogic.values
- const surveyUrl = saved.id ? joinWithUiHost(uiHost, urls.survey(saved.id)) : null
- const message = editingId
- ? launch
- ? 'Survey saved and launched'
- : 'Survey saved'
- : launch
- ? 'Survey launched'
- : 'Draft survey created'
- lemonToast.success(message, {
- button: surveyUrl
- ? {
- label: 'Open in PostHog',
- action: () => window.open(surveyUrl, '_blank'),
- }
- : undefined,
- })
- actions.submitQuickCreateSuccess()
- actions.loadSurveys()
- } catch (e) {
- // eslint-disable-next-line no-console
- console.warn('[Toolbar] survey submit failed', e)
- lemonToast.error(editingId ? 'Failed to save survey' : 'Failed to create survey')
+ const result = editingId
+ ? await toolbarApi.surveys.update(editingId, payload, {
+ context: 'save_survey',
+ toastOnError: 'Failed to save survey',
+ })
+ : await toolbarApi.surveys.create(payload, {
+ context: 'create_survey',
+ toastOnError: 'Failed to create survey',
+ })
+ // If the user cancelled while we were awaiting, drop the result
+ // silently — they explicitly threw the work away.
+ if (!values.isCreating) {
+ return
+ }
+ if (!result.ok) {
actions.submitQuickCreateFailure()
+ return
}
+ const saved = result.data
+ toolbarPosthogJS.capture(editingId ? 'toolbar survey edited' : 'toolbar survey created', {
+ question_type: values.quickForm.questionType,
+ has_url_targeting: values.quickForm.targetingMode === 'specific',
+ frequency: values.quickForm.frequency,
+ trigger_mode: values.quickForm.triggerMode,
+ launched: launch,
+ })
+ const { uiHost } = toolbarConfigLogic.values
+ const surveyUrl = saved.id ? joinWithUiHost(uiHost, urls.survey(saved.id)) : null
+ const message = editingId
+ ? launch
+ ? 'Survey saved and launched'
+ : 'Survey saved'
+ : launch
+ ? 'Survey launched'
+ : 'Draft survey created'
+ lemonToast.success(message, {
+ button: surveyUrl
+ ? {
+ label: 'Open in PostHog',
+ action: () => window.open(surveyUrl, '_blank'),
+ }
+ : undefined,
+ })
+ actions.submitQuickCreateSuccess()
+ actions.loadSurveys()
},
})),
])
diff --git a/frontend/src/toolbar/toolbarApi.ts b/frontend/src/toolbar/toolbarApi.ts
new file mode 100644
index 000000000000..469e589a1cb0
--- /dev/null
+++ b/frontend/src/toolbar/toolbarApi.ts
@@ -0,0 +1,391 @@
+import { encodeParams } from 'kea-router'
+
+import type { PaginatedResponse } from 'lib/api'
+import { lemonToast } from 'lib/lemon-ui/LemonToast/LemonToast'
+
+import { toolbarConfigLogic } from '~/toolbar/toolbarConfigLogic'
+import { toolbarFetch } from '~/toolbar/toolbarFetch'
+import { toolbarLogger } from '~/toolbar/toolbarLogger'
+import { captureToolbarException } from '~/toolbar/toolbarPosthogJS'
+import type { ElementsEventType, WebExperiment } from '~/toolbar/types'
+import type { ActionType, CombinedFeatureFlagAndValueType, EventDefinition, ProductTour, Survey } from '~/types'
+
+/**
+ * The single, blessed way to talk to the PostHog API from the toolbar.
+ *
+ * Every authenticated data request should go through `toolbarApi` — preferably one of its
+ * resource namespaces (`toolbarApi.actions.list()`, `toolbarApi.surveys.update(id, …)`), which
+ * own the route strings (see the `toolbarApi` export below for the full contract). It wraps
+ * `toolbarFetch` (which owns the OAuth bearer + token refresh) and folds the eight different
+ * ad-hoc failure-handling styles the toolbar had grown into one consistent contract:
+ *
+ * - It never throws. Network-level failures (CORS, offline, a customer page that
+ * replaced `window.fetch`) are caught and returned as a normal failure result,
+ * so no caller needs a `try/catch` and no listener can leak an unhandled rejection.
+ * - It always parses the body and returns a discriminated-union `ToolbarApiResult`,
+ * so every call site branches on `result.ok` the same way.
+ * - It centralizes observability: every failure is logged via `toolbarLogger`, and
+ * genuinely-unexpected failures (network errors, 5xx, malformed JSON) are reported
+ * to error tracking. Auth (401/403) and client (4xx) errors are expected outcomes —
+ * they are logged but not reported as exceptions.
+ * - Per-request telemetry (`toolbar api request`) is emitted by `toolbarFetch` itself.
+ *
+ * What stays at the call site is only what is genuinely call-site specific: the
+ * fallback value to use on failure, and any feature side effects (e.g. resetting a
+ * form, disabling a mode). Toasting and re-authentication are opt-in via options so
+ * that loaders stay quiet while user-initiated writes can surface a message.
+ *
+ * Auth flows (OAuth code exchange, token refresh, the reachability HEAD check) and the
+ * pre-mount feature-flag preload deliberately do NOT use this — they run before the
+ * toolbar is authenticated (or before kea is mounted) and own their own fetch behavior.
+ */
+
+export type ToolbarApiMethod = 'GET' | 'POST' | 'PATCH' | 'PUT' | 'DELETE'
+
+export interface ToolbarApiErrorInfo {
+ /** HTTP status, or 0 for a network-level failure that never reached the server. */
+ status: number
+ /** Best human-readable message extracted from the response body, or a fallback. */
+ detail: string
+ /** Parsed JSON body, when there was one. */
+ body: unknown
+ /** 401/403 — the session is missing, expired, or lacks access. Handled by the auth flow. */
+ isAuthError: boolean
+ /** The request never completed (CORS, offline, aborted, customer fetch wrapper threw). */
+ isNetworkError: boolean
+}
+
+export type ToolbarApiResult<T> =
+ | { ok: true; status: number; data: T }
+ | { ok: false; status: number; data: null; error: ToolbarApiErrorInfo }
+
+export interface ToolbarApiOptions {
+ /**
+ * Identifies the call site in logs, telemetry, and error tracking, e.g. `'load_actions'`.
+ * Use a short snake_case string.
+ */
+ context: string
+ /**
+ * Surface a `lemonToast.error` when the request fails. Pass `true` to show the
+ * extracted error detail, or a string to use as the fallback message when the
+ * response carries no specific detail. Defaults to `false` (silent — the failure
+ * is still logged and, when unexpected, reported). Prefer `false` for background
+ * loaders and a string for user-initiated writes.
+ */
+ toastOnError?: boolean | string
+ /**
+ * Re-trigger the OAuth flow when the request returns 403 (project access lost or the
+ * user switched projects). `toolbarFetch` already clears the session on 403; this
+ * additionally kicks off re-authentication. Defaults to `false`.
+ */
+ reauthenticateOnForbidden?: boolean
+ /**
+ * Report unexpected failures (network / 5xx / malformed JSON) to error tracking.
+ * Defaults to `true`. Set to `false` when the caller deliberately re-raises the
+ * failure (e.g. a kea loader that throws to drive its own `*Failure` reducer) so the
+ * exception is only captured once.
+ */
+ captureOnError?: boolean
+ /**
+ * Passed through to `toolbarFetch`. Use `'use-as-provided'` for pagination URLs that
+ * come from a response body (they are pinned to the uiHost/apiHost origin). Defaults
+ * to `'full'`.
+ */
+ urlConstruction?: 'full' | 'use-as-provided'
+}
+
+/** Pull a human-readable message out of a (possibly DRF) error body. */
+export function extractErrorDetail(body: unknown, status: number, fallback: string): string {
+ if (status === 401 || status === 403) {
+ return 'Your toolbar session lacks permission. Please re-authenticate the toolbar from PostHog.'
+ }
+ if (body && typeof body === 'object') {
+ const obj = body as Record<string, unknown>
+ if (typeof obj.detail === 'string' && obj.detail) {
+ return obj.detail
+ }
+ // Surface DRF field-level errors: { name: ["..."], questions: [...] }.
+ const fieldMessages: string[] = []
+ for (const [key, value] of Object.entries(obj)) {
+ if (Array.isArray(value) && value.length > 0 && typeof value[0] === 'string') {
+ fieldMessages.push(`${key}: ${value[0]}`)
+ } else if (typeof value === 'string') {
+ fieldMessages.push(`${key}: ${value}`)
+ }
+ }
+ if (fieldMessages.length > 0) {
+ return fieldMessages.join('; ')
+ }
+ }
+ return fallback
+}
+
+function pathnameForLog(url: string): string {
+ try {
+ // url may be a path ("/api/…") or an absolute pagination URL — both parse against a base.
+ return new URL(url, 'http://x').pathname
+ } catch {
+ return url
+ }
+}
+
+function emitToast(toastOnError: boolean | string, error: ToolbarApiErrorInfo): void {
+ if (!toastOnError) {
+ return
+ }
+ const fallback = typeof toastOnError === 'string' ? toastOnError : error.detail
+ lemonToast.error(extractErrorDetail(error.body, error.status, fallback))
+}
+
+async function request<T>(
+ method: ToolbarApiMethod,
+ url: string,
+ payload: Record<string, any> | FormData | undefined,
+ options: ToolbarApiOptions
+): Promise<ToolbarApiResult<T>> {
+ const {
+ context,
+ toastOnError = false,
+ reauthenticateOnForbidden = false,
+ captureOnError = true,
+ urlConstruction = 'full',
+ } = options
+ const pathname = pathnameForLog(url)
+
+ let response: Response
+ try {
+ response = await toolbarFetch(url, method, payload, urlConstruction)
+ } catch (e) {
+ const error: ToolbarApiErrorInfo = {
+ status: 0,
+ detail: 'Network error',
+ body: null,
+ isAuthError: false,
+ isNetworkError: true,
+ }
+ toolbarLogger.error('api', `Request failed (network): ${context}`, { context, method, pathname })
+ if (captureOnError) {
+ captureToolbarException(e, context, { reason: 'network' })
+ }
+ emitToast(toastOnError, error)
+ return { ok: false, status: 0, data: null, error }
+ }
+
+ const status = response.status
+
+ if (response.ok) {
+ // DELETE responses are typically 204/empty — don't try to parse a body we won't use.
+ if (method === 'DELETE') {
+ return { ok: true, status, data: null as T }
+ }
+ try {
+ const data = (await response.json()) as T
+ return { ok: true, status, data }
+ } catch (e) {
+ const error: ToolbarApiErrorInfo = {
+ status,
+ detail: 'The server returned a malformed response.',
+ body: null,
+ isAuthError: false,
+ isNetworkError: false,
+ }
+ toolbarLogger.error('api', `Response was not valid JSON: ${context}`, { context, method, pathname, status })
+ if (captureOnError) {
+ captureToolbarException(e, context, { reason: 'invalid_json', status })
+ }
+ emitToast(toastOnError, error)
+ return { ok: false, status, data: null, error }
+ }
+ }
+
+ const body = await response.json().catch(() => null)
+ const isAuthError = status === 401 || status === 403
+ const isServerError = status >= 500
+ const error: ToolbarApiErrorInfo = {
+ status,
+ detail: extractErrorDetail(body, status, 'Request failed'),
+ body,
+ isAuthError,
+ isNetworkError: false,
+ }
+
+ if (status === 403 && reauthenticateOnForbidden) {
+ toolbarConfigLogic.actions.authenticate()
+ }
+
+ // Server errors are unexpected and worth an exception; auth and other client errors
+ // are expected outcomes (stale session, validation) — log them but don't report.
+ if (isServerError) {
+ toolbarLogger.error('api', `Request failed (server): ${context}`, { context, method, pathname, status })
+ if (captureOnError) {
+ captureToolbarException(new Error(`${context}: HTTP ${status}`), context, { status })
+ }
+ } else {
+ toolbarLogger.warn('api', `Request failed: ${context}`, { context, method, pathname, status })
+ }
+
+ emitToast(toastOnError, error)
+ return { ok: false, status, data: null, error }
+}
+
+function apiGet<T = unknown>(url: string, options: ToolbarApiOptions): Promise<ToolbarApiResult<T>> {
+ return request<T>('GET', url, undefined, options)
+}
+function apiPost<T = unknown>(
+ url: string,
+ payload: Record<string, any> | FormData | undefined,
+ options: ToolbarApiOptions
+): Promise<ToolbarApiResult<T>> {
+ return request<T>('POST', url, payload, options)
+}
+function apiPatch<T = unknown>(
+ url: string,
+ payload: Record<string, any> | FormData | undefined,
+ options: ToolbarApiOptions
+): Promise<ToolbarApiResult<T>> {
+ return request<T>('PATCH', url, payload, options)
+}
+function apiDelete<T = unknown>(url: string, options: ToolbarApiOptions): Promise<ToolbarApiResult<T>> {
+ return request<T>('DELETE', url, undefined, options)
+}
+
+const PROJECT = '/api/projects/@current'
+const ENVIRONMENT = '/api/environments/@current'
+
+/**
+ * `toolbarApi` is the single entry point for talking to the PostHog API from the toolbar.
+ *
+ * Prefer the resource namespaces (`toolbarApi.actions.list()`, `toolbarApi.surveys.update(id, …)`):
+ * they own the route strings so every `/api/projects/@current/…` path lives in exactly one place
+ * and call sites read as intent rather than URLs. Each method takes the resource-specific arguments
+ * (id, payload, query) plus a `ToolbarApiOptions` and returns the same `ToolbarApiResult<T>`, so
+ * failure handling stays identical everywhere.
+ *
+ * The bare verb methods (`get`/`post`/`patch`/`delete`) remain as the low-level primitive that the
+ * namespaces are built on — reach for them only for a one-off route not yet modeled as a resource.
+ */
+export const toolbarApi = {
+ get: apiGet,
+ post: apiPost,
+ patch: apiPatch,
+ delete: apiDelete,
+
+ actions: {
+ list: (options: ToolbarApiOptions): Promise<ToolbarApiResult<{ results: ActionType[] }>> =>
+ apiGet(`${PROJECT}/actions/`, options),
+ create: (payload: Record<string, any>, options: ToolbarApiOptions): Promise<ToolbarApiResult<ActionType>> =>
+ apiPost(`${PROJECT}/actions/`, payload, options),
+ update: (
+ id: number | string,
+ payload: Record<string, any>,
+ options: ToolbarApiOptions
+ ): Promise<ToolbarApiResult<ActionType>> => apiPatch(`${PROJECT}/actions/${id}/`, payload, options),
+ },
+
+ webExperiments: {
+ list: (options: ToolbarApiOptions): Promise<ToolbarApiResult<{ results: WebExperiment[] }>> =>
+ apiGet(`${PROJECT}/web_experiments/`, options),
+ create: (payload: Record<string, any>, options: ToolbarApiOptions): Promise<ToolbarApiResult<WebExperiment>> =>
+ apiPost(`${PROJECT}/web_experiments/`, payload, options),
+ update: (
+ id: number | string,
+ payload: Record<string, any>,
+ options: ToolbarApiOptions
+ ): Promise<ToolbarApiResult<WebExperiment>> => apiPatch(`${PROJECT}/web_experiments/${id}/`, payload, options),
+ },
+
+ productTours: {
+ list: (options: ToolbarApiOptions): Promise<ToolbarApiResult<{ results?: ProductTour[] } | ProductTour[]>> =>
+ apiGet(`${PROJECT}/product_tours/`, options),
+ create: (payload: Record<string, any>, options: ToolbarApiOptions): Promise<ToolbarApiResult<ProductTour>> =>
+ apiPost(`${PROJECT}/product_tours/`, payload, options),
+ updateDraft: (
+ id: number | string,
+ payload: Record<string, any>,
+ options: ToolbarApiOptions
+ ): Promise<ToolbarApiResult<ProductTour>> =>
+ apiPatch(`${PROJECT}/product_tours/${id}/draft/`, payload, options),
+ delete: (id: number | string, options: ToolbarApiOptions): Promise<ToolbarApiResult<null>> =>
+ apiDelete(`${PROJECT}/product_tours/${id}/`, options),
+ },
+
+ fieldNotes: {
+ listPending: <T = unknown>(options: ToolbarApiOptions): Promise<ToolbarApiResult<T>> =>
+ apiGet<T>(`${PROJECT}/field_notes/?field_note_status=pending`, options),
+ create: <T = unknown>(payload: Record<string, any>, options: ToolbarApiOptions): Promise<ToolbarApiResult<T>> =>
+ apiPost<T>(`${PROJECT}/field_notes/`, payload, options),
+ delete: (id: number | string, options: ToolbarApiOptions): Promise<ToolbarApiResult<null>> =>
+ apiDelete(`${PROJECT}/field_notes/${id}/`, options),
+ },
+
+ surveys: {
+ list: (
+ params: { limit: number; offset: number; search?: string },
+ options: ToolbarApiOptions
+ ): Promise<ToolbarApiResult<{ results?: Survey[]; next?: string | null }>> =>
+ apiGet(`${PROJECT}/surveys/${encodeParams({ archived: false, ...params }, '?')}`, options),
+ create: (
+ payload: Record<string, any>,
+ options: ToolbarApiOptions
+ ): Promise<ToolbarApiResult<{ id?: string }>> => apiPost(`${PROJECT}/surveys/`, payload, options),
+ update: (
+ id: number | string,
+ payload: Record<string, any>,
+ options: ToolbarApiOptions
+ ): Promise<ToolbarApiResult<{ id?: string }>> => apiPatch(`${PROJECT}/surveys/${id}/`, payload, options),
+ },
+
+ featureFlags: {
+ myFlags: (
+ params: Record<string, any>,
+ options: ToolbarApiOptions
+ ): Promise<ToolbarApiResult<CombinedFeatureFlagAndValueType[]>> =>
+ apiGet(`${PROJECT}/feature_flags/my_flags${encodeParams(params, '?')}`, options),
+ evaluationReasons: <T = unknown>(
+ distinctId: string,
+ options: ToolbarApiOptions
+ ): Promise<ToolbarApiResult<T>> =>
+ apiGet<T>(
+ `${PROJECT}/feature_flags/evaluation_reasons${encodeParams({ distinct_id: distinctId }, '?')}`,
+ options
+ ),
+ },
+
+ webVitals: {
+ get: <T = unknown>(params: { pathname: string }, options: ToolbarApiOptions): Promise<ToolbarApiResult<T>> =>
+ apiGet<T>(`${ENVIRONMENT}/web_vitals${encodeParams(params, '?')}`, options),
+ },
+
+ eventDefinitions: {
+ search: (
+ query: string,
+ options: ToolbarApiOptions
+ ): Promise<ToolbarApiResult<{ results?: EventDefinition[] }>> =>
+ apiGet(
+ `${PROJECT}/event_definitions/${encodeParams(
+ { search: query, limit: 20, event_type: 'event_custom' },
+ '?'
+ )}`,
+ options
+ ),
+ },
+
+ objectMediaPreviews: {
+ create: (payload: Record<string, any>, options: ToolbarApiOptions): Promise<ToolbarApiResult<unknown>> =>
+ apiPost(`${PROJECT}/object_media_previews/`, payload, options),
+ },
+
+ elementStats: {
+ list: (
+ params: Record<string, any>,
+ options: ToolbarApiOptions
+ ): Promise<ToolbarApiResult<PaginatedResponse<ElementsEventType>>> =>
+ apiGet(`/api/element/stats/${encodeParams(params, '?')}`, options),
+ // Pagination URLs come from a response body — pinned to the uiHost/apiHost origin.
+ page: (
+ url: string,
+ options: ToolbarApiOptions
+ ): Promise<ToolbarApiResult<PaginatedResponse<ElementsEventType>>> =>
+ apiGet(url, { ...options, urlConstruction: 'use-as-provided' }),
+ },
+}
diff --git a/frontend/src/toolbar/toolbarConfigLogic.test.ts b/frontend/src/toolbar/toolbarConfigLogic.test.ts
index 658a9012b5ce..ed301861b9cd 100644
--- a/frontend/src/toolbar/toolbarConfigLogic.test.ts
+++ b/frontend/src/toolbar/toolbarConfigLogic.test.ts
@@ -1,13 +1,8 @@
import { expectLogic } from 'kea-test-utils'
import { initKeaTests } from '~/test/init'
-import {
- canonicalizeApiHost,
- canonicalizeUiHost,
- toolbarConfigLogic,
- toolbarFetch,
- toolbarUploadMedia,
-} from '~/toolbar/toolbarConfigLogic'
+import { canonicalizeApiHost, canonicalizeUiHost, toolbarConfigLogic } from '~/toolbar/toolbarConfigLogic'
+import { toolbarFetch, toolbarUploadMedia } from '~/toolbar/toolbarFetch'
import { cleanToolbarAuthHash, OAUTH_LOCALSTORAGE_KEY, PKCE_STORAGE_KEY, readToolbarAuthHash } from '~/toolbar/utils'
// The toolbar calls `global.fetch` directly (not the app api client / MSW). Reassign the mock per
diff --git a/frontend/src/toolbar/toolbarConfigLogic.ts b/frontend/src/toolbar/toolbarConfigLogic.ts
index c88d8b497ee1..ce34be65ac71 100644
--- a/frontend/src/toolbar/toolbarConfigLogic.ts
+++ b/frontend/src/toolbar/toolbarConfigLogic.ts
@@ -1,5 +1,4 @@
import { actions, afterMount, beforeUnmount, kea, listeners, path, props, reducers, selectors } from 'kea'
-import { combineUrl, encodeParams } from 'kea-router'
import { lemonToast } from 'lib/lemon-ui/LemonToast/LemonToast'
@@ -7,7 +6,6 @@ import { toolbarLogger } from '~/toolbar/toolbarLogger'
import { captureToolbarException, toolbarPosthogJS } from '~/toolbar/toolbarPosthogJS'
import { TOOLBAR_USER_INTENTS, ToolbarProps, ToolbarUserIntent } from '~/types'
-import { withTokenRefresh } from './toolbarAuth'
import type { toolbarConfigLogicType } from './toolbarConfigLogicType'
import {
asNonEmptyString,
@@ -17,7 +15,6 @@ import {
OAUTH_LOCALSTORAGE_KEY,
PKCE_STORAGE_KEY,
readToolbarAuthHash,
- safeFetch,
} from './utils'
export type ApiHostSource = 'posthog_api_host' | 'api_url' | 'fallback_rejected' | 'fallback_absent'
@@ -782,160 +779,3 @@ async function exchangeCodeForTokens(
actions.setAuthStatus('idle')
}
}
-
-export async function toolbarFetch(
- url: string,
- method: string = 'GET',
- payload?: Record<string, any> | FormData,
- /*
- allows caller to control how the provided URL is altered before use
- if "full" then the payload and URL are taken apart and reconstructed
- if "use-as-provided" then the URL is used as-is, and the payload is not used
- this is because the heatmapLogic needs more control over how the query parameters are constructed
- */
- urlConstruction: 'full' | 'use-as-provided' = 'full'
-): Promise<Response> {
- const logic = toolbarConfigLogic.findMounted()
- const accessToken = logic?.values.accessToken
- const host = logic?.values.uiHost
-
- if (!accessToken) {
- return new Response(JSON.stringify({ results: [] }), { status: 401 })
- }
-
- let fullUrl: string
- if (urlConstruction === 'use-as-provided') {
- // Pagination URLs come from response bodies — pin to uiHost (or apiHost, which
- // is where Django's build_absolute_uri() sources its host) so they cannot
- // redirect the Authorization header off-origin. Stub body matches the 401
- // shape above so paginating callers fail gracefully on `results: []`.
- const apiHost = logic?.values.apiHost
- const allowedOrigins = [host, apiHost].filter(Boolean).map((h) => {
- try {
- return new URL(h as string).origin
- } catch {
- return null
- }
- })
- if (allowedOrigins.length === 0) {
- return new Response(JSON.stringify({ results: [], detail: 'no_uihost' }), { status: 400 })
- }
- let got: string
- try {
- got = new URL(url).origin
- } catch {
- return new Response(JSON.stringify({ results: [], detail: 'invalid_url' }), { status: 400 })
- }
- if (!allowedOrigins.includes(got)) {
- toolbarLogger.warn('fetch', 'use-as-provided URL origin not in allowlist', {
- allowed: allowedOrigins,
- got,
- })
- return new Response(JSON.stringify({ results: [], detail: 'origin_mismatch' }), { status: 400 })
- }
- fullUrl = url
- } else {
- const { pathname, searchParams } = combineUrl(url)
- fullUrl = `${host}${pathname}${encodeParams(searchParams, '?')}`
- }
-
- const isFormData = typeof FormData !== 'undefined' && payload instanceof FormData
- const buildHeaders = (token: string): Record<string, string> => {
- const headers: Record<string, string> = { Authorization: `Bearer ${token}` }
- // Don't set Content-Type for FormData: the browser supplies it with a
- // multipart boundary. Setting it manually would corrupt the body.
- if (payload && !isFormData) {
- headers['Content-Type'] = 'application/json'
- }
- return headers
- }
- // `withTokenRefresh` may replay the same request once with a new token. We intentionally
- // reuse the same FormData instance here: FormData is re-readable (unlike one-shot streams),
- // so both the initial send and the retry can consume it safely.
- const body: BodyInit | undefined = payload
- ? isFormData
- ? (payload as FormData)
- : JSON.stringify(payload)
- : undefined
-
- const startTime = performance.now()
- let didRetry = false
-
- let response = await safeFetch(fullUrl, {
- method,
- headers: buildHeaders(accessToken),
- ...(body !== undefined ? { body } : {}),
- })
-
- response = await withTokenRefresh(response, async (newAccessToken) => {
- didRetry = true
- return await safeFetch(fullUrl, {
- method,
- headers: buildHeaders(newAccessToken),
- ...(body !== undefined ? { body } : {}),
- })
- })
-
- const durationMs = Math.round(performance.now() - startTime)
- const { pathname } = combineUrl(url)
-
- toolbarPosthogJS.capture('toolbar api request', {
- method,
- pathname,
- status: response.status,
- duration_ms: durationMs,
- did_token_retry: didRetry,
- })
-
- if (response.status === 403) {
- // The toolbar can't distinguish "token lost access" from "user switched projects" —
- // both are project-level access failures. Clear tokens and let the user re-auth
- // rather than auto-redirecting to /toolbar_oauth/authorize/ (which would use the
- // session's current team, potentially causing a "Domain not authorized" loop).
- toolbarConfigLogic.actions.tokenExpired()
- }
- return response
-}
-
-export interface ToolbarMediaUploadResponse {
- id: string
- image_location: string
- name: string
-}
-
-/** Upload media (images) from the toolbar. */
-export async function toolbarUploadMedia(file: File): Promise<{ id: string; url: string; fileName: string }> {
- // Fail fast when there's no session to begin with — don't route through
- // toolbarFetch (which would return a stub 401 and trip tokenExpired
- // telemetry / toasts for a user who was never authenticated).
- if (!toolbarConfigLogic.findMounted()?.values.accessToken) {
- throw new Error('Toolbar not authenticated')
- }
-
- // Route through toolbarFetch so authenticated uploads share the single
- // auth + token-refresh implementation. toolbarFetch sends the bearer to
- // uiHost (validated + token-bound), closing the apiHost-redirect leak.
- const formData = new FormData()
- formData.append('image', file)
-
- const response = await toolbarFetch('/api/projects/@current/uploaded_media/', 'POST', formData)
-
- if (response.status === 401) {
- // Session was valid at start but expired and refresh failed.
- toolbarConfigLogic.findMounted()?.actions.tokenExpired()
- throw new Error('Authentication expired')
- }
-
- if (!response.ok) {
- const errorData = await response.json().catch(() => ({}))
- // toolbarFetch already calls tokenExpired() on 403, so no need to repeat it here.
- throw new Error(errorData.detail || `Upload failed: ${response.status}`)
- }
-
- const data: ToolbarMediaUploadResponse = await response.json()
- return {
- id: data.id,
- url: data.image_location,
- fileName: data.name,
- }
-}
diff --git a/frontend/src/toolbar/toolbarFetch.ts b/frontend/src/toolbar/toolbarFetch.ts
new file mode 100644
index 000000000000..94d9a5f4c3ef
--- /dev/null
+++ b/frontend/src/toolbar/toolbarFetch.ts
@@ -0,0 +1,179 @@
+import { combineUrl, encodeParams } from 'kea-router'
+
+import { toolbarLogger } from '~/toolbar/toolbarLogger'
+import { toolbarPosthogJS } from '~/toolbar/toolbarPosthogJS'
+
+import { withTokenRefresh } from './toolbarAuth'
+import { toolbarConfigLogic } from './toolbarConfigLogic'
+import { safeFetch } from './utils'
+
+/**
+ * Low-level authenticated transport for the toolbar — the single place that knows how
+ * to attach the OAuth bearer, refresh it on 401, clear the session on 403, and emit
+ * per-request telemetry. It returns a raw `Response`.
+ *
+ * Prefer `toolbarApi` (`get`/`post`/`patch`/`delete`) for data requests: it builds on
+ * this primitive and adds consistent failure handling, observability, and opt-in toasts.
+ * Reach for `toolbarFetch` directly only when you genuinely need the raw `Response` and
+ * cannot use `toolbarApi` — currently the dual-context shared logics (`heatmapDataLogic`,
+ * `hedgehogModeLogic`) that interleave authenticated toolbar requests with unauthenticated
+ * `fetch` and share one response-handling branch across both. Keeping this module free of
+ * `lemonToast` (and therefore out of `toolbarApi`'s import graph) also lets those widely
+ * imported logics depend on the transport without pulling the toast layer into test setup.
+ */
+export async function toolbarFetch(
+ url: string,
+ method: string = 'GET',
+ payload?: Record<string, any> | FormData,
+ /*
+ allows caller to control how the provided URL is altered before use
+ if "full" then the payload and URL are taken apart and reconstructed
+ if "use-as-provided" then the URL is used as-is, and the payload is not used
+ this is because the heatmapLogic needs more control over how the query parameters are constructed
+ */
+ urlConstruction: 'full' | 'use-as-provided' = 'full'
+): Promise<Response> {
+ const logic = toolbarConfigLogic.findMounted()
+ const accessToken = logic?.values.accessToken
+ const host = logic?.values.uiHost
+
+ if (!accessToken) {
+ return new Response(JSON.stringify({ results: [] }), { status: 401 })
+ }
+
+ let fullUrl: string
+ if (urlConstruction === 'use-as-provided') {
+ // Pagination URLs come from response bodies — pin to uiHost (or apiHost, which
+ // is where Django's build_absolute_uri() sources its host) so they cannot
+ // redirect the Authorization header off-origin. Stub body matches the 401
+ // shape above so paginating callers fail gracefully on `results: []`.
+ const apiHost = logic?.values.apiHost
+ const allowedOrigins = [host, apiHost].filter(Boolean).map((h) => {
+ try {
+ return new URL(h as string).origin
+ } catch {
+ return null
+ }
+ })
+ if (allowedOrigins.length === 0) {
+ return new Response(JSON.stringify({ results: [], detail: 'no_uihost' }), { status: 400 })
+ }
+ let got: string
+ try {
+ got = new URL(url).origin
+ } catch {
+ return new Response(JSON.stringify({ results: [], detail: 'invalid_url' }), { status: 400 })
+ }
+ if (!allowedOrigins.includes(got)) {
+ toolbarLogger.warn('fetch', 'use-as-provided URL origin not in allowlist', {
+ allowed: allowedOrigins,
+ got,
+ })
+ return new Response(JSON.stringify({ results: [], detail: 'origin_mismatch' }), { status: 400 })
+ }
+ fullUrl = url
+ } else {
+ const { pathname, searchParams } = combineUrl(url)
+ fullUrl = `${host}${pathname}${encodeParams(searchParams, '?')}`
+ }
+
+ const isFormData = typeof FormData !== 'undefined' && payload instanceof FormData
+ const buildHeaders = (token: string): Record<string, string> => {
+ const headers: Record<string, string> = { Authorization: `Bearer ${token}` }
+ // Don't set Content-Type for FormData: the browser supplies it with a
+ // multipart boundary. Setting it manually would corrupt the body.
+ if (payload && !isFormData) {
+ headers['Content-Type'] = 'application/json'
+ }
+ return headers
+ }
+ // `withTokenRefresh` may replay the same request once with a new token. We intentionally
+ // reuse the same FormData instance here: FormData is re-readable (unlike one-shot streams),
+ // so both the initial send and the retry can consume it safely.
+ const body: BodyInit | undefined = payload
+ ? isFormData
+ ? (payload as FormData)
+ : JSON.stringify(payload)
+ : undefined
+
+ const startTime = performance.now()
+ let didRetry = false
+
+ let response = await safeFetch(fullUrl, {
+ method,
+ headers: buildHeaders(accessToken),
+ ...(body !== undefined ? { body } : {}),
+ })
+
+ response = await withTokenRefresh(response, async (newAccessToken) => {
+ didRetry = true
+ return await safeFetch(fullUrl, {
+ method,
+ headers: buildHeaders(newAccessToken),
+ ...(body !== undefined ? { body } : {}),
+ })
+ })
+
+ const durationMs = Math.round(performance.now() - startTime)
+ const { pathname } = combineUrl(url)
+
+ toolbarPosthogJS.capture('toolbar api request', {
+ method,
+ pathname,
+ status: response.status,
+ duration_ms: durationMs,
+ did_token_retry: didRetry,
+ })
+
+ if (response.status === 403) {
+ // The toolbar can't distinguish "token lost access" from "user switched projects" —
+ // both are project-level access failures. Clear tokens and let the user re-auth
+ // rather than auto-redirecting to /toolbar_oauth/authorize/ (which would use the
+ // session's current team, potentially causing a "Domain not authorized" loop).
+ toolbarConfigLogic.actions.tokenExpired()
+ }
+ return response
+}
+
+export interface ToolbarMediaUploadResponse {
+ id: string
+ image_location: string
+ name: string
+}
+
+/** Upload media (images) from the toolbar. */
+export async function toolbarUploadMedia(file: File): Promise<{ id: string; url: string; fileName: string }> {
+ // Fail fast when there's no session to begin with — don't route through
+ // toolbarFetch (which would return a stub 401 and trip tokenExpired
+ // telemetry / toasts for a user who was never authenticated).
+ if (!toolbarConfigLogic.findMounted()?.values.accessToken) {
+ throw new Error('Toolbar not authenticated')
+ }
+
+ // Route through toolbarFetch so authenticated uploads share the single
+ // auth + token-refresh implementation. toolbarFetch sends the bearer to
+ // uiHost (validated + token-bound), closing the apiHost-redirect leak.
+ const formData = new FormData()
+ formData.append('image', file)
+
+ const response = await toolbarFetch('/api/projects/@current/uploaded_media/', 'POST', formData)
+
+ if (response.status === 401) {
+ // Session was valid at start but expired and refresh failed.
+ toolbarConfigLogic.findMounted()?.actions.tokenExpired()
+ throw new Error('Authentication expired')
+ }
+
+ if (!response.ok) {
+ const errorData = await response.json().catch(() => ({}))
+ // toolbarFetch already calls tokenExpired() on 403, so no need to repeat it here.
+ throw new Error(errorData.detail || `Upload failed: ${response.status}`)
+ }
+
+ const data: ToolbarMediaUploadResponse = await response.json()
+ return {
+ id: data.id,
+ url: data.image_location,
+ fileName: data.name,
+ }
+}
diff --git a/frontend/src/toolbar/utils/screenshot.ts b/frontend/src/toolbar/utils/screenshot.ts
index 3947a1116d9a..259180d3a09b 100644
--- a/frontend/src/toolbar/utils/screenshot.ts
+++ b/frontend/src/toolbar/utils/screenshot.ts
@@ -1,6 +1,6 @@
import { toBlob } from 'html-to-image'
-import { toolbarUploadMedia } from '~/toolbar/toolbarConfigLogic'
+import { toolbarUploadMedia } from '~/toolbar/toolbarFetch'
import { TOOLBAR_ID } from '~/toolbar/utils'
export interface ElementScreenshot {
diff --git a/frontend/src/toolbar/web-vitals/webVitalsToolbarLogic.ts b/frontend/src/toolbar/web-vitals/webVitalsToolbarLogic.ts
index 55224b6ca7d2..b6ab6766cde1 100644
--- a/frontend/src/toolbar/web-vitals/webVitalsToolbarLogic.ts
+++ b/frontend/src/toolbar/web-vitals/webVitalsToolbarLogic.ts
@@ -1,12 +1,13 @@
import { actions, afterMount, connect, kea, path, reducers } from 'kea'
import { loaders } from 'kea-loaders'
-import { encodeParams, router, urlToAction } from 'kea-router'
+import { router, urlToAction } from 'kea-router'
import { inStorybook, inStorybookTestRunner } from 'lib/utils/dom'
import { permanentlyMount } from 'lib/utils/kea-logic-builders'
import { WebVitalsMetric } from '~/queries/schema/schema-general'
-import { toolbarConfigLogic, toolbarFetch } from '~/toolbar/toolbarConfigLogic'
+import { toolbarApi } from '~/toolbar/toolbarApi'
+import { toolbarConfigLogic } from '~/toolbar/toolbarConfigLogic'
import type { webVitalsToolbarLogicType } from './webVitalsToolbarLogicType'
@@ -69,27 +70,18 @@ export const webVitalsToolbarLogic = kea<webVitalsToolbarLogicType>([
return { LCP: null, FCP: null, CLS: null, INP: null } as WebVitalsMetrics
}
- const params = { pathname: window.location.pathname }
-
- let response: Response
- try {
- response = await toolbarFetch(
- `/api/environments/@current/web_vitals${encodeParams(params, '?')}`
- )
- } catch {
- // Network-level failures (origin unreachable, CORS, aborted) throw a TypeError.
- // Degrade the same way we do for a non-OK response — the UI already handles null metrics.
- return { LCP: null, FCP: null, CLS: null, INP: null } as WebVitalsMetrics
- }
+ const result = await toolbarApi.webVitals.get<WebVitalsMetricsResponse>(
+ { pathname: window.location.pathname },
+ { context: 'load_web_vitals' }
+ )
breakpoint()
- if (!response.ok) {
+ // The UI already handles null metrics — any failure degrades to "no data".
+ if (!result.ok) {
return { LCP: null, FCP: null, CLS: null, INP: null } as WebVitalsMetrics
}
- const json = (await response.json()) as WebVitalsMetricsResponse
- breakpoint()
-
+ const json = result.data
return {
LCP: json.results.find((result) => result.action.custom_name === 'LCP')?.data[1] ?? null,
FCP: json.results.find((result) => result.action.custom_name === 'FCP')?.data[1] ?? null,