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.

chore(storybook): keep msw and vite preload out of story load time (#128589)

Frank Hamand945c5707a311
diff --git a/common/storybook/.storybook/main.ts b/common/storybook/.storybook/main.ts
index 6dee728b7af7..92ef22d22d45 100644
--- a/common/storybook/.storybook/main.ts
+++ b/common/storybook/.storybook/main.ts
@@ -80,6 +80,10 @@ const config: StorybookConfig = {
options: {},
},
+ // Automated runs skip the highlight feature, which scans every element after each DOM change.
+ previewHead: (head) =>
+ `${head}<script>if (navigator.webdriver) { window.__STORYBOOK_HIGHLIGHT_INITIALIZED = true }</script>`,
+
viteFinal: (viteConfig) =>
mergeConfig(viteConfig, {
plugins: [
@@ -147,6 +151,8 @@ const config: StorybookConfig = {
},
},
build: {
+ // The preload helper's cost grows with the square of the chunk count.
+ modulePreload: false,
rollupOptions: {
onwarn(warning: Rollup.RollupLog, defaultHandler: (warning: Rollup.RollupLog) => void) {
// "use client" directives from RSC-oriented deps (framer-motion, radix)
diff --git a/common/storybook/.storybook/preview.tsx b/common/storybook/.storybook/preview.tsx
index fdac7ec27766..949149a91b08 100644
--- a/common/storybook/.storybook/preview.tsx
+++ b/common/storybook/.storybook/preview.tsx
@@ -28,6 +28,7 @@ configureTestingLibrary({ asyncUtilTimeout: 15000 })
const setupMsw = (): void => {
// Make sure the msw worker is started
worker.start({
+ serviceWorker: { url: '/storybookServiceWorker.js' },
quiet: true,
onUnhandledRequest(request, print) {
// MSW warns on all unhandled requests, but we don't necessarily care
diff --git a/common/storybook/.storybook/public/storybookServiceWorker.js b/common/storybook/.storybook/public/storybookServiceWorker.js
new file mode 100644
index 000000000000..a6a45360ed52
--- /dev/null
+++ b/common/storybook/.storybook/public/storybookServiceWorker.js
@@ -0,0 +1,12 @@
+// Static assets skip msw, which otherwise round-trips every request through the page.
+const STATIC_ASSET_URL =
+ /^https?:\/\/[^/]+\/(?!api\/)(?:(?:assets|static|sb-[\w-]+|@fs|@id|@vite|node_modules)\/.*|[^?#]*\.(?:m?js|jsx|tsx?|css|scss|less|woff2?|ttf|otf|png|jpe?g|gif|svg|webp|ico|map|wasm))$/
+
+self.addEventListener('fetch', (event) => {
+ const url = event.request.url.split(/[?#]/)[0]
+ if (event.request.method === 'GET' && STATIC_ASSET_URL.test(url)) {
+ event.stopImmediatePropagation()
+ }
+})
+
+importScripts('./mockServiceWorker.js')
diff --git a/frontend/src/mocks/browser.tsx b/frontend/src/mocks/browser.tsx
index 2118d49199b2..f5e216a96ac5 100644
--- a/frontend/src/mocks/browser.tsx
+++ b/frontend/src/mocks/browser.tsx
@@ -2,6 +2,7 @@ import type { Decorator } from '@storybook/react'
import { setupWorker } from 'msw/browser'
import { handlers, toPaginatedResponse } from '~/mocks/handlers'
+import { routeHandlers } from '~/mocks/routeHandlers'
import { HTTP_METHODS, MockSignature, Mocks, mocksToHandlers } from '~/mocks/utils'
import type { AppContext } from '~/types'
@@ -20,8 +21,7 @@ const storybookDefaultMocks: Mocks = {
// Default handlers ensure no request is unhandled by msw. Handlers listed first take precedence.
export const worker: ReturnType<typeof setupWorker> = setupWorker(
- ...mocksToHandlers(storybookDefaultMocks),
- ...handlers
+ routeHandlers([...mocksToHandlers(storybookDefaultMocks), ...handlers])
)
export const useStorybookMocks = (mocks: Mocks): void => worker.use(...mocksToHandlers(mocks))
diff --git a/frontend/src/mocks/routeHandlers.test.ts b/frontend/src/mocks/routeHandlers.test.ts
new file mode 100644
index 000000000000..8375e9f440ce
--- /dev/null
+++ b/frontend/src/mocks/routeHandlers.test.ts
@@ -0,0 +1,51 @@
+import { getResponse, HttpHandler, type HttpHandler as HttpHandlerType } from 'msw'
+
+import { handlers } from '~/mocks/handlers'
+import { routeHandlers } from '~/mocks/routeHandlers'
+
+const markers: HttpHandlerType[] = handlers.map(
+ (handler, index) => new HttpHandler(handler.info.method, handler.info.path, () => new Response(String(index)))
+)
+
+const answer = async (list: HttpHandlerType[], method: string, url: string): Promise<string> => {
+ const response = await getResponse(list, new Request(new URL(url, 'http://localhost/'), { method }))
+ return response ? await response.text() : 'unhandled'
+}
+
+const requestsFor = (handler: HttpHandlerType, index: number): [string, string][] => {
+ const { method, path } = handler.info
+ if (typeof path !== 'string' || typeof method !== 'string' || !path.startsWith('/')) {
+ return []
+ }
+ const filled = path.replace(/:[^/]+/g, 'Abc1')
+ const variants: [string, string][] = [
+ [method, filled],
+ [method, `${filled.toUpperCase()}?q=1`],
+ [method, `${filled}/extra/`],
+ [method === 'GET' ? 'POST' : 'GET', `${filled}/`],
+ ]
+ return [[method, `${filled}/`], variants[index % variants.length]]
+}
+
+describe('routeHandlers', () => {
+ it('answers every request with the same default handler as msw', async () => {
+ const router = [routeHandlers(markers)]
+ const requests: [string, string][] = [
+ ...markers.flatMap(requestsFor),
+ ['GET', '/'],
+ ['GET', '/api/'],
+ ['GET', '/not/a/mocked/path/'],
+ ['GET', 'https://us.i.posthog.com/flags/?v=2'],
+ ]
+ const mismatches: string[] = []
+ for (const [method, url] of requests) {
+ const expected = await answer(markers, method, url)
+ const actual = await answer(router, method, url)
+ if (actual !== expected) {
+ mismatches.push(`${method} ${url}: msw ${expected}, router ${actual}`)
+ }
+ }
+ expect(requests.length).toBeGreaterThan(300)
+ expect(mismatches).toEqual([])
+ })
+})
diff --git a/frontend/src/mocks/routeHandlers.ts b/frontend/src/mocks/routeHandlers.ts
new file mode 100644
index 000000000000..0293bda40b7a
--- /dev/null
+++ b/frontend/src/mocks/routeHandlers.ts
@@ -0,0 +1,48 @@
+import { getResponse, http, type HttpHandler } from 'msw'
+
+type RouteEntry = { handler: HttpHandler; method: string | RegExp; segments: string[] | null }
+
+const pathSegments = (path: unknown): string[] | null => {
+ if (typeof path !== 'string' || !path.startsWith('/') || /[*?+()\\]/.test(path)) {
+ return null
+ }
+ const segments = path.replace(/\/$/, '').toLowerCase().split('/')
+ return segments.some((segment) => segment.includes(':', 1)) ? null : segments
+}
+
+// Must never reject a handler msw would accept. msw ignores case and a trailing slash.
+const mayMatch = (entry: RouteEntry, method: string, requestSegments: string[]): boolean => {
+ const methodMatches =
+ typeof entry.method === 'string' ? entry.method.toUpperCase() === method : entry.method.test(method)
+ if (!methodMatches) {
+ return false
+ }
+ if (!entry.segments) {
+ return true
+ }
+ return (
+ entry.segments.length === requestSegments.length &&
+ entry.segments.every((segment, i) =>
+ segment.startsWith(':') ? requestSegments[i] !== '' : segment === requestSegments[i]
+ )
+ )
+}
+
+export const routeHandlers = (handlers: HttpHandler[]): HttpHandler => {
+ const entries: RouteEntry[] = handlers.map((handler) => ({
+ handler,
+ method: handler.info.method,
+ segments: pathSegments(handler.info.path),
+ }))
+ return http.all('*', ({ request }) => {
+ const requestSegments = new URL(request.url).pathname.replace(/\/$/, '').toLowerCase().split('/')
+ const method = request.method.toUpperCase()
+ const candidates = entries.filter((entry) => mayMatch(entry, method, requestSegments))
+ return candidates.length > 0
+ ? getResponse(
+ candidates.map((entry) => entry.handler),
+ request
+ )
+ : undefined
+ })
+}