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.

feat(shared-views): reintroduce 401 skipping + exporter bundle split, with playwright coverage (#57853)

Paul D'Ambra8e0b514a4284
diff --git a/common/esbuilder/utils.mjs b/common/esbuilder/utils.mjs
index 33905012ecbf..b1c5ee622175 100644
--- a/common/esbuilder/utils.mjs
+++ b/common/esbuilder/utils.mjs
@@ -279,7 +279,8 @@ function getChunks(result) {
(i) => i.kind === 'import-statement' && i.path.startsWith('dist/chunk-')
)
const exports = output.exports.filter((e) => e !== 'default' && e !== 'scene')
- if (importStatements.length > 0 && (exports.length > 0 || output.entryPoint === 'src/index.tsx')) {
+ const isRootEntry = output.entryPoint === 'src/index.tsx' || output.entryPoint === 'src/exporter/index.tsx'
+ if (importStatements.length > 0 && (exports.length > 0 || isRootEntry)) {
chunks[exports[0] || 'index'] = importStatements.map((i) =>
i.path.replace('dist/chunk-', '').replace('.js', '')
)
@@ -356,10 +357,52 @@ export async function buildInParallel(configs, { onBuildStart, onBuildComplete }
/** Get the main ".js" and ".css" files for a build */
function getBuiltEntryPoints(config, result) {
+ // Normalise entryPoints: support both array form and object form { name: path }
+ const entryValues = Array.isArray(config.entryPoints) ? config.entryPoints : Object.values(config.entryPoints || {})
+
+ // Primary: scan the metafile directly — works regardless of entryNames overrides.
+ // CSS outputs never have entryPoint set, so we find JS entries first, then locate
+ // each companion CSS by matching the same base name (hashes differ between JS and CSS).
+ const jsFiles = []
+ for (const [outputPath, output] of Object.entries(result.metafile?.outputs || {})) {
+ if (output.entryPoint && entryValues.includes(output.entryPoint) && outputPath.endsWith('.js')) {
+ jsFiles.push(path.resolve(process.cwd(), outputPath))
+ }
+ }
+ if (jsFiles.length > 0) {
+ const allFiles = [...jsFiles]
+ const allOutputPaths = Object.keys(result.metafile?.outputs || {})
+ // Pair each entry JS with its companion CSS by stripping the optional
+ // "-<hash>" suffix. The hash matcher excludes `-` so that a sibling
+ // entry sharing a prefix can't have its CSS stolen — e.g. an `exporter`
+ // entry must not match `dist/exporter-extra-HASH.css` (the `-extra-HASH`
+ // segment contains a `-`, which fails the single-segment match).
+ // esbuild's default hash is base32 (uppercase + digits, no hyphens) so
+ // the constraint is compatible with default builds and allows mixed-
+ // case alphabets too.
+ const hashSuffixPattern = /(-[^./-]+)?\.js$/
+ for (const jsFile of jsFiles) {
+ const baseName = jsFile.replace(hashSuffixPattern, '')
+ const escapedBase = baseName.replace(/[.*+?^${}()|[\]\\]/g, '\\$&')
+ const expectedCss = new RegExp(`^${escapedBase}(-[^./-]+)?\\.css$`)
+ for (const outputPath of allOutputPaths) {
+ if (!outputPath.endsWith('.css')) {
+ continue
+ }
+ const absoluteCss = path.resolve(process.cwd(), outputPath)
+ if (expectedCss.test(absoluteCss)) {
+ allFiles.push(absoluteCss)
+ }
+ }
+ }
+ return allFiles
+ }
+
+ // Fallback: path-based convention for configs where metafile scan yields nothing
let outfiles = []
if (config.outdir) {
// convert "src/index.tsx" --> /a/posthog/frontend/dist/index.js
- outfiles = config.entryPoints.map((file) =>
+ outfiles = entryValues.map((file) =>
path
.resolve(config.absWorkingDir, file)
.replace('/src/', '/dist/')
@@ -369,24 +412,21 @@ function getBuiltEntryPoints(config, result) {
outfiles = [path.resolve(config.absWorkingDir, config.outfile)]
}
- const builtFiles = []
+ const fallbackFiles = []
for (const outfile of outfiles) {
- // convert "/a/something.tsx" --> "/a/something-"
const fileNoExt = outfile.replace(/\.[^/]+$/, '')
- // find if we built a .js or .css file that matches
- for (const file of Object.keys(result.metafile.outputs)) {
+ for (const file of Object.keys(result.metafile?.outputs || {})) {
const absoluteFile = path.resolve(process.cwd(), file)
if (
(absoluteFile.startsWith(`${fileNoExt}-`) && (file.endsWith('.js') || file.endsWith('.css'))) ||
absoluteFile === `${fileNoExt}.js` ||
absoluteFile === `${fileNoExt}.css`
) {
- builtFiles.push(absoluteFile)
+ fallbackFiles.push(absoluteFile)
}
}
}
-
- return builtFiles
+ return fallbackFiles
}
let buildsInProgress = 0
diff --git a/frontend/build.mjs b/frontend/build.mjs
index e44edbcb79aa..cd15e130b800 100755
--- a/frontend/build.mjs
+++ b/frontend/build.mjs
@@ -79,10 +79,10 @@ await buildInParallel(
},
{
name: 'Exporter',
- globalName: 'posthogExporter',
- entryPoints: ['src/exporter/index.tsx'],
- format: 'iife',
- outfile: path.resolve(__dirname, 'dist', 'exporter.js'),
+ entryPoints: { exporter: 'src/exporter/index.tsx' },
+ splitting: true,
+ format: 'esm',
+ outdir: path.resolve(__dirname, 'dist'),
...common,
},
{
diff --git a/frontend/src/exporter/Exporter.tsx b/frontend/src/exporter/Exporter.tsx
index efede9ef06cb..ae5cde1786bf 100644
--- a/frontend/src/exporter/Exporter.tsx
+++ b/frontend/src/exporter/Exporter.tsx
@@ -3,35 +3,28 @@ import './Exporter.scss'
import clsx from 'clsx'
import { BindLogic, useValues } from 'kea'
-import { useCallback, useEffect } from 'react'
+import { lazy, Suspense, useEffect } from 'react'
import { Logo } from 'lib/brand/Logo'
-import { HeatmapCanvas } from 'lib/components/heatmaps/HeatmapCanvas'
-import { usePageVisibilityCb } from 'lib/hooks/usePageVisibility'
import { useResizeObserver } from 'lib/hooks/useResizeObserver'
import { useThemedHtml } from 'lib/hooks/useThemedHtml'
import { LemonMarkdown } from 'lib/lemon-ui/LemonMarkdown'
import { Link } from 'lib/lemon-ui/Link'
import { humanFriendlyDuration } from 'lib/utils'
-import { Dashboard } from 'scenes/dashboard/Dashboard'
-import { dashboardLogic } from 'scenes/dashboard/dashboardLogic'
-import { Notebook } from 'scenes/notebooks/Notebook/Notebook'
-import { SessionRecordingPlayer } from 'scenes/session-recordings/player/SessionRecordingPlayer'
-import { SessionRecordingPlayerMode } from 'scenes/session-recordings/player/sessionRecordingPlayerLogic'
+import { AUTO_REFRESH_INITIAL_INTERVAL_SECONDS } from 'scenes/dashboard/dashboardConstants'
import { teamLogic } from 'scenes/teamLogic'
-import { ExportedInsight } from '~/exporter/ExportedInsight/ExportedInsight'
import { ExporterLogin } from '~/exporter/ExporterLogin'
import { ExportType, ExportedData } from '~/exporter/types'
-import { getQueryBasedDashboard } from '~/queries/nodes/InsightViz/utils'
-import {
- AUTO_REFRESH_INITIAL_INTERVAL_SECONDS,
- scheduleSharedDashboardStaleAutoForceIfEligible,
-} from '~/scenes/dashboard/dashboardUtils'
-import { DashboardPlacement } from '~/types'
import { exporterViewLogic } from './exporterViewLogic'
+const LazyDashboardScene = lazy(() => import('./scenes/ExporterDashboardScene'))
+const LazyHeatmapScene = lazy(() => import('./scenes/ExporterHeatmapScene'))
+const LazyInsightScene = lazy(() => import('./scenes/ExporterInsightScene'))
+const LazyNotebookScene = lazy(() => import('./scenes/ExporterNotebookScene'))
+const LazyRecordingScene = lazy(() => import('./scenes/ExporterRecordingScene'))
+
function resolveForcedTheme(theme?: 'light' | 'dark' | 'system'): 'light' | 'dark' | null {
if (theme === 'light' || theme === 'dark') {
return theme
@@ -44,89 +37,7 @@ function resolveForcedTheme(theme?: 'light' | 'dark' | 'system'): 'light' | 'dar
: 'light'
}
-function ExportHeatmap(): JSX.Element {
- const { exportedData, isLoading, screenshotUrl } = useValues(exporterViewLogic)
- const { exportToken } = exportedData
- const width = exportedData.heatmap_context?.width
-
- return (
- <div
- className="heatmap-exporter relative"
- // eslint-disable-next-line react/forbid-dom-props
- style={{
- width: width ? `${width}px` : '100%',
- minHeight: '100vh',
- overflow: 'hidden',
- }}
- >
- <HeatmapCanvas
- positioning="absolute"
- widthOverride={width ?? null}
- context="in-app"
- exportToken={exportToken}
- />
- {exportedData.heatmap_context?.heatmap_type === 'screenshot' ? (
- isLoading ? null : (
- <img
- src={screenshotUrl ?? ''}
- alt="Heatmap"
- // eslint-disable-next-line react/forbid-dom-props
- style={{ width: '100%', height: 'auto', display: 'block' }}
- />
- )
- ) : (
- <iframe
- id="heatmap-iframe"
- ref={null}
- title="Heatmap export"
- className="bg-white"
- // eslint-disable-next-line react/forbid-dom-props
- style={{ width: '100%', height: '100vh', display: 'block' }}
- src={exportedData.heatmap_url ?? ''}
- onLoad={() => {}}
- // these two sandbox values are necessary so that the site and toolbar can run
- // this is a very loose sandbox,
- // but we specify it so that at least other capabilities are denied
- sandbox="allow-scripts allow-same-origin"
- // we don't allow things such as camera access though
- allow=""
- />
- )}
- </div>
- )
-}
-
-function SharedDashboardAutoRefresh({ dashboardId }: { dashboardId: number }): JSX.Element | null {
- const logic = dashboardLogic({ id: dashboardId, placement: DashboardPlacement.Public })
- const { setAutoRefresh, setPageVisibility, triggerDashboardRefresh } = logic.actions
-
- // Tie auto-refresh to tab visibility AND fire a one-shot staleness check when the tab
- // regains focus — Chrome throttles background timers, so the periodic interval can drift
- // well past the staleness budget before the next tick. Reading `logic.values` inside the
- // callback gets the live `effectiveLastRefresh` rather than a stale closure value.
- const onVisibilityChange = useCallback(
- (visible: boolean) => {
- setPageVisibility(visible)
- if (visible) {
- scheduleSharedDashboardStaleAutoForceIfEligible({
- effectiveLastRefresh: logic.values.effectiveLastRefresh,
- triggerDashboardRefresh: () => void triggerDashboardRefresh(),
- })
- }
- },
- [setPageVisibility, triggerDashboardRefresh, logic]
- )
- usePageVisibilityCb(onVisibilityChange)
-
- useEffect(() => {
- setAutoRefresh(true, AUTO_REFRESH_INITIAL_INTERVAL_SECONDS)
- }, [setAutoRefresh])
-
- return null
-}
-
export function Exporter(props: ExportedData): JSX.Element {
- // NOTE: Mounting the logic is important as it is used by sub-logics
const {
type,
dashboard,
@@ -238,40 +149,37 @@ export function Exporter(props: ExportedData): JSX.Element {
</div>
</div>
)}
- <Notebook
- shortId={notebook.short_id}
- editable={false}
- cachedNotebook={notebook}
- cachedInsightsByShortId={insights}
- cachedInlineQueryResultsByNodeId={inlineQueryResults}
- />
+ <Suspense fallback={null}>
+ <LazyNotebookScene
+ notebook={notebook}
+ insights={insights}
+ inline_query_results={inlineQueryResults}
+ />
+ </Suspense>
</div>
) : insight ? (
- <ExportedInsight insight={insight} themes={themes!} exportOptions={exportOptions} />
+ <Suspense fallback={null}>
+ <LazyInsightScene insight={insight} themes={themes!} exportOptions={exportOptions} />
+ </Suspense>
) : dashboard ? (
- <>
- {type !== ExportType.Image && <SharedDashboardAutoRefresh dashboardId={dashboard.id} />}
- <Dashboard
- id={String(dashboard.id)}
- dashboard={getQueryBasedDashboard(dashboard)!}
- placement={
- type === ExportType.Image ? DashboardPlacement.Export : DashboardPlacement.Public
- }
- themes={themes}
- />
- </>
+ <Suspense fallback={null}>
+ <LazyDashboardScene dashboard={dashboard} type={type} themes={themes} />
+ </Suspense>
) : recording ? (
- <SessionRecordingPlayer
- playerKey="exporter"
- sessionRecordingId={recording.id}
- mode={props.mode ?? SessionRecordingPlayerMode.Sharing}
- autoPlay={props.autoplay ?? false}
- withSidebar={showInspector}
- noBorder={props.noBorder ?? false}
- accessToken={exportToken}
- />
+ <Suspense fallback={null}>
+ <LazyRecordingScene
+ recording={recording}
+ mode={props.mode}
+ autoplay={props.autoplay}
+ noBorder={props.noBorder}
+ exportToken={exportToken}
+ showInspector={showInspector}
+ />
+ </Suspense>
) : type === ExportType.Heatmap ? (
- <ExportHeatmap />
+ <Suspense fallback={null}>
+ <LazyHeatmapScene />
+ </Suspense>
) : (
<h1 className="text-center p-4">Something went wrong...</h1>
)}
diff --git a/frontend/src/exporter/exporterViewLogic.ts b/frontend/src/exporter/exporterViewLogic.ts
index 1c9b09259210..af16e6e9ff45 100644
--- a/frontend/src/exporter/exporterViewLogic.ts
+++ b/frontend/src/exporter/exporterViewLogic.ts
@@ -103,3 +103,24 @@ export const exporterViewLogic = kea<exporterViewLogicType>([
export const getCurrentExporterData = (): ExportedData | undefined => {
return exporterViewLogic.findMounted()?.values.exportedData
}
+
+/**
+ * Synchronous check for "this bundle is rendering a shared/exported view".
+ *
+ * Reads `window.POSTHOG_EXPORTED_DATA` directly because that global is set by
+ * Django before any React code runs. Going through the kea logic (via
+ * `getCurrentExporterData`) is unreliable from inside a leaf component's
+ * `useEffect` — React fires child effects before parent ones, so the
+ * `BindLogic` wrapping `<Exporter>` may not have mounted `exporterViewLogic`
+ * yet by the time a deeply-nested gate checks. Direct global access is
+ * synchronous and there's no mount-order risk.
+ *
+ * Falls back to the kea check for non-exporter contexts (Storybook, jest)
+ * where `POSTHOG_EXPORTED_DATA` isn't injected.
+ */
+export const isSharedView = (): boolean => {
+ if (typeof window !== 'undefined' && window.POSTHOG_EXPORTED_DATA) {
+ return true
+ }
+ return !!getCurrentExporterData()
+}
diff --git a/frontend/src/exporter/scenes/ExporterDashboardScene.tsx b/frontend/src/exporter/scenes/ExporterDashboardScene.tsx
new file mode 100644
index 000000000000..ae7a20ae6aa8
--- /dev/null
+++ b/frontend/src/exporter/scenes/ExporterDashboardScene.tsx
@@ -0,0 +1,76 @@
+import { useActions } from 'kea'
+import { useCallback, useEffect, useMemo } from 'react'
+
+import { usePageVisibilityCb } from 'lib/hooks/usePageVisibility'
+import { Dashboard } from 'scenes/dashboard/Dashboard'
+import { AUTO_REFRESH_INITIAL_INTERVAL_SECONDS } from 'scenes/dashboard/dashboardConstants'
+import { dashboardLogic } from 'scenes/dashboard/dashboardLogic'
+
+import { getQueryBasedDashboard } from '~/queries/nodes/InsightViz/utils'
+import { DashboardPlacement, DashboardType, QueryBasedInsightModel } from '~/types'
+
+import { ExportType, ExportedData } from '../types'
+
+function SharedDashboardAutoRefresh({
+ dashboardId,
+ dashboard,
+}: {
+ dashboardId: number
+ dashboard: DashboardType<QueryBasedInsightModel>
+}): JSX.Element | null {
+ // Pass `dashboard` so dashboardLogic.afterMount uses the cached branch
+ // (loadDashboardSuccess) instead of firing an unauthenticated loadDashboard.
+ //
+ // CONTRACT: dashboardLogic is keyed by `id` only. This mount and the
+ // inner <Dashboard> below pass the same id, so they resolve to the same
+ // logic instance — the first mount's props win and the second is a no-op
+ // for prop initialisation. If a future refactor splits the auto-refresh
+ // off so it mounts a different keyed instance, the inner <Dashboard>
+ // would mount without `dashboard`, afterMount would call loadDashboard,
+ // and shared mode would 401. Whichever component mounts first must seed
+ // `dashboard` for the cached branch to win.
+ const logic = dashboardLogic({ id: dashboardId, placement: DashboardPlacement.Public, dashboard })
+ const { setAutoRefresh, setPageVisibility, forceRefreshIfStale } = useActions(logic)
+
+ const onVisibilityChange = useCallback(
+ (visible: boolean) => {
+ setPageVisibility(visible)
+ if (visible) {
+ forceRefreshIfStale()
+ }
+ },
+ [setPageVisibility, forceRefreshIfStale]
+ )
+ usePageVisibilityCb(onVisibilityChange)
+
+ useEffect(() => {
+ setAutoRefresh(true, AUTO_REFRESH_INITIAL_INTERVAL_SECONDS)
+ }, [setAutoRefresh])
+
+ return null
+}
+
+export default function ExporterDashboardScene({
+ dashboard,
+ type,
+ themes,
+}: {
+ dashboard: NonNullable<ExportedData['dashboard']>
+ type: ExportedData['type']
+ themes: ExportedData['themes']
+}): JSX.Element {
+ const queryBasedDashboard = useMemo(() => getQueryBasedDashboard(dashboard)!, [dashboard])
+ return (
+ <>
+ {type !== ExportType.Image && (
+ <SharedDashboardAutoRefresh dashboardId={dashboard.id} dashboard={queryBasedDashboard} />
+ )}
+ <Dashboard
+ id={String(dashboard.id)}
+ dashboard={queryBasedDashboard}
+ placement={type === ExportType.Image ? DashboardPlacement.Export : DashboardPlacement.Public}
+ themes={themes}
+ />
+ </>
+ )
+}
diff --git a/frontend/src/exporter/scenes/ExporterHeatmapScene.tsx b/frontend/src/exporter/scenes/ExporterHeatmapScene.tsx
new file mode 100644
index 000000000000..683ce532842e
--- /dev/null
+++ b/frontend/src/exporter/scenes/ExporterHeatmapScene.tsx
@@ -0,0 +1,55 @@
+import { useValues } from 'kea'
+
+import { HeatmapCanvas } from 'lib/components/heatmaps/HeatmapCanvas'
+
+import { exporterViewLogic } from '../exporterViewLogic'
+
+export default function ExporterHeatmapScene(): JSX.Element {
+ const { exportedData, isLoading, screenshotUrl } = useValues(exporterViewLogic)
+ const { exportToken } = exportedData
+ const width = exportedData.heatmap_context?.width
+
+ return (
+ <div
+ className="heatmap-exporter relative"
+ // eslint-disable-next-line react/forbid-dom-props
+ style={{
+ width: width ? `${width}px` : '100%',
+ minHeight: '100vh',
+ overflow: 'hidden',
+ }}
+ >
+ <HeatmapCanvas
+ positioning="absolute"
+ widthOverride={width ?? null}
+ context="in-app"
+ exportToken={exportToken}
+ />
+ {exportedData.heatmap_context?.heatmap_type === 'screenshot' ? (
+ isLoading ? null : (
+ <img
+ src={screenshotUrl ?? ''}
+ alt="Heatmap"
+ // eslint-disable-next-line react/forbid-dom-props
+ style={{ width: '100%', height: 'auto', display: 'block' }}
+ />
+ )
+ ) : (
+ <iframe
+ id="heatmap-iframe"
+ title="Heatmap export"
+ className="bg-white"
+ // eslint-disable-next-line react/forbid-dom-props
+ style={{ width: '100%', height: '100vh', display: 'block' }}
+ src={exportedData.heatmap_url ?? ''}
+ // these two sandbox values are necessary so that the site and toolbar can run
+ // this is a very loose sandbox,
+ // but we specify it so that at least other capabilities are denied
+ sandbox="allow-scripts allow-same-origin"
+ // we don't allow things such as camera access though
+ allow=""
+ />
+ )}
+ </div>
+ )
+}
diff --git a/frontend/src/exporter/scenes/ExporterInsightScene.tsx b/frontend/src/exporter/scenes/ExporterInsightScene.tsx
new file mode 100644
index 000000000000..e7e58c4b5ad4
--- /dev/null
+++ b/frontend/src/exporter/scenes/ExporterInsightScene.tsx
@@ -0,0 +1,16 @@
+import { ExportedInsight } from '~/exporter/ExportedInsight/ExportedInsight'
+import { SharingConfigurationSettings } from '~/queries/schema/schema-general'
+
+import { ExportedData } from '../types'
+
+export default function ExporterInsightScene({
+ insight,
+ themes,
+ exportOptions,
+}: {
+ insight: NonNullable<ExportedData['insight']>
+ themes: NonNullable<ExportedData['themes']>
+ exportOptions: SharingConfigurationSettings
+}): JSX.Element {
+ return <ExportedInsight insight={insight} themes={themes} exportOptions={exportOptions} />
+}
diff --git a/frontend/src/exporter/scenes/ExporterNotebookScene.tsx b/frontend/src/exporter/scenes/ExporterNotebookScene.tsx
new file mode 100644
index 000000000000..7d1a4acbca4d
--- /dev/null
+++ b/frontend/src/exporter/scenes/ExporterNotebookScene.tsx
@@ -0,0 +1,23 @@
+import { Notebook } from 'scenes/notebooks/Notebook/Notebook'
+
+import { ExportedData } from '../types'
+
+export default function ExporterNotebookScene({
+ notebook,
+ insights,
+ inline_query_results: inlineQueryResults,
+}: {
+ notebook: NonNullable<ExportedData['notebook']>
+ insights: ExportedData['insights']
+ inline_query_results: ExportedData['inline_query_results']
+}): JSX.Element {
+ return (
+ <Notebook
+ shortId={notebook.short_id}
+ editable={false}
+ cachedNotebook={notebook}
+ cachedInsightsByShortId={insights}
+ cachedInlineQueryResultsByNodeId={inlineQueryResults}
+ />
+ )
+}
diff --git a/frontend/src/exporter/scenes/ExporterRecordingScene.tsx b/frontend/src/exporter/scenes/ExporterRecordingScene.tsx
new file mode 100644
index 000000000000..21a2cbf35bde
--- /dev/null
+++ b/frontend/src/exporter/scenes/ExporterRecordingScene.tsx
@@ -0,0 +1,32 @@
+import { SessionRecordingPlayer } from 'scenes/session-recordings/player/SessionRecordingPlayer'
+import { SessionRecordingPlayerMode } from 'scenes/session-recordings/player/sessionRecordingPlayerLogic'
+
+import { ExportedData } from '../types'
+
+export default function ExporterRecordingScene({
+ recording,
+ mode,
+ autoplay,
+ noBorder,
+ exportToken,
+ showInspector,
+}: {
+ recording: NonNullable<ExportedData['recording']>
+ mode: ExportedData['mode']
+ autoplay: ExportedData['autoplay']
+ noBorder: ExportedData['noBorder']
+ exportToken: ExportedData['exportToken']
+ showInspector: ExportedData['showInspector']
+}): JSX.Element {
+ return (
+ <SessionRecordingPlayer
+ playerKey="exporter"
+ sessionRecordingId={recording.id}
+ mode={mode ?? SessionRecordingPlayerMode.Sharing}
+ autoPlay={autoplay ?? false}
+ withSidebar={showInspector ?? false}
+ noBorder={noBorder ?? false}
+ accessToken={exportToken}
+ />
+ )
+}
diff --git a/frontend/src/lib/api.ts b/frontend/src/lib/api.ts
index 86b4d79ec68b..9c76b3cba568 100644
--- a/frontend/src/lib/api.ts
+++ b/frontend/src/lib/api.ts
@@ -18,7 +18,7 @@ import { RecordingComment } from 'scenes/session-recordings/player/inspector/pla
import { SessionSummaryContent } from 'scenes/session-recordings/player/player-meta/types'
import { LINK_PAGE_SIZE, SURVEY_PAGE_SIZE } from 'scenes/surveys/constants'
-import { getCurrentExporterData } from '~/exporter/exporterViewLogic'
+import { getCurrentExporterData, isSharedView } from '~/exporter/exporterViewLogic'
import { OrganizationOAuthApplicationApi } from '~/generated/core/api.schemas'
import { Variable } from '~/queries/nodes/DataVisualization/types'
import {
@@ -6921,6 +6921,8 @@ const api = {
},
} as const
+const warnedSharedViewLeaks = new Set<string>()
+
async function handleFetch(url: string, method: string, fetcher: () => Promise<Response>): Promise<Response> {
const startTime = new Date().getTime()
@@ -6944,6 +6946,7 @@ async function handleFetch(url: string, method: string, fetcher: () => Promise<R
if (!response.ok) {
const duration = new Date().getTime() - startTime
const pathname = new URL(url, location.origin).pathname
+ const inSharedView = isSharedView()
// when used inside the posthog toolbar, `posthog.capture` isn't loaded
// check if the function is available before calling it.
if (posthog.capture) {
@@ -6952,8 +6955,16 @@ async function handleFetch(url: string, method: string, fetcher: () => Promise<R
method,
duration,
status: response.status,
+ is_shared_view: inSharedView,
})
}
+ if (inSharedView && (response.status === 401 || response.status === 403)) {
+ const leakKey = `${method} ${pathname}`
+ if (!warnedSharedViewLeaks.has(leakKey)) {
+ warnedSharedViewLeaks.add(leakKey)
+ console.warn(`[shared-view] unexpected ${response.status} on ${leakKey}`)
+ }
+ }
const data = await getJSONOrNull(response)
diff --git a/frontend/src/lib/components/QuickFilters/quickFiltersLogic.ts b/frontend/src/lib/components/QuickFilters/quickFiltersLogic.ts
index 9be3688de8da..ebddc5952111 100644
--- a/frontend/src/lib/components/QuickFilters/quickFiltersLogic.ts
+++ b/frontend/src/lib/components/QuickFilters/quickFiltersLogic.ts
@@ -5,6 +5,7 @@ import posthog from 'posthog-js'
import api from 'lib/api'
import { lemonToast } from 'lib/lemon-ui/LemonToast/LemonToast'
+import { isSharedView } from '~/exporter/exporterViewLogic'
import { QuickFilterContext } from '~/queries/schema/schema-general'
import { QuickFilter } from '~/types'
@@ -37,6 +38,9 @@ export const quickFiltersLogic = kea<quickFiltersLogicType>([
[] as QuickFilter[],
{
loadQuickFilters: async () => {
+ if (isSharedView()) {
+ return []
+ }
const response = await api.quickFilters.list(props.context)
return response.results
},
diff --git a/frontend/src/lib/hooks/useFileSystemLogView.ts b/frontend/src/lib/hooks/useFileSystemLogView.ts
index 00b77e93f0e1..00c4a5888ce6 100644
--- a/frontend/src/lib/hooks/useFileSystemLogView.ts
+++ b/frontend/src/lib/hooks/useFileSystemLogView.ts
@@ -2,6 +2,7 @@ import { useEffect } from 'react'
import api, { ApiConfig } from 'lib/api'
+import { isSharedView } from '~/exporter/exporterViewLogic'
import { recentItemsModel } from '~/models/recentItemsModel'
type FileSystemLogViewType =
@@ -26,7 +27,14 @@ interface TrackFileSystemLogViewOptions {
}
export function trackFileSystemLogView({ type, ref, enabled = true }: TrackFileSystemLogViewOptions): void {
- if (!enabled || window.IMPERSONATED_SESSION || ref === null || ref === undefined || !ApiConfig.hasCurrentTeamId()) {
+ if (
+ !enabled ||
+ window.IMPERSONATED_SESSION ||
+ isSharedView() ||
+ ref === null ||
+ ref === undefined ||
+ !ApiConfig.hasCurrentTeamId()
+ ) {
return
}
diff --git a/frontend/src/queries/nodes/DataVisualization/Components/Variables/variableDataLogic.ts b/frontend/src/queries/nodes/DataVisualization/Components/Variables/variableDataLogic.ts
index db511f313af1..ec531104e999 100644
--- a/frontend/src/queries/nodes/DataVisualization/Components/Variables/variableDataLogic.ts
+++ b/frontend/src/queries/nodes/DataVisualization/Components/Variables/variableDataLogic.ts
@@ -5,6 +5,8 @@ import { lemonToast } from '@posthog/lemon-ui'
import api from 'lib/api'
+import { isSharedView } from '~/exporter/exporterViewLogic'
+
import { Variable } from '../../types'
import type { variableDataLogicType } from './variableDataLogicType'
@@ -15,6 +17,9 @@ export const variableDataLogic = kea<variableDataLogicType>([
[] as Variable[],
{
loadVariables: async () => {
+ if (isSharedView()) {
+ return []
+ }
const insights = await api.insightVariables.list()
return insights.results
},
diff --git a/frontend/src/scenes/dashboard/dashboardConstants.ts b/frontend/src/scenes/dashboard/dashboardConstants.ts
new file mode 100644
index 000000000000..7c5527427b84
--- /dev/null
+++ b/frontend/src/scenes/dashboard/dashboardConstants.ts
@@ -0,0 +1,8 @@
+export const AUTO_REFRESH_INITIAL_INTERVAL_SECONDS = 1800
+
+/**
+ * Cold-start one-shot threshold: if data is older than this when a shared dashboard loads,
+ * trigger one immediate force_blocking refresh. Aligned with the periodic interval and the
+ * backend throttle (`SHARED_FORCE_BLOCKING_MIN_AGE`).
+ */
+export const SHARED_DASHBOARD_AUTO_FORCE_IF_STALE_MINUTES = AUTO_REFRESH_INITIAL_INTERVAL_SECONDS / 60
diff --git a/frontend/src/scenes/dashboard/dashboardLogic.tsx b/frontend/src/scenes/dashboard/dashboardLogic.tsx
index 97624979be38..61528f070228 100644
--- a/frontend/src/scenes/dashboard/dashboardLogic.tsx
+++ b/frontend/src/scenes/dashboard/dashboardLogic.tsx
@@ -40,6 +40,7 @@ import { Scene } from 'scenes/sceneTypes'
import { urls } from 'scenes/urls'
import { userLogic } from 'scenes/userLogic'
+import { isSharedView } from '~/exporter/exporterViewLogic'
import { SIDE_PANEL_CONTEXT_KEY, SidePanelSceneContext } from '~/layout/navigation-3000/sidepanel/types'
import { dashboardsModel } from '~/models/dashboardsModel'
import { insightsModel } from '~/models/insightsModel'
@@ -81,11 +82,11 @@ import {
import { getResponseBytes, sortDayJsDates } from '../insights/utils'
import { filterVariablesReferencedInQuery } from '../insights/utils/queryUtils'
import { teamLogic } from '../teamLogic'
+import { AUTO_REFRESH_INITIAL_INTERVAL_SECONDS } from './dashboardConstants'
import { BreakdownColorConfig } from './DashboardInsightColorsModal'
import type { dashboardLogicType } from './dashboardLogicType'
import { dashboardQuickFiltersLogic } from './dashboardQuickFiltersLogic'
import {
- AUTO_REFRESH_INITIAL_INTERVAL_SECONDS,
BREAKPOINT_COLUMN_COUNTS,
DASHBOARD_MIN_REFRESH_INTERVAL_MINUTES,
IS_TEST_MODE,
@@ -102,7 +103,7 @@ import {
parseURLFilters,
parseURLVariables,
runWithLimit,
- scheduleSharedDashboardStaleAutoForceIfEligible,
+ shouldSharedDashboardAutoForceForStaleTime,
} from './dashboardUtils'
import { TileFiltersOverride } from './TileFiltersOverride'
import { tileLogic } from './tileLogic'
@@ -217,6 +218,12 @@ export const dashboardLogic = kea<dashboardLogicType>([
triggerDashboardRefresh: (payload?: { withAnalysis?: boolean }) => ({
withAnalysis: payload?.withAnalysis ?? false,
}),
+ /**
+ * If the latest tile data is older than SHARED_DASHBOARD_AUTO_FORCE_IF_STALE_MINUTES,
+ * queue a single force-blocking refresh on the next microtask. Reads
+ * `effectiveLastRefresh` from values, so always sees the live age — no closure.
+ */
+ forceRefreshIfStale: true,
/** Manually refresh a single insight from the insight card on the dashboard. */
refreshDashboardItem: (payload: { tile: DashboardTile<QueryBasedInsightModel> }) => payload,
/** Refresh tiles of a loaded dashboard e.g. stale tiles after initial load, previewed tiles after applying filters, etc. */
@@ -1761,6 +1768,13 @@ export const dashboardLogic = kea<dashboardLogicType>([
})
},
updateTileColor: async ({ tileId, color }) => {
+ // Defense in depth: shared dashboards (DashboardPlacement.Public)
+ // shouldn't render the tile-color editor, so this listener should
+ // never fire from shared mode. Guarding here avoids a phantom
+ // optimistic local state change that reverts on the inevitable 401.
+ if (isSharedView()) {
+ return
+ }
const previousColor = values.tiles.find((tile) => tile.id === tileId)?.color
actions.setTileProperty(tileId, { color })
try {
@@ -1773,6 +1787,10 @@ export const dashboardLogic = kea<dashboardLogicType>([
}
},
toggleTileDescription: async ({ tileId }) => {
+ // Defense in depth — same reason as updateTileColor above.
+ if (isSharedView()) {
+ return
+ }
const matchingTile = values.tiles.find((tile) => tile.id === tileId)
const previousValue = matchingTile?.show_description
const newValue = previousValue === false
@@ -1918,6 +1936,26 @@ export const dashboardLogic = kea<dashboardLogicType>([
dashboardsModel.actions.updateDashboard({ id: values.dashboard.id, ...payload })
}
},
+ forceRefreshIfStale: () => {
+ // Dedupe: this listener can be invoked from multiple sources for the same
+ // freshness state — the post-load auto-trigger in refreshDashboardItems and
+ // the visibility-change callback in ExporterDashboardScene can both fire on
+ // the same render tick. Tracking the last `effectiveLastRefresh` we already
+ // forced a refresh against ensures we queue at most one trigger per
+ // freshness window. Once a refresh lands, `effectiveLastRefresh` advances
+ // and a future stale window can re-fire.
+ const currentRefreshKey = values.effectiveLastRefresh?.valueOf() ?? null
+ if (cache.lastAutoForcedFor === currentRefreshKey) {
+ return
+ }
+ if (!shouldSharedDashboardAutoForceForStaleTime(values.effectiveLastRefresh)) {
+ return
+ }
+ cache.lastAutoForcedFor = currentRefreshKey
+ queueMicrotask(() => {
+ void actions.triggerDashboardRefresh()
+ })
+ },
/** Triggered from dashboard refresh button, when user refreshes entire dashboard */
triggerDashboardRefresh: async ({ withAnalysis }, breakpoint) => {
actions.resetInterval()
@@ -2199,12 +2237,7 @@ export const dashboardLogic = kea<dashboardLogicType>([
tilesAbortedCount === 0 &&
values.placement === DashboardPlacement.Public
) {
- scheduleSharedDashboardStaleAutoForceIfEligible({
- effectiveLastRefresh: values.effectiveLastRefresh,
- triggerDashboardRefresh: () => {
- void actions.triggerDashboardRefresh()
- },
- })
+ actions.forceRefreshIfStale()
}
},
saveEditModeChanges: () => {
@@ -2366,7 +2399,7 @@ export const dashboardLogic = kea<dashboardLogicType>([
.map((insight: QueryBasedInsightModel) => insight?.id)
.filter((id): id is number => !!id)
- if (insightIds.length > 0 && values.currentTeamId) {
+ if (insightIds.length > 0 && values.currentTeamId && !isSharedView()) {
void api.create(`api/environments/${values.currentTeamId}/insights/viewed`, {
insight_ids: insightIds,
})
diff --git a/frontend/src/scenes/dashboard/dashboardUtils.test.ts b/frontend/src/scenes/dashboard/dashboardUtils.test.ts
index d0ccc08178d6..d486bf2daf5c 100644
--- a/frontend/src/scenes/dashboard/dashboardUtils.test.ts
+++ b/frontend/src/scenes/dashboard/dashboardUtils.test.ts
@@ -5,14 +5,9 @@ import {
parseURLVariables,
SEARCH_PARAM_FILTERS_KEY,
SEARCH_PARAM_QUERY_VARIABLES_KEY,
- scheduleSharedDashboardStaleAutoForceIfEligible,
shouldSharedDashboardAutoForceForStaleTime,
} from './dashboardUtils'
-async function flushMicrotasks(): Promise<void> {
- await new Promise<void>((resolve) => queueMicrotask(resolve))
-}
-
describe('parseURLVariables', () => {
it.each([
['a JSON string value', '{"card_name":"Polukranos, Unchained"}', { card_name: 'Polukranos, Unchained' }],
@@ -95,26 +90,3 @@ describe('shouldSharedDashboardAutoForceForStaleTime', () => {
})
})
})
-
-describe('scheduleSharedDashboardStaleAutoForceIfEligible', () => {
- it('does not invoke trigger when not stale', async () => {
- const trigger = jest.fn()
- scheduleSharedDashboardStaleAutoForceIfEligible({
- effectiveLastRefresh: dayjs().subtract(15, 'minute'),
- triggerDashboardRefresh: trigger,
- })
- await flushMicrotasks()
- expect(trigger).not.toHaveBeenCalled()
- })
-
- it('invokes trigger on the next microtask when stale', async () => {
- const trigger = jest.fn()
- scheduleSharedDashboardStaleAutoForceIfEligible({
- effectiveLastRefresh: dayjs().subtract(31, 'minute'),
- triggerDashboardRefresh: trigger,
- })
- expect(trigger).not.toHaveBeenCalled()
- await flushMicrotasks()
- expect(trigger).toHaveBeenCalledTimes(1)
- })
-})
diff --git a/frontend/src/scenes/dashboard/dashboardUtils.ts b/frontend/src/scenes/dashboard/dashboardUtils.ts
index 9f25b0185017..76338e68c051 100644
--- a/frontend/src/scenes/dashboard/dashboardUtils.ts
+++ b/frontend/src/scenes/dashboard/dashboardUtils.ts
@@ -24,6 +24,8 @@ import {
TileLayout,
} from '~/types'
+import { SHARED_DASHBOARD_AUTO_FORCE_IF_STALE_MINUTES } from './dashboardConstants'
+
/** Shape used for staff JSON export, customer save-as-template, and API `create_from_template_json`. */
export function dashboardToSaveableTemplate(
dashboard: DashboardType<InsightModel> | null | undefined
@@ -115,16 +117,8 @@ export const DEFAULT_AUTO_PREVIEW_TILE_LIMIT = 10
const RATE_LIMIT_ERROR_MESSAGE = 'concurrency_limit_exceeded'
-export const AUTO_REFRESH_INITIAL_INTERVAL_SECONDS = 1800
export const QUICK_FILTER_DEBOUNCE_MS = 1500
-/**
- * Cold-start one-shot threshold: if data is older than this when a shared dashboard loads,
- * trigger one immediate force_blocking refresh. Aligned with the periodic interval and the
- * backend throttle (`SHARED_FORCE_BLOCKING_MIN_AGE`).
- */
-export const SHARED_DASHBOARD_AUTO_FORCE_IF_STALE_MINUTES = AUTO_REFRESH_INITIAL_INTERVAL_SECONDS / 60
-
function staleAgeMinutes(effectiveLastRefresh: Dayjs | null): number | null {
if (!effectiveLastRefresh) {
return null
@@ -144,23 +138,6 @@ export function shouldSharedDashboardAutoForceForStaleTime(effectiveLastRefresh:
return ageMinutes !== null && ageMinutes >= SHARED_DASHBOARD_AUTO_FORCE_IF_STALE_MINUTES
}
-/**
- * Trigger one force_blocking refresh on initial shared-dashboard load if the stalest tile is too old.
- * Idempotent across reloads since the follow-up run uses `forceRefresh` + non-initial action.
- */
-export function scheduleSharedDashboardStaleAutoForceIfEligible(options: {
- effectiveLastRefresh: Dayjs | null
- triggerDashboardRefresh: () => void
-}): void {
- const { effectiveLastRefresh, triggerDashboardRefresh } = options
- if (!shouldSharedDashboardAutoForceForStaleTime(effectiveLastRefresh)) {
- return
- }
- queueMicrotask(() => {
- triggerDashboardRefresh()
- })
-}
-
// Helper function for exponential backoff
const wait = (ms: number): Promise<void> => new Promise((resolve) => setTimeout(resolve, ms))
diff --git a/frontend/src/scenes/insights/insightUsageLogic.ts b/frontend/src/scenes/insights/insightUsageLogic.ts
index 3c1ee284f636..ef777dc33f98 100644
--- a/frontend/src/scenes/insights/insightUsageLogic.ts
+++ b/frontend/src/scenes/insights/insightUsageLogic.ts
@@ -7,6 +7,7 @@ import { eventUsageLogic } from 'lib/utils/eventUsageLogic'
import { projectLogic } from 'scenes/projectLogic'
import { sceneLogic } from 'scenes/sceneLogic'
+import { isSharedView } from '~/exporter/exporterViewLogic'
import { DataNodeLogicProps, dataNodeLogic } from '~/queries/nodes/DataNode/dataNodeLogic'
import { insightVizDataNodeKey } from '~/queries/nodes/InsightViz/InsightViz'
import { Node } from '~/queries/schema/schema-general'
@@ -63,7 +64,7 @@ export const insightUsageLogic = kea<insightUsageLogicType>([
// Report the insight being viewed to our '/viewed' endpoint.
// Used for "recently viewed insights", and in insights dashboard.
- if (values.insight.id) {
+ if (values.insight.id && !isSharedView()) {
void api.create(`api/environments/${values.currentProjectId}/insights/viewed`, {
insight_ids: [values.insight.id],
})
diff --git a/frontend/src/scenes/sceneLogic.tsx b/frontend/src/scenes/sceneLogic.tsx
index afdd76a6afb4..84ac164159b0 100644
--- a/frontend/src/scenes/sceneLogic.tsx
+++ b/frontend/src/scenes/sceneLogic.tsx
@@ -36,6 +36,7 @@ import {
} from 'scenes/sceneTypes'
import { urls } from 'scenes/urls'
+import { isSharedView } from '~/exporter/exporterViewLogic'
import { sidePanelStateLogic } from '~/layout/navigation-3000/sidepanel/sidePanelStateLogic'
import { FileSystemIconType, ProductKey } from '~/queries/schema/schema-general'
import { AccessControlLevel } from '~/types'
@@ -971,6 +972,9 @@ export const sceneLogic = kea<sceneLogicType>([
}
},
loadPinnedTabsFromBackend: async () => {
+ if (isSharedView()) {
+ return
+ }
try {
const response = await api.get<{
tabs?: SceneTab[]
@@ -1572,6 +1576,9 @@ export const sceneLogic = kea<sceneLogicType>([
subscriptions(({ actions, values, cache }) => {
const schedulePinnedStateSync = (): void => {
+ if (isSharedView()) {
+ return
+ }
const pinnedTabsForPersistence = getPinnedTabsForPersistence(values.tabs)
const homepageForPersistence = getHomepageForPersistence(values.homepage)
const serializedPinnedState = JSON.stringify({
diff --git a/playwright/e2e/shared-dashboard-unauthenticated.spec.ts b/playwright/e2e/shared-dashboard-unauthenticated.spec.ts
index 89ffb1ae6f84..8ef90e24f549 100644
--- a/playwright/e2e/shared-dashboard-unauthenticated.spec.ts
+++ b/playwright/e2e/shared-dashboard-unauthenticated.spec.ts
@@ -9,6 +9,7 @@ import { expect, Page } from '@playwright/test'
import { InsightVizNode, NodeKind, TrendsQuery } from '../../frontend/src/queries/schema/schema-general'
import { SharingConfigurationType } from '../../frontend/src/types'
import { PlaywrightSetup } from '../utils/playwright-setup'
+import { expectNoTeamScopedApiLeaks, openUnauthenticatedSharedPage } from '../utils/sharedViewExpectations'
import { test } from '../utils/workspace-test-base'
async function createSharedDashboard(
@@ -74,7 +75,7 @@ test.describe('Shared dashboard (unauthenticated)', () => {
)
const unauthContext = await browser.newContext({ storageState: { cookies: [], origins: [] } })
- const unauthPage = await unauthContext.newPage()
+ const { unauthPage, failedApiResponses } = await openUnauthenticatedSharedPage(unauthContext)
try {
await unauthPage.goto(`/shared/${sharingData.access_token}`)
@@ -83,6 +84,8 @@ test.describe('Shared dashboard (unauthenticated)', () => {
await expect(unauthPage.locator(`text=${dashboardName}`)).toBeVisible({ timeout: 30000 })
await expect(unauthPage.locator(`text=${insightName}`)).toBeVisible({ timeout: 30000 })
await expect(unauthPage.locator('[data-attr="insights-graph"]').first()).toBeVisible({ timeout: 30000 })
+
+ expectNoTeamScopedApiLeaks(failedApiResponses)
} finally {
await unauthContext.close()
}
diff --git a/playwright/e2e/shared-insight-unauthenticated.spec.ts b/playwright/e2e/shared-insight-unauthenticated.spec.ts
new file mode 100644
index 000000000000..ef0f8cec7e29
--- /dev/null
+++ b/playwright/e2e/shared-insight-unauthenticated.spec.ts
@@ -0,0 +1,84 @@
+/**
+ * Regression test: shared insights must render in a fully unauthenticated browser context.
+ * Sibling to shared-dashboard-unauthenticated.spec.ts and shared-notebook-unauthenticated.spec.ts —
+ * covers the ExporterInsightScene path directly so a regression in insight sharing isn't
+ * masked behind dashboard tile rendering.
+ */
+import { expect, Page } from '@playwright/test'
+
+import { InsightVizNode, NodeKind, TrendsQuery } from '../../frontend/src/queries/schema/schema-general'
+import { SharingConfigurationType } from '../../frontend/src/types'
+import { PlaywrightSetup } from '../utils/playwright-setup'
+import { expectNoTeamScopedApiLeaks, openUnauthenticatedSharedPage } from '../utils/sharedViewExpectations'
+import { test } from '../utils/workspace-test-base'
+
+async function createSharedInsight(
+ page: Page,
+ playwrightSetup: PlaywrightSetup,
+ orgName: string
+): Promise<{ sharingData: SharingConfigurationType; insightName: string }> {
+ const workspace = await playwrightSetup.createWorkspace(orgName)
+ const authHeaders = {
+ Authorization: `Bearer ${workspace.personal_api_key}`,
+ 'Content-Type': 'application/json',
+ }
+
+ const insightName = 'Logged-out insight render'
+ const insightPayload: { name: string; query: InsightVizNode<TrendsQuery> } = {
+ name: insightName,
+ query: {
+ kind: NodeKind.InsightVizNode,
+ source: {
+ kind: NodeKind.TrendsQuery,
+ series: [{ kind: NodeKind.EventsNode, event: '$pageview' }],
+ dateRange: { date_from: '2024-10-04', date_to: '2024-11-03', explicitDate: true },
+ },
+ },
+ }
+
+ const insightResponse = await page.request.post(`/api/projects/${workspace.team_id}/insights/`, {
+ headers: authHeaders,
+ data: insightPayload,
+ })
+ expect(insightResponse.ok()).toBe(true)
+ const insightData = await insightResponse.json()
+
+ const sharingResponse = await page.request.patch(
+ `/api/projects/${workspace.team_id}/insights/${insightData.id}/sharing`,
+ {
+ headers: authHeaders,
+ data: { enabled: true },
+ }
+ )
+ expect(sharingResponse.ok()).toBe(true)
+ const sharingData: SharingConfigurationType = await sharingResponse.json()
+ expect(sharingData.access_token).toBeTruthy()
+ expect(sharingData.enabled).toBe(true)
+
+ return { sharingData, insightName }
+}
+
+test.describe('Shared insight (unauthenticated)', () => {
+ test('renders successfully in a logged-out browser context', async ({ browser, page, playwrightSetup }) => {
+ const { sharingData, insightName } = await createSharedInsight(
+ page,
+ playwrightSetup,
+ 'Unauth Shared Insight Test Org'
+ )
+
+ const unauthContext = await browser.newContext({ storageState: { cookies: [], origins: [] } })
+ const { unauthPage, failedApiResponses } = await openUnauthenticatedSharedPage(unauthContext)
+
+ try {
+ await unauthPage.goto(`/shared/${sharingData.access_token}`)
+
+ await expect(unauthPage.locator('body.ExporterBody')).toBeVisible()
+ await expect(unauthPage.locator(`text=${insightName}`)).toBeVisible({ timeout: 30000 })
+ await expect(unauthPage.locator('[data-attr="insights-graph"]')).toBeVisible({ timeout: 30000 })
+
+ expectNoTeamScopedApiLeaks(failedApiResponses)
+ } finally {
+ await unauthContext.close()
+ }
+ })
+})
diff --git a/playwright/e2e/shared-notebook-unauthenticated.spec.ts b/playwright/e2e/shared-notebook-unauthenticated.spec.ts
new file mode 100644
index 000000000000..1bd73035fa79
--- /dev/null
+++ b/playwright/e2e/shared-notebook-unauthenticated.spec.ts
@@ -0,0 +1,87 @@
+/**
+ * Regression test: shared notebooks must render in a fully unauthenticated browser context.
+ * Sibling to shared-dashboard-unauthenticated.spec.ts — ensures the ExporterNotebookScene
+ * code path keeps working when the exporter bundle / shared-view skipping evolves.
+ */
+import { expect, Page } from '@playwright/test'
+
+import { SharingConfigurationType } from '../../frontend/src/types'
+import { PlaywrightSetup } from '../utils/playwright-setup'
+import { expectNoTeamScopedApiLeaks, openUnauthenticatedSharedPage } from '../utils/sharedViewExpectations'
+import { test } from '../utils/workspace-test-base'
+
+async function createSharedNotebook(
+ page: Page,
+ playwrightSetup: PlaywrightSetup,
+ orgName: string
+): Promise<{ sharingData: SharingConfigurationType; notebookTitle: string; paragraphText: string }> {
+ const workspace = await playwrightSetup.createWorkspace(orgName)
+ const authHeaders = {
+ Authorization: `Bearer ${workspace.personal_api_key}`,
+ 'Content-Type': 'application/json',
+ }
+
+ const notebookTitle = 'Logged-out notebook render'
+ const paragraphText = 'Anonymous notebook body content'
+ const notebookContent = {
+ type: 'doc',
+ content: [
+ {
+ type: 'heading',
+ attrs: { level: 1 },
+ content: [{ type: 'text', text: notebookTitle }],
+ },
+ {
+ type: 'paragraph',
+ content: [{ type: 'text', text: paragraphText }],
+ },
+ ],
+ }
+
+ const notebookResponse = await page.request.post(`/api/projects/${workspace.team_id}/notebooks/`, {
+ headers: authHeaders,
+ data: { title: notebookTitle, content: notebookContent },
+ })
+ expect(notebookResponse.ok()).toBe(true)
+ const notebookData = await notebookResponse.json()
+ expect(notebookData.short_id).toBeTruthy()
+
+ const sharingResponse = await page.request.patch(
+ `/api/projects/${workspace.team_id}/notebooks/${notebookData.short_id}/sharing/`,
+ {
+ headers: authHeaders,
+ data: { enabled: true },
+ }
+ )
+ expect(sharingResponse.ok()).toBe(true)
+ const sharingData: SharingConfigurationType = await sharingResponse.json()
+ expect(sharingData.access_token).toBeTruthy()
+ expect(sharingData.enabled).toBe(true)
+
+ return { sharingData, notebookTitle, paragraphText }
+}
+
+test.describe('Shared notebook (unauthenticated)', () => {
+ test('renders successfully in a logged-out browser context', async ({ browser, page, playwrightSetup }) => {
+ const { sharingData, notebookTitle, paragraphText } = await createSharedNotebook(
+ page,
+ playwrightSetup,
+ 'Unauth Shared Notebook Test Org'
+ )
+
+ const unauthContext = await browser.newContext({ storageState: { cookies: [], origins: [] } })
+ const { unauthPage, failedApiResponses } = await openUnauthenticatedSharedPage(unauthContext)
+
+ try {
+ await unauthPage.goto(`/shared/${sharingData.access_token}`)
+
+ await expect(unauthPage.locator('body.ExporterBody')).toBeVisible()
+ await expect(unauthPage.locator(`text=${notebookTitle}`).first()).toBeVisible({ timeout: 30000 })
+ await expect(unauthPage.locator(`text=${paragraphText}`)).toBeVisible({ timeout: 30000 })
+
+ expectNoTeamScopedApiLeaks(failedApiResponses)
+ } finally {
+ await unauthContext.close()
+ }
+ })
+})
diff --git a/playwright/utils/sharedViewExpectations.ts b/playwright/utils/sharedViewExpectations.ts
new file mode 100644
index 000000000000..9ef17f25eed1
--- /dev/null
+++ b/playwright/utils/sharedViewExpectations.ts
@@ -0,0 +1,66 @@
+/**
+ * Shared helpers for the `/shared/{token}` unauthenticated playwright tests
+ * (dashboard, insight, notebook). Centralises the network-leak assertion so a
+ * silent 401/403 against /api/* fails the test even if the page still renders.
+ *
+ * The class of regression we keep tripping on is "shared mode silently leaks an
+ * authenticated request" — the page may still render, but the leak is the
+ * actual bug. Each unauth spec must assert on the network, not just the DOM.
+ */
+import { type BrowserContext, expect, type Page } from '@playwright/test'
+
+interface RecordedFailure {
+ method: string
+ url: string
+ status: number
+}
+
+/**
+ * Open a Page in the supplied context and record EVERY /api/* response with
+ * status >= 400. The recording is unfiltered — what to allow vs flag is the
+ * caller's job (see `expectNoTeamScopedApiLeaks` below).
+ *
+ * The expected use is to pass a fresh BrowserContext (created with empty
+ * storage/cookies) to guarantee a logged-out browser, then assert against the
+ * recorded failures after the page has settled.
+ */
+export async function openUnauthenticatedSharedPage(context: BrowserContext): Promise<{
+ unauthPage: Page
+ failedApiResponses: RecordedFailure[]
+}> {
+ const unauthPage = await context.newPage()
+ const failedApiResponses: RecordedFailure[] = []
+
+ unauthPage.on('response', (response) => {
+ const url = response.url()
+ const status = response.status()
+ if (!url.includes('/api/') || status < 400) {
+ return
+ }
+ failedApiResponses.push({ method: response.request().method(), url, status })
+ })
+
+ return { unauthPage, failedApiResponses }
+}
+
+/**
+ * Assert that no `/api/(environments|projects)/{team}/{resource}` request
+ * 4xx'd while the shared page was rendering. Other paths (`/api/flags/`,
+ * `/api/users/@me/`, `/api/organizations/...`, `/api/user_home_settings/`,
+ * etc) are intentionally NOT covered here — they have legitimate unauth
+ * failure modes, and the `client_request_failure` posthog event tags them
+ * with `is_shared_view` so production telemetry still surfaces leaks.
+ *
+ * NOTE: this filter is deliberately narrow to avoid false positives. If a
+ * regression leaks an org-scoped or user-scoped call, this assertion won't
+ * catch it — broaden the filter (or add a sibling assertion) when those
+ * paths become a concern.
+ */
+export function expectNoTeamScopedApiLeaks(failedApiResponses: ReadonlyArray<RecordedFailure>): void {
+ const leaked = failedApiResponses.filter(({ url }) => /\/api\/(environments|projects)\/\d+\//.test(url))
+ expect(leaked, `Unexpected team-scoped API failures in shared mode:\n${formatFailures(leaked)}`).toEqual([])
+}
+
+function formatFailures(failures: ReadonlyArray<RecordedFailure>): string {
+ return failures.map(({ method, status, url }) => ` ${method} ${url} -> ${status}`).join('\n')
+}