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): wait for the mock service worker before rendering (#129045)

Michael Reichenbach6ea0691ce8fa
diff --git a/common/storybook/.storybook/preview.tsx b/common/storybook/.storybook/preview.tsx
index 949149a91b08..6f9a29d6df1c 100644
--- a/common/storybook/.storybook/preview.tsx
+++ b/common/storybook/.storybook/preview.tsx
@@ -25,9 +25,9 @@ import { withTheme } from './decorators/withTheme'
// story a load-tolerant default budget instead of making each play pass its own timeout.
configureTestingLibrary({ asyncUtilTimeout: 15000 })
-const setupMsw = (): void => {
+const setupMsw = (): Promise<unknown> => {
// Make sure the msw worker is started
- worker.start({
+ const workerStarted = worker.start({
serviceWorker: { url: '/storybookServiceWorker.js' },
quiet: true,
onUnhandledRequest(request, print) {
@@ -45,8 +45,9 @@ const setupMsw = (): void => {
})
;(window as any).__mockServiceWorker = worker
;(window as any).POSTHOG_APP_CONTEXT = getStorybookAppContext()
+ return workerStarted
}
-setupMsw()
+const mswStarted = setupMsw()
const setupPosthogJs = (): void => {
// Make sure we don't hit production posthog. We want to control requests to,
@@ -71,6 +72,13 @@ const loaders: Preview['loaders'] = [
.catch(() => undefined)
return {}
},
+ // MSW 2 does not hold requests back while its worker registers. Without this wait, the first story
+ // on a fresh page can send its API calls to the real server and render their failure instead.
+ // A failed start rejects here, so the story reports it rather than rendering without mocks.
+ async () => {
+ await mswStarted
+ return {}
+ },
]
// Setup storybook global decorators. See https://storybook.js.org/docs/react/writing-stories/decorators#global-decorators
diff --git a/common/storybook/docs/mocking-data.md b/common/storybook/docs/mocking-data.md
index 0a4960bf041c..192190e591c5 100644
--- a/common/storybook/docs/mocking-data.md
+++ b/common/storybook/docs/mocking-data.md
@@ -1,6 +1,7 @@
# Mocking data in stories
Stories talk to the PostHog API through a Mock Service Worker that starts in `preview.tsx`.
+A global loader holds every story's render until the worker is ready, so the first story on a fresh page gets its mocks too.
Every request goes to the worker first: a story mock, then a default mock, then the network.
## Mock API responses