Frontend compilation pipeline
The frontend compilation pipeline turns a Python Reflex application into a React Router project that can run in development or produce a static deployment bundle. It evaluates pages and components, gathers the imports and browser code they need, adds shared state and app wrappers, copies assets, and writes the project files that the JavaScript build tool consumes. See the parent page Application runtime for the wider runtime model, Application lifecycle for app startup and build timing, State and events for state data used by generated code, Routing and pages for route definitions, Frontend runtime package for the browser runtime package, and Runtime foundations for shared browser and server behavior.
Compilation model
Reflex treats the application definition as the source model and the .web directory as a generated frontend workspace. A frontend compile does not send Python component objects to the browser. It evaluates those objects into JavaScript expressions and support modules, then lets the frontend tool resolve packages and create browser assets. When the current mode needs only backend page evaluation, the same entry point skips frontend output and records the page information needed by the backend.
The main inputs and outputs are:
| Input | Frontend role |
|---|---|
| App configuration | Sets the frontend path, theme, stylesheets, plugins, build options, and runtime settings. |
| Page definitions | Provide routes, page component trees, metadata, and page-load behavior. |
| Components and Vars | Describe the rendered tree, browser props, state reads, event handlers, hooks, and imports. |
| Assets | Supply files that become public browser resources. |
| Plugins | Add pages, packages, styles, static files, environment data, or compile-time transformations. |
| Generated project files | Give React Router and Vite the modules and configuration needed for development or export. |
The pipeline shares concepts with Routing and pages and State and events. Those pages explain the source concepts; this page follows their path into frontend output.
Compilation stages
The compile run is ordered so that later stages can use facts collected by earlier stages. Page routes and component trees must exist before the compiler can collect imports or write the final page modules.
flowchart LR
A[App and plugin definitions] --> B[Register and evaluate pages]
B --> C[Walk component trees]
C --> D[Collect imports hooks events and wrappers]
D --> E[Render pages and isolate reactive subtrees]
E --> F[Assemble shared roots and frontend files]
F --> G[Install frontend packages]
G --> H[Write .web project files]
H --> I[Vite and React Router development or export]
I --> J[Static build artifacts]
Application inputs
The compiler starts by applying decorated pages and registering pages supplied by configured plugins. Plugin route registration is staged before page evaluation so a plugin can add routes without changing the app's page registry halfway through a compile. The compiler then decides whether to perform a real frontend compile or only re-evaluate pages for backend use.
A real compile resets run-specific registries, collects plugin frontend dependencies, and creates one compile context for all pages. This stage also resolves the effective theme plugin and checks application-wide options. The result is a stable set of page definitions plus the global settings that control the generated project.
References: reflex/…/compiler.py• L1197-1319 reflex/…/compiler.py• L1252-1291
Page compilation
Each page definition becomes a page context. The page function is evaluated into a component tree, then the compiler walks that tree once. The ordered page plugins apply page styles, add the page's local client-state scope when needed, replace reactive parts with browser memo boundaries, and collect the imports, hooks, custom browser code, dynamic imports, refs, and app wrappers that remain relevant to the generated page.
The component tree remains the central hand-off between Python declarations and JavaScript rendering. Components provide a render description, and the page template turns that description into a default React component. Page metadata is added before rendering so the generated page carries its title and other document data. After collection, the compiler checks route conflicts and installs the compiled page roots into the app's evaluated page set.
References: reflex/…/compiler.py• L1321-1346 packages/…/compiler.py• L674-750 packages/…/compiler.py• L778-864 packages/…/templates.py• L477-513
Component tree processing
Compiler plugins can inspect or replace a component before or after its children are visited. The default pipeline applies app-level style, auto-memoizes reactive subtrees, and collects frontend artifacts after those replacements. A reactive subtree is one that carries state data, hook data, or event work that must stay in its own browser render scope. Static ID refs and event handlers with no state-dependent work do not make a subtree reactive by themselves. The compiler also walks app-wrapper subtrees to find wrappers declared inside fallbacks or other wrappers. Page-local copies protect user-owned component objects when a plugin must change children, styles, or event triggers.
The collector treats component data as a set of related browser needs rather than as isolated fields. A state read or event can require hooks and context imports. A component can also surface an app wrapper or a dynamic module. The collected result therefore describes both what the page renders and what must surround it for that render to work. Collection runs after memo replacement for the current node, while descendants of a pass-through wrapper remain available for collection.
Memo isolation has two broad roles. A snapshot boundary owns the captured subtree and keeps its state-dependent browser code inside the generated memo module. A passthrough boundary keeps its descendants in the page render while moving the boundary's own hooks and callback work into the memo module. Snapshot descendants are suppressed during the page walk so their hooks do not leak into page scope. Passthrough descendants remain visible to the walk so their imports and nested memo wrappers are still collected. The page still owns local client-state names used by memo bodies, so each page and its memo boundaries resolve the same client-state slots. Components with instance hooks inside a loop receive a local wrapper so each rendered item owns its hooks. The compiler warns when an item with such hooks uses its position as its key because item removal or reordering can attach the hooks to a different item.
References: reflex/…/compiler.py• L1032-1087 reflex/…/memoize.py• L60-227 reflex/…/memoize.py• L307-451 reflex/…/memoize.py• L453-691 packages/…/compiler.py• L286-336 packages/…/compiler.py• L457-581
Shared frontend modules
After page collection, the compiler builds modules shared by all routes. The app root combines providers and wrappers such as theme support, state support, overlays, error handling, and user-defined app wrappers. Stateful app wrappers are also isolated into memo modules so their state hooks run below the state provider rather than in the outer wrapper. A hydration fallback follows the same memo path so the root can expose it as the client loading view.
The app root also exposes the browser libraries that the compiled application may use. Core libraries can stay in the initial browser set while configured non-core libraries can load on demand. The compiler records this library set so page and wrapper code use the same names as the generated browser registry.
The document root supplies the HTML shell and head content. It adds the global stylesheet links and rejects stateful head components because the document shell cannot own browser hooks. The context module carries initial state, client-storage rules, event-loop support, color-mode defaults, and hashes for the compiled state snapshots. State compilation resolves the initial values before it writes the context and caches those same values for backend hydration diffs, so both sides use one set of defaults. Components found in initial state values also contribute their frontend imports and bundled library requirements.
Browser storage is part of this compile-time contract. A storage-typed field must declare its storage value as the default so the compiler knows its name and options. A frontend field with a string-compatible annotation is also checked when its default_factory produces a browser storage value; such a factory is rejected rather than treated as an ordinary state value. A factory that raises during this check is treated as a runtime-only factory with no declared storage.
Reactive component subtrees can become memo modules. A memo module keeps the code required by its boundary together, then the page or app root imports the generated component. Snapshot boundaries compile their captured body into the module. Passthrough boundaries compile only the boundary's own hooks, custom code, dynamic imports, and root style while leaving descendant rendering in the caller. A passthrough boundary also forwards parent props and refs to its rendered root so slot-style parents preserve the wrapped element's behavior. Memos with a safe source module are grouped in one output file that mirrors that module under .web/app_components; component or function memos without a safe source path use separate modules under .web/utils/components. Paths that differ only by case are rejected because they can collide on case-insensitive file systems.
References: reflex/…/compiler.py• L168-287 reflex/…/compiler.py• L1132-1168 reflex/…/compiler.py• L1474-1524 reflex/…/utils.py• L232-493 reflex/…/utils.py• L586-829 reflex/…/utils.py• L868-965 reflex/…/utils.py• L1093-1103 reflex/…/memoize.py• L403-451
Import and package resolution
Components declare the JavaScript libraries and symbols needed by their rendered output. The compiler merges imports from the page, app root, document root, initial state components, and generated modules. It removes duplicates, checks for conflicting names, and formats the result as JavaScript import statements.
The same collected import data also drives package installation. External library imports become frontend package requirements when their import markers allow installation. Framework-owned modules and generated .web modules stay as local aliases, while URL imports remain external references. This keeps the generated code and the package set aligned.
References: reflex/…/utils.py• L69-181 packages/…/imports.py• L20-65 reflex/…/compiler.py• L1461-1471 reflex/…/compiler.py• L1585-1614
Styles and assets
The pipeline turns app styles, plugin styles, and user stylesheets into the root stylesheet used by the frontend. Local stylesheet paths must resolve inside the app's assets directory. Supported source formats are copied or compiled into .web/styles, while URL stylesheets remain CSS imports.
The app assets directory is copied into .web/public, which makes those files available to the browser without putting them into page source. The compiler tracks the files it owns in .web/.asset-manifest.json, including a source fingerprint, so it can remove stale copies without deleting a generated or user-modified public file. rx.asset returns a browser URL and can add a content version so a changed file gets a new URL. Shared assets are exposed through the external asset area and are linked before the compile copies the asset tree.
References: reflex/…/compiler.py• L315-478 reflex/…/utils.py• L1162-1323 reflex/…/compiler.py• L1525-1527 reflex/assets.py• L23-39 reflex/assets.py• L161-172 reflex/assets.py• L204-303
Frontend project files
The .web directory is a managed project, not only a folder of page files. Initialization copies the framework web template and creates package, Vite, React Router, environment, and public-directory files. Each compile refreshes generated route configuration and the client entry when no plugin owns that entry.
The generated project uses $ as its local module alias. This lets pages refer to generated context, state, styles, public assets, and app-component modules without depending on the app's Python path. The route configuration records the frontend base path and can enable route prerendering. The compiler also writes a route manifest for the standalone production server so known SPA paths can be served separately from unknown paths. The context module is emitted as JSX so the frontend refresh transform registers its provider components; an old same-name JavaScript context file is removed before the new file is written.
References: reflex/…/frontend_skeleton.py• L451-485 reflex/…/frontend_skeleton.py• L488-530 reflex/…/frontend_skeleton.py• L533-632 packages/…/templates.py• L548-705 packages/…/imports.py• L9-18 reflex/…/utils.py• L995-1103 reflex/…/compiler.py• L1616-1637
Output assembly
The compiler collects generated files in memory before it writes them. Plugin save tasks can add files, plugin static assets can add or replace files, and plugin modify tasks can transform generated content. The final map is resolved under .web, stale route files are removed, and unchanged content is not rewritten.
Memo output has an additional cleanup record. Each successful non-dry compile records the memo files it emitted in .web/.memo-manifest.json; the next compile removes only files recorded there that are no longer needed. A dry run does not change the workspace or this manifest. This prevents old memo modules from remaining after a component or source module changes while protecting files outside the compiler's own output set.
This assembly step gives plugin output the same destination rules as framework output. It also makes collisions visible through warnings rather than silently hiding which producer supplied a file.
References: reflex/…/compiler.py• L1529-1673 reflex/…/utils.py• L1162-1217 reflex/…/utils.py• L1325-1351
Production build
A production build runs after compilation and frontend setup. The JavaScript package runner executes the project's export command, which uses React Router and Vite to transform the generated modules into static client files. The build then adds route-friendly HTML copies, lets plugins post-process the static directory, creates a 404 page, applies configured compression, and moves output under the configured frontend path.
The deployable frontend is the static directory below .web/build/client. The source modules in .web/app, .web/utils, .web/styles, and .web/public are inputs to this build; they are not the final browser bundle.
References: reflex/…/build.py• L231-301 packages/…/base.py• L23-56 reflex/app.py• L758-790
Generated artifact map
The generated workspace has a small set of important roles. Engineers usually need the role of an artifact more than its exact generated name.
| Artifact area | Purpose |
|---|---|
.web/app/routes | Route page modules generated from page definitions. |
.web/app/_document | Document shell with head and body support. |
.web/app/root | App providers, wrappers, layout, and route outlet. |
.web/utils/context | Initial state, client storage, event-loop, and color-mode context. |
.web/utils/theme | Global theme data derived from app style. |
.web/styles | Root CSS and stylesheet inputs. |
.web/public | Browser-visible app and plugin assets. |
| .web/.asset-manifest.json | Ownership and source fingerprints for app asset copies. |
.web/app_components | Memo modules mirrored from source modules. |
.web/utils/components | Memo modules that cannot use a mirrored source path. |
| .web/.memo-manifest.json | Record of memo files owned by the previous compile for safe cleanup. |
| Route manifest | Compiled route data used by the standalone production server to distinguish known SPA paths from 404 paths. |
.web/build/client | Static output produced by the production export. |
Change checklist
When these files or sections are changed, remember to consider these:
- Changes to component imports must stay consistent with package-name extraction and the generated
$alias rules. - Changes to page route naming must stay consistent with page output paths, React Router configuration, the route manifest, and stale-page cleanup.
- Changes to context exports must stay consistent with generated hooks and the imports emitted into page, app-root, and document modules.
- Changes to asset URL prefixes must stay consistent with
frontend_path, public-file copying, Vite's base path, and static export relocation. - Changes to app asset synchronization must preserve .asset-manifest.json ownership and fingerprint rules so stale cleanup does not remove plugin or user files.
- Changes to plugin route registration must preserve the staged page registry used before page evaluation and route conflict checks.
- Changes to plugin save or modify hooks must preserve the output collision and ordering rules used by the final output map.
- Changes to memo source-path rules must keep grouped mirrored module paths, the manifest paths, and the library specifiers used by page imports in agreement.
- Changes to memo cleanup must preserve the boundary between compiler-owned files in the manifest and user or plugin files in
.web. - Changes to app-wrapper or hydration-fallback assembly must preserve the provider order that lets stateful wrappers run below the state provider.
- Changes to document-root head handling must preserve the no-hooks rule and the global stylesheet links required by the HTML shell.
- Changes to passthrough memo prop or ref forwarding must preserve the generated root props and the slot-parent behavior of wrapped components.
- Changes to bundled-library loading must keep the browser registry, app-root aliases, and package installation in agreement.
- Changes to browser storage field classification must keep storage names and options available at compile time and reject unsupported factory-based declarations.
- Changes to page-local client-state collection must keep names used by page hooks and memo bodies inside the same page scope.
- Changes to loop-item memoization must keep instance hooks inside the item render scope and preserve stable-key warnings for position-keyed items.
Important failure modes
| Trigger | Consequence | Guard |
|---|---|---|
| A component uses state but the app has no state class. | The generated page cannot provide the state context required by the component. | The compile rejects the frontend output with a state-definition error. |
| Two imports use the same tag from incompatible libraries. | Generated JavaScript can bind the wrong symbol or fail to compile. | Import validation rejects the conflict before templates render. |
| A stylesheet is missing, unsupported, or outside the app assets directory. | The root stylesheet cannot represent the requested style source. | Stylesheet validation raises an error during compilation. |
| A document head component needs a hook. | The document shell cannot safely render the component. | Document-root creation rejects stateful components and hooks. |
A browser storage field uses a default_factory. | The compiler cannot reliably know the storage name and options at compile time. | Storage compilation raises VarTypeError; declare the storage value as the field default. |
| A string-compatible frontend factory returns a browser storage value. | The storage object can be mistaken for an ordinary state value. | Storage compilation detects the produced value and raises VarTypeError. |
| Two memo source modules map to the same path on a case-insensitive file system. | One memo module can overwrite another. | Memo compilation rejects the case-only path collision. |
| A loop item with lifecycle hooks or other instance hooks uses its index as its key. | Hook state can follow the list position instead of the logical item after removal or reordering. | The memoization pass warns and recommends a stable item key. |
| A plugin writes a file that another output already owns. | One generated file replaces another output. | The output assembler warns and uses the last mapped value. |
| A memo output path changes but stale-file tracking does not. | An old memo module can remain in .web and confuse later frontend imports. | The compile records emitted paths and prunes only paths from the prior memo manifest. |
| A production export fails or no JavaScript runtime is available for compression. | No trustworthy static frontend bundle is produced. | The build exits with an error instead of serving partial output. |
| A page route conflicts with an existing dynamic route shape. | React Router cannot distinguish the routes reliably. | Route validation rejects the conflicting registration. |
| The route manifest does not match the compiled page routes. | The standalone production server can return a 404 for a valid SPA path or serve a path that should be unknown. | The compiler writes the manifest from the app's current route table during output assembly. |
| The stateful-pages marker is missing, invalid JSON, or not valid UTF-8. | The backend cannot trust its shortcut and may otherwise fail before it can rebuild page state information. | The marker reader treats the missing or corrupt marker as absent and runs full page evaluation. |
Key files
| File | Why to read it |
|---|---|
| reflex/…/compiler.py | Main compile orchestration from page collection through output assembly. |
| packages/…/compiler.py | Shared page and compile contexts plus the component-walk contract. |
| reflex/…/builtin.py | Default page evaluation, client-state scope, style application, artifact collection, and plugin order. |
| reflex/…/memoize.py | Reactive subtree boundaries, loop-item hook scoping, stable-key warnings, and generated memo modules. |
| reflex/…/utils.py | Import formatting, state and browser-storage compilation, artifact paths, document helpers, memo compilation, asset ownership, passthrough prop forwarding, and stale output cleanup. |
| packages/…/templates.py | Shapes of generated page, root, context, stylesheet, and Vite files. |
| reflex/…/frontend_skeleton.py | Managed .web project setup and generated frontend configuration. |
| reflex/assets.py | Asset URLs, content versioning, and shared asset exposure. |
| reflex/…/build.py | Production export and conversion of the generated project into static artifacts. |