Storybook runtime architecture
Storybook turns project configuration and story files into a browser-based workbench for browsing, rendering, and testing components. A Node.js server prepares the project and serves two browser realms: the manager UI controls the session, while the preview iframe loads and renders the selected story. Shared APIs and event channels connect these realms without merging their responsibilities.
Runtime boundaries
The runtime has four main boundaries. The server owns project setup and coordination. The manager owns navigation and controls. The preview owns story code and rendering. Shared APIs define the contracts that let addons and framework packages work across these boundaries.
| Boundary | Main responsibility | Primary result |
|---|---|---|
| Server | Load configuration, apply presets, index stories, and start builders | A running Storybook service |
| Manager | Show the Storybook workbench and select a story | Navigation and user controls |
| Preview | Load project annotations and render the selected story | Component output and story events |
| Shared APIs | Carry state, addon calls, and runtime events across realms | Consistent cross-boundary behavior |
The server passes one resolved option set and one channel into the manager and preview builders. This keeps project settings, feature flags, and runtime services aligned while each browser realm remains isolated. The public server boundary also exposes runtime assembly, story-index, channel, service, and change-detection capabilities to other Storybook packages. The common boundary also exposes project setup services, including package-manager and source-resolution contracts, before the browser realms start.
References: code/…/build-dev.ts• L184-293 code/…/build-static.ts• L129-145 code/…/load.ts• L45-49 code/…/index.ts• L3-16
Configuration and story assembly
Project configuration is the input to the runtime assembly process. Storybook reads the main configuration, identifies the framework and builder, applies presets, and resolves the project’s story and preview settings before it serves the browser pages or writes a static build.
The story index is the server-side map from story files to navigable story and docs entries. It lets the manager show the project tree and lets the preview resolve a selected story without scanning the project in the browser. The index also carries tags, story relationships, and import paths that support docs, tests, and other runtime features.
Development, production, and embedded loading use the same two-stage assembly idea. An initial preset pass identifies the renderer and builder. A complete pass then combines the common presets with the builder, renderer, framework, feature, and service settings. The active channel is supplied to that complete pass so runtime services share the same event and state path.
The assembly flow has these stages:
- Load the main configuration and framework preset.
- Apply an initial preset pass to discover the renderer and builder.
- Apply the complete preset chain with the resolved channel available.
- Build or write the story index from the configured story files and docs sources.
- Start the manager and preview builders, or emit their static browser assets.
This diagram shows how project inputs become the runtime surfaces used by the browser.
flowchart LR
config[Project configuration] --> presets[Resolved presets and features]
stories[Story and docs files] --> index[Story index]
presets --> server[Storybook server or static output]
index --> server
server --> manager[Manager page]
server --> preview[Preview iframe]
manager <--> channel[Shared event channels]
preview <--> channel
The same assembly also enables server-side services that enrich the runtime, such as component documentation. Source analysis can follow a component through imports, aliases, and re-exports so documentation points to the component a story actually names. Static build reporting can summarize the available story documentation without changing the manager-to-preview contract.
The common preset also connects the live server to project services and tools. These services use the resolved story index, module graph, Git state, and shared channel to support module changes, review data, story documentation, and project-aware tools while the browser boundaries stay unchanged. The service layer is applied once and then subscribes to development-server events, so these capabilities extend the server without becoming another browser realm.
Change detection turns repository changes into story-level status data. It waits for the module graph to be ready, reads changed and new files from Git, maps those files to affected stories, and publishes status updates through the server-side status store. A baseline comparison can also mark newly indexed stories so review tools can show both file changes and index changes.
The shared common API gathers the configuration, preset, path, framework, project-resolution, package-manager, and source-analysis contracts used by this assembly. Package-manager adapters provide one project setup contract across npm, Yarn Classic, Yarn Berry, pnpm, and Bun. They preserve workspace catalogs, dependency overrides, bundled package metadata, and the set of Storybook packages maintained outside the monorepo. The server API gathers the server entry points and service contracts that make the assembled runtime available to callers.
See Story format and analysis for story-file formats, indexing, and analysis tools.
References: code/…/build-static.ts• L60-114 code/…/build-static.ts• L177-185 code/…/build-static.ts• L217-243 code/…/common-preset.ts• L373-500 code/…/common-preset.ts• L502-512 code/…/common-preset.ts• L514-554 code/…/GitDiffProvider.ts• L47-115 code/…/change-detection-service.ts• L227-251 code/…/change-detection-service.ts• L357-414 code/…/index.ts• L3-16 code/…/index.ts• L5-84 code/…/JsPackageManager.ts• L108-166 code/…/JsPackageManager.ts• L349-405 code/…/NPMProxy.ts• L83-143 code/…/PNPMProxy.ts• L69-165 code/…/Yarn1Proxy.ts• L33-80 code/…/Yarn2Proxy.ts• L90-134 code/…/BUNProxy.ts• L81-151 code/…/PackageJson.ts• L12-19 code/…/satellite-addons.ts• L1-14 code/…/overrides.ts• L1-33 code/…/resolve-meta-component.ts• L105-152 code/…/summarizeStoryDocs.ts• L8-32
Server boundary
The server is the Node.js boundary that turns resolved project settings into an addressable Storybook. It attaches the manager and preview builders to one HTTP service, exposes the story index, serves static assets, and keeps the runtime aware of file and configuration changes.
The server starts the manager first when a full Storybook is requested. It then starts the preview and only treats the runtime as ready after both the preview build and the listening address succeed. Preview-only mode skips the manager and opens the preview directly. A production build follows a separate path: it writes the manager and preview assets, the story index, and project metadata to an output directory for a host server to serve.
The server also owns the server side of the event channel. It accepts authenticated manager, preview, and server clients. It broadcasts allowed events to the connected clients and rejects messages that do not match the sender role. Server-side services use this same boundary for project tools and status updates without giving browser clients direct access to the module graph or Git state.
The server-facing API groups these runtime capabilities behind one shared boundary. It gives callers access to configuration and build entry points, story indexing, channel setup, runtime services, and change-aware project data without exposing the manager or preview as the same process space.
During development, the server preset starts channel-backed services after the shared configuration and story index are ready. Those services extend the live runtime with project tools and change-aware data. They do not become a second browser runtime.
A running development instance can publish a private runtime record with its address, process identity, channel token, and configuration location. This gives tools a safe way to find and attach to the active Storybook without changing the browser boundaries.
See CLI and server lifecycle for command startup, server lifecycle, and shutdown behavior.
References: code/…/build-dev.ts• L253-293 code/…/build-static.ts• L141-215 code/…/dev-server.ts• L32-57 code/…/dev-server.ts• L120-180 code/…/common-preset.ts• L311-323 code/…/common-preset.ts• L373-523 code/…/GitDiffProvider.ts• L47-115 code/…/change-detection-service.ts• L196-251 code/…/change-detection-service.ts• L284-352 code/…/get-server-channel.ts• L23-39 code/…/get-server-channel.ts• L55-101 code/…/runtime-instance-registry.ts• L56-83 code/…/runtime-instance-registry.ts• L382-429 code/…/index.ts• L3-16 code/…/index.ts• L97-127
Story index
The story index is the shared navigation contract between the server, manager, and preview. The server creates it from configured story specifiers. Indexers turn matching story files into story entries, while docs analysis adds docs entries and links them to their story files. The manager uses the result to present stories and docs. The preview uses it to locate the module and story selected by the manager.
Story entries receive stable IDs, names, titles, import paths, tags, and optional component or parent information. Autodocs can add a docs entry beside a story file. Standalone MDX can create a docs entry that points to the stories it imports. Duplicate entries are resolved or reported before the index is returned.
Changes to story files or preview configuration invalidate the relevant index data. Story-file events are filtered against the configured story patterns and batched before invalidation. A preview-file change invalidates the full index because project tags and annotations can affect every entry. The server emits a debounced invalidation event so the browser realms can refresh their view of the project.
The index can also be summarized for reports and feature signals. That summary counts user stories and components separately from example and onboarding content, and it records selected docs, play, test, and page-story signals without changing the navigation contract.
References: code/…/StoryIndexGenerator.ts• L111-132 code/…/StoryIndexGenerator.ts• L341-465 code/…/StoryIndexGenerator.ts• L467-585 code/…/StoryIndexGenerator.ts• L683-844 code/…/index-json.ts• L17-76 code/…/watch-files.ts• L27-69 code/…/watch-story-specifiers.ts• L7-53 code/…/watch-story-specifiers.test.ts• L57-215 code/…/summarizeIndex.ts• L28-111 code/…/glob-to-regexp.ts• L3-29 code/…/Preview.tsx• L181-190
Manager boundary
The manager is the Storybook workbench. It owns the sidebar, toolbar, panels, addon pages, routing, layout, and the selection state that tells the preview which story to display.
The manager runtime creates a browser channel before it renders the UI. Its provider connects the manager API to the channel and addon store. The main application then combines manager state with the preview container and addon-provided UI elements.
The manager does not render the story module itself. Its preview container points at the preview iframe and supplies the selected story, view mode, layout, tools, and wrappers. This separation keeps user controls in the manager while component code runs in the preview realm.
The manager keeps layout state separate from story state. It can hide or restore the sidebar and addon panel, switch the panel position, enter full-screen mode, and treat narrow-screen navigation as a temporary drawer. Review routes can make navigation unavailable rather than merely hidden. Keyboard shortcuts use the same manager API and can receive key events relayed from the preview.
See Manager UI for the manager application, layout, navigation, and addon surfaces.
References: code/…/runtime.tsx• L31-41 code/…/index.tsx• L40-98 code/…/Preview.tsx• L65-118 code/…/layout.ts• L40-49 code/…/layout.ts• L269-352 code/…/shortcuts.ts• L197-220 code/…/shortcuts.ts• L545-614
Preview boundary
The preview is the browser realm that evaluates project annotations and story modules. It loads the story index, prepares the selected entry, and asks the configured renderer to place the component or docs page in the preview document.
PreviewWeb joins the general preview lifecycle to browser selection and view handling. It reads the initial selection and persisted args or globals, then responds to manager requests such as story selection, argument changes, global changes, rerenders, preloading, and hot updates. A story render tracks preparation, loading, rendering, play, completion, abort, and error states so the manager can show accurate progress.
The preview keeps story and docs rendering as separate view modes. It selects a story render for a story entry and a docs render for a CSF or MDX docs entry. It preserves the current content during a same-story refresh when possible, while a new story or view mode shows a preparation state. Missing entries, configuration errors, loader failures, render failures, and play-function failures become preview error views and channel events.
Before rendering, the preview combines project, component, and story annotations into a prepared story context. That context supplies parameters, args, globals, decorators, loaders, lifecycle hooks, and the play function to the renderer. Args can be mapped or filtered for the active target, while server-side documentation mode leaves second-pass type enrichment to the server service.
The preview also provides the public preview API. It exposes hooks, decorators, story composition helpers, docs context, story-store access, and channel access to project entries and addons.
See Preview runtime for story preparation, rendering, docs, and preview-side APIs.
References: code/…/Preview.tsx• L60-101 code/…/Preview.tsx• L124-186 code/…/PreviewWithSelection.tsx• L153-218 code/…/PreviewWithSelection.tsx• L327-539 code/…/PreviewWithSelection.tsx• L542-602 code/…/prepareStory.ts• L37-168 code/…/prepareStory.ts• L181-295 code/…/PreviewWeb.test.ts• L139-253 code/…/PreviewWeb.test.ts• L421-691
Shared runtime APIs
Shared APIs define the safe points where addons, project entries, and framework packages cross runtime boundaries. The manager API gives manager-side code access to navigation, state, addon registration, and channel events. The preview API gives preview-side code access to hooks, decorators, story context, docs, and story composition. The shared server and common APIs provide the configuration, preset, service, package-manager, and project-resolution contracts used before those browser APIs run.
The common package-management contract keeps project setup independent of the selected package manager. Its adapters translate dependency changes, version lookups, installation inspection, workspace rules, and registry access into one interface. This lets runtime setup work across npm, Yarn, pnpm, and Bun while retaining package-manager-specific dependency rules.
The same channel contract is available in both realms, but each realm supplies its own browser transport. This allows an addon to react to a manager action, update preview state, and report the result without direct access to the other realm’s memory.
Universal stores provide a second shared-state contract for supported runtime services. Browser channels prepare the store for the manager or preview environment. The server and non-server callers prepare their own local or supplied channel before presets run. Code that uses a shared store must therefore use the channel prepared for its realm.
References: code/…/load.ts• L22-49 code/…/index.ts• L34-57 code/…/index.ts• L5-84 code/…/JsPackageManager.ts• L108-166 code/…/JsPackageManager.ts• L207-232 code/…/NPMProxy.ts• L83-143 code/…/PNPMProxy.ts• L69-165 code/…/Yarn1Proxy.ts• L33-80 code/…/Yarn2Proxy.ts• L90-134 code/…/BUNProxy.ts• L81-151 code/…/index.ts• L1-7 code/…/channel.ts• L7-76 code/…/index.ts• L3-18 code/…/index.ts• L40-99 code/…/index.ts• L25-56 code/…/index.ts• L383-432
Inter-process channels
The channel is an event bus with one local event interface and one or more transports. A channel emits an event locally and forwards it through its transports. Browser pages use postMessage for iframe traffic. Development mode also uses WebSocket connections to reach the server and other connected clients. The browser channel prepares the universal store for either the manager or preview page and can use a configured WebSocket path.
The server channel is a one-to-many bridge. It receives events from manager, preview, and server clients, applies token and host checks, filters events by sender role, and broadcasts accepted events. The channel carries selection, args, globals, render status, index invalidation, addon, and error signals rather than component data or direct function calls.
The manager API adds target handling for iframe and composed Storybook references. This keeps events addressed to the correct preview when more than one preview is present.
This diagram shows the normal event path for a manager selection change.
sequenceDiagram
participant User
participant Manager
participant Server
participant Preview
User->>Manager: Select story
Manager->>Server: Emit selection event
Server->>Preview: Broadcast event
Preview->>Preview: Prepare and render story
Preview-->>Server: Render status event
Server-->>Manager: Broadcast status event
Manager->>User: Update workbench state
References: code/…/main.ts• L22-81 code/…/index.ts• L25-56 code/…/get-server-channel.ts• L127-170 code/…/channel.ts• L52-74
Runtime security boundary
The runtime treats the manager, preview, and server as separate communication parties. Development WebSocket connections use a runtime token. Browser embedding and message origins are checked so a local Storybook is not controlled by an unrelated page.
The security boundary matters because the manager and preview are separate browser contexts. A message that crosses that boundary must come through an accepted channel transport and must target the intended preview.
References: code/…/get-server-channel.ts• L58-99 code/…/core-common.ts• L682-710 code/…/index.ts• L41-50
Change checklist
When these files or sections are changed, remember to consider these:
- Changes to
StoryIndexGeneratoror /index.json affect both manager navigation and preview story selection. Keep index invalidation events aligned with the data they invalidate. - Changes to story glob normalization or matching must preserve relative paths, parent-directory patterns, and platform-specific path separators used by both indexing and file watching.
- Changes to channel event names or payloads must stay compatible across
manager-api, preview listeners, server sender rules, and any composed Storybook targets. - Changes to browser channel construction must preserve both iframe transport and the development WebSocket path, token, page identity, and universal-store environment.
- Changes to manager or preview entry generation must preserve the browser globals and channel setup expected before either realm renders.
- Changes to the server channel must keep token checks, origin checks, client roles, and event sender rules consistent.
- Changes to preset loading must preserve the two-stage builder discovery flow. The complete preset pass must receive the live channel used by runtime services.
- Changes to common server services must preserve one-time registration, shared story-index access, module-graph readiness, and subscription setup after the development server is ready.
- Changes to static output must keep the manager and preview assets, story index, project metadata, and any story-document summary on the same resolved configuration.
- Changes to preview selection or view-mode handling must preserve the event and error contracts used by the manager for stories, CSF docs, and MDX docs.
- Changes to manager layout or shortcut state must preserve the distinction between hidden navigation, unavailable navigation, mobile drawer state, and persisted desktop layout.
- Changes to prepared story context must preserve annotation precedence, target and conditional args, and the handoff between client-side preparation and server-side documentation data.
- Changes to the public server or common export surfaces must preserve the contracts used by callers to assemble runtimes, access story indexes, register services, resolve project configuration, and manage project dependencies.
- Changes to package-manager adapters or override parsing must preserve equivalent dependency behavior across npm, Yarn Classic, Yarn Berry, pnpm, and Bun, including workspace catalogs, root-level override sources, bundled package metadata, and maintained satellite packages.
- Changes to source-analysis helpers must preserve component paths relative to story import paths and must keep unresolved imports distinct from missing exports.
- Changes to Git change detection or module-graph status handling must preserve the distinction between changed, new, affected, and baseline-new stories.
- Changes to file-watch error handling or event batching must preserve invalidation for added, changed, and removed matching files without allowing watcher errors to stop the development server.
- Changes to index summaries must preserve the distinction between user content, examples, onboarding content, docs, play stories, and test stories used by reports.
Important failure modes
| Trigger | Consequence | Guard |
|---|---|---|
| No preview builder is resolved | The server cannot assemble the preview runtime | Fail with the missing-builder error before starting the browser surfaces |
| Story index generation fails | The manager cannot provide valid navigation and the preview cannot resolve stories | Return the index error and show the preview entry error state |
| Preview build fails after manager startup | The server may have a partial manager runtime but no usable story canvas | Bail both builders and rethrow the preview error |
| Server services are applied more than once | Service registration stops and the live server cannot complete its setup | Apply the services preset once and consume its pending subscriptions during development startup |
| Static output omits the story index or browser assets | A deployed Storybook cannot show navigation or load the preview | Write the index and shared browser assets as part of the production build |
| A story glob does not match the platform path form | Stories are missing from navigation or file edits do not trigger refresh | Normalize paths and use platform-aware glob matching for indexing and watching |
| A watcher receives an invalid interval or system watcher error | File changes are not observed, so the index can stay stale | Warn without crashing and support the configured polling fallback |
| Git is unavailable or the working directory is not a repository | Change detection cannot classify repository changes | Mark change detection unavailable while leaving the rest of the runtime available |
| The module graph is not ready when a scan starts | Story statuses can reflect a transient or incomplete reverse index | Wait for graph readiness and drain pending graph updates before scanning |
| A package-manager workspace, override source, or bundled package record is unreadable | Dependency setup can use the wrong package or version source | Keep adapter fallbacks explicit and report unresolved catalog, override, or package metadata data |
| A component export cannot be followed through a barrel | Documentation can miss the component or report the wrong source | Distinguish unreadable modules, missing exports, and namespace exports |
| Channel token or host validation fails | A client cannot join the server event bus | Reject the WebSocket upgrade |
| A client sends an event outside its role | The event is ignored and the expected state change does not occur | Enforce sender rules in the server channel |
| The runtime record is stale or exposed to other users | Tools can attach to a dead process or read a channel token | Write owner-only records and remove stale or exited instances |
| A story, docs entry, loader, or renderer fails | The preview shows an error state and emits a matching error event | Convert the failure into the preview error view and channel status |
| The manager WebSocket disconnects | The workbench can no longer control or observe the preview | Show the connection-lost notification and require a server restart and page reload |
Key files
| File | Why to read it |
|---|---|
| code/…/build-dev.ts | Shows configuration loading, preset passes, channel creation, and development runtime startup orchestration. |
| code/…/index.ts | Shows the public server boundary for builders, story indexing, channels, runtime services, and change-aware project data. |
| code/…/build-static.ts | Shows how production output assembles manager and preview assets, the story index, metadata, and build reporting. |
| code/…/load.ts | Shows how callers load a configured runtime with a local or supplied channel without starting the dev server. |
| code/…/index.ts | Shows the shared configuration, preset, package-manager, and source-analysis exports that support runtime assembly. |
| code/…/JsPackageManager.ts | Defines the project dependency contract shared by supported package managers. |
| code/…/NPMProxy.ts | Shows npm-specific dependency commands, registry access, and installation inspection. |
| code/…/PNPMProxy.ts | Shows pnpm workspace, catalog, override, and build-approval behavior. |
| code/…/Yarn1Proxy.ts | Shows the project setup contract for Yarn Classic. |
| code/…/Yarn2Proxy.ts | Shows the project setup contract for Yarn Berry and its package-age rules. |
| code/…/BUNProxy.ts | Shows Bun dependency commands, package-age rules, and compatibility with npm registry queries. |
| code/…/PackageJson.ts | Defines package metadata used to identify versions bundled by another installed package. |
| code/…/overrides.ts | Defines the normalized view of dependency override sources. |
| code/…/satellite-addons.ts | Identifies maintained Storybook packages that are outside the monorepo package set. |
| code/…/resolve-meta-component.ts | Shows how story metadata is resolved to the component source used by documentation services. |
| code/…/follow-export.ts | Defines the source-analysis contract for imports and re-exports. |
| code/…/component-path-from-story.ts | Defines stable component paths relative to the story import path. |
| code/…/subcomponents.ts | Shows how declared subcomponents are extracted for source analysis. |
| code/…/dev-server.ts | Shows how the server attaches the manager, preview, index route, and live runtime services. |
| code/…/common-preset.ts | Shows the shared preset contract for features, story indexing, channels, and channel-backed server services. |
| code/…/GitDiffProvider.ts | Shows how Git state becomes a change source and how repository watcher failures are contained. |
| code/…/change-detection-service.ts | Shows how Git changes and module-graph relationships become story statuses. |
| code/…/StoryIndexGenerator.ts | Defines the server-side contract that turns story and docs files into navigable entries and refreshable index state. |
| code/…/index-json.ts | Connects the index endpoint and channel invalidation events to story and configuration changes. |
| code/…/watch-files.ts | Defines the common file-watch boundary and its polling and error behavior. |
| code/…/watch-story-specifiers.ts | Maps configured story patterns to filtered and batched index invalidations. |
| code/…/watch-story-specifiers.test.ts | Verifies that story-file watches filter paths, batch changes, preserve add and remove state, and handle polling and watcher errors. |
| code/…/summarizeIndex.ts | Shows how the story index becomes high-level content and feature counts for reports. |
| code/…/runtime-instance-registry.ts | Shows how a running development instance is made discoverable to tools while protecting its channel credentials. |
| code/…/get-server-channel.ts | Defines the server-side bridge between browser clients and server events. |
| code/…/runtime.tsx | Shows manager channel setup and the manager browser entry point. |
| code/…/index.tsx | Shows how the manager provider, routing, state, and application are assembled. |
| code/…/Preview.tsx | Shows how manager selection and tools are mapped to the preview iframe. |
| code/…/layout.ts | Shows how manager navigation, panels, full-screen mode, and mobile layout share one state contract. |
| code/…/shortcuts.ts | Shows how manager and preview keyboard events drive navigation and focus actions. |
| code/…/Preview.tsx | Shows preview initialization, story-index loading, and manager event handling. |
| code/…/PreviewWithSelection.tsx | Shows how selection, story and docs view modes, refreshes, keyboard events, and render errors reach the preview view and channel. |
| code/…/prepareStory.ts | Shows how project, component, and story annotations become the context used by rendering. |
| code/…/StoryRender.ts | Shows the high-level story render lifecycle and status events. |
| code/…/index.ts | Shows browser channel construction, transport selection, and manager or preview environment setup. |
| code/…/main.ts | Shows the common event-bus contract used by all transports. |