Introducing a new way to review your PRs.

Read the announcement

reflex-dev / reflex

🕸️ Web apps in pure Python 🐍

View on GitHub

30 documents · Updated Nov 23, 2026

docs / frontend-runtime-package

Frontend runtime package

The reflex-frontend package is the JavaScript runtime that generated Reflex applications use in the browser. It connects generated React pages to the Python service, keeps browser and server state aligned, provides route and UI support, and supplies the build tools needed to produce the frontend. The wider runtime boundary is described in Application runtime; this page focuses on the maintained browser package within that system.

Package boundary

The package is a shared runtime source for generated applications rather than a normal application dependency. During app setup, its source is copied into the app's .web directory and compiled with generated pages. The $ import alias points generated code at that shared runtime, so a change to a runtime export can affect every generated app and separately released component package. Frontend compilation explains the surrounding compile flow.

Runtime role

The runtime gives generated code a stable browser contract. It supplies the entrypoints, React contexts, event and state connection, client-only state, browser actions, Python-like helpers, and build hooks that generated pages expect.

These responsibilities work as one path:

  • Generated pages provide app-specific components and state metadata.
  • The runtime mounts those pages through React and React Router.
  • The event loop sends user work to the backend and applies returned updates.
  • Shared helpers keep generated expressions and browser actions consistent with Python behavior.
  • Build plugins prepare the app for development and production serving.

References: packages/…/README.md• L3-23 packages/…/package.json• L1-29 packages/…/globals.d.ts• L1-25

Application entrypoints

The package supports two browser start modes. The normal entrypoint hydrates the document produced by the app build. The embed entrypoint can mount a widget into a selected host element and give it its own in-widget route space. Both modes hand control to the generated root and route manifest after React Router is ready.

The entrypoint choice changes where the app owns its page tree, not the core event and state contract. This lets a generated app run as a full page or as an embedded widget while using the same runtime services.

References: packages/…/entry.client.js• L1-8 packages/…/entry.client.embed.js• L1-63 packages/…/routes.js• L1-9

Browser runtime

The browser runtime keeps the generated UI active after the first page load. It joins React rendering, browser navigation, client storage, and the connection to the Python backend.

Event and state connection

The event loop turns generated event actions into browser work or backend events. A socket carries stateful events and state updates. The runtime queues work until a usable connection exists, adds the current route data, and drains the queue in order. Navigation creates a new load event so the backend can refresh page data for the new route.

Returned state deltas update only the known state areas. Unchanged data keeps its identity where possible, which helps React avoid work. Connection errors, state update errors, and frontend exceptions remain visible to the backend through the runtime's error path. State and events describes the matching server contract.

The main browser exchange is:

flowchart LR
    UI[Generated React UI] --> Action[Event action]
    Action --> Queue[Frontend event queue]
    Queue -->|stateful event| Socket[Socket connection]
    Socket --> Backend[Python backend]
    Backend -->|state delta or browser event| Socket
    Socket --> Update[Runtime update]
    Update --> UI

References: packages/…/state.js• L304-453 packages/…/state.js• L590-815 packages/…/state.js• L909-957 packages/…/state.js• L1047-1360 packages/…/state.js• L1603-1859

Client state

Client state is data that belongs in the browser and does not need a server round trip for each read. The runtime exposes it to React components through scoped state and exposes named global values to backend-driven browser events or other browser code.

A scope belongs to a mounted component boundary. Components in that boundary can share its value, while separate mounted boundaries can keep separate values. Global values use the shared app store and can be read or changed outside the React tree. The store uses per-value subscriptions so a change updates only the components that use that value.

The runtime also mirrors declared browser storage. Cookies, local storage, and session storage can provide initial values and receive later server updates. This makes browser persistence part of the state contract instead of an unrelated side channel.

References: packages/…/client_state.js• L1-20 packages/…/client_state.js• L123-216 packages/…/client_state.js• L219-249 packages/…/state.js• L1437-1484 packages/…/state.js• L1528-1591

React integration

The runtime provides shared React contexts that connect generated components to app data. These contexts carry state stores, event dispatch, uploads, color mode, and app metadata. The static context registry also provides selective state subscriptions and a stable event-loop bridge, so generated modules can be re-executed during hot reload without breaking provider and consumer links.

The generated context module registers app-specific values into that registry. Theme state can follow the system preference or a saved browser choice. Optional components extend this base with features such as code display and theme integration without changing the main event loop.

References: packages/…/context-registry.js• L1-92 packages/…/react-theme.js• L12-139 packages/…/radix_themes_color_mode_provider.js• L1-18 packages/…/code.js• L1-109

Browser features

The package turns generated expressions and events into common browser behavior. These features keep application code concise while preserving the framework's shared rules at the browser boundary.

Browser actions

Browser-only events handle work that does not belong on the Python service. The runtime supports navigation, storage changes, focus and value updates, downloads, script or function calls, client-state reads and writes, and file uploads. Backend events use the configured event transport, while upload work uses the upload endpoint and can report progress.

Event actions can also control default browser behavior, propagation, debounce, throttle, and temporal checks. These actions are applied before the target runs, so generated component behavior stays consistent across event sources.

File uploads are a streaming part of this browser contract. The runtime sends files and bound handler arguments to the upload endpoint, reports upload progress, and reads newline-delimited response chunks as backend event updates. It prevents a second upload with the same upload identifier, supports cancellation, forwards client and trace headers, and reports handler or network errors through the upload result.

References: packages/…/state.js• L590-815 packages/…/state.js• L861-889 packages/…/state.js• L1362-1434 packages/…/upload.js• L20-31 packages/…/upload.js• L41-79 packages/…/upload.js• L82-95 packages/…/upload.js• L100-186

Generated expression helpers

Generated JavaScript calls the helper layer for behavior that must match Python. The helpers cover truth checks, string and number operations, ranges, set operations, date comparison, JSON values, and array or object handling. They form a compatibility layer between Python declarations and JavaScript execution.

The helper layer also includes Python-compatible list ordering and small browser services such as paste support, throttling, debouncing, and streamed upload response parsing. List ordering follows Python rules for nested values and values that cannot be ordered. These helpers are part of the generated-code contract even when an app does not import them directly by name.

References: packages/…/state.js• L1861-1988 packages/…/array.js• L1-105 packages/…/set.js• L1-8 packages/…/json.js• L1-72 packages/…/datetime.js• L1-20 packages/…/helpers.test.js• L1-175 packages/…/array.test.js• L1-111

Build and delivery

The package includes the browser start code and the Node.js build hooks that shape an app's frontend output. It is compiled as part of the generated app, so build behavior is part of the runtime contract.

Build configuration

The package configures React Router for a client-rendered application and supplies Vite plugins for generated code. The optional React Compiler pass improves generated React code and keeps generated event callbacks aligned with their real inputs. The development cache-bust plugin works around Safari module caching during route and dependency changes.

The package also defines the per-app environment contract. The generated env.json supplies event, upload, health, route, transport, and version values. Window hooks provide optional telemetry and dynamic library loading without making those integrations required for every app.

References: packages/…/react-router.config.js• L1-6 packages/…/vite-plugin-react-compiler.js• L111-163 packages/…/vite-plugin-safari-cachebust.js• L32-47 packages/…/globals.d.ts• L9-50

Static delivery

Production builds can create compressed sidecar files for suitable frontend assets. A server can then return a pre-compressed file instead of compressing each response while serving the generated app. The runtime keeps this task separate from browser code so static delivery does not add browser work.

References: packages/…/compress-static.js• L1-19 packages/…/compress-static.js• L57-105

Test surface

The test surface checks both the public contract and the stateful browser behavior. It runs with Vitest and uses a browser-like environment for React and connection tests, while also importing every public module in Node to protect production prerendering.

Contract tests

The public API test records the names that generated pages and component packages can import, including the shared list-ordering helper. It also checks that runtime modules load without window or document, because production build work evaluates them in Node. The type checks use JSDoc for browser code and a separate Node configuration for build files.

References: packages/…/public_api.test.js• L1-16 packages/…/public_api.test.js• L18-117 packages/…/tsconfig.json• L1-27 packages/…/tsconfig.node.json• L1-11

Runtime behavior tests

The behavior tests protect the parts that can fail across browser, React, and backend boundaries. They cover state delta application, connection and reconnect handling, queued event behavior, client-state scope and isolation, storage behavior, Python-compatible helpers including list ordering, and URL handling for secure deployments. The package check runs lint, type checks, and the full Vitest suite.

References: packages/…/state_connection.test.js• L1-12 packages/…/state.test.js• L1-43 packages/…/client_state.test.js• L1-25 packages/…/array.test.js• L1-111 packages/…/state_https.test.js• L1-26 packages/…/package.json• L16-21

Change checklist

When these files or sections are changed, remember to consider these:

  • Keep exported runtime names aligned with generated pages and separately released component packages. Update the public API contract when a name changes.
  • Keep socket event names, state mismatch signals, client error types, and storage event names aligned with the Python constants and server handlers.
  • Keep the generated env.json fields aligned with URL building, transport choice, uploads, health checks, and route loading.
  • Keep the event queue, reconnect path, route data, and hydration behavior consistent when changing connection code.
  • Keep client-state scope rules aligned with compiler-emitted boundaries and with backend client-state get and set events.
  • Keep shared context objects, app registration, and event-loop dispatchers stable across generated-module hot reload.
  • Keep browser-safe module loading intact. Build files and browser files have different runtime globals and type-check settings.
  • Keep the embed mount target and memory route behavior aligned with generated embed manifests and host-page integration.
  • Keep compression format names aligned with the deployment server's support for pre-compressed assets.
  • Keep optional compiler and component imports optional unless their packages become required app dependencies.
  • Keep Python list-ordering rules aligned with generated comparison operators and the public helper export.
  • Keep upload form field names and streamed response framing aligned with the backend upload handler. Preserve the order of bound event arguments before file parts.
  • Keep upload identifiers, cancellation references, progress callbacks, auth headers, trace hooks, and upload endpoint paths aligned with the event and observability contracts.

Important failure modes

TriggerConsequenceGuard
A generated app uses a removed or renamed runtime exportThe app or a component package fails during buildPreserve the public export or update all generated consumers and the API test together
Browser and backend state schemas differUpdates can target missing state areas and the app may reload or show stale dataRebuild the frontend and connect it to the matching backend
A stateful event is drained while the socket is disconnectedThe event remains pending and user work does not reach the backendKeep disconnected stateful work queued until reconnect
Generated modules replace shared context objects during hot reloadProviders and consumers use different contexts and state or events stop crossing the React treeKeep the context registry static and register generated values into it
Runtime code reads browser globals during Node evaluationProduction prerender or frontend build failsGuard browser-only work and keep the Node import contract tested
Client-state scope ownership changesSeparate component instances can share values or updates can reach the wrong treePreserve outermost-scope ownership and per-slot subscriptions
Embed code uses the host URL as its routeWidget events and page-load state use the wrong pathKeep the embed memory router and mirrored widget location as one contract
env.json fields or endpoint paths drift from the backendEvents, uploads, health checks, or route requests go to the wrong serviceGenerate and consume the same environment contract
A configured compression format is unavailable in NodeProduction asset preparation stops before static servingCheck runtime support before compression and use supported formats
List comparison rules drift from Python semanticsGenerated conditions return different results for nested or mixed list valuesPreserve the helper contract and test ordered and non-orderable values
Upload argument fields or response chunks use the wrong formatThe backend cannot bind the handler args or the frontend misses streamed updatesKeep the upload field name and newline-delimited stream contract aligned
A repeated upload uses an active upload identifierThe second request is rejected or silently returns without startingKeep one controller reference per upload identifier and clear it after completion
Upload progress or stream errors are handled as successThe UI can show completion while the handler failed or the network failedDistinguish HTTP status, stream error, abort, and network error before resolving

Key files

FileWhy to read it
packages/…/README.mdExplains how the package reaches a generated app and identifies its shared runtime contract.
packages/…/entry.client.jsShows the normal browser entrypoint that hydrates the generated app.
packages/…/entry.client.embed.jsShows the embedded widget entrypoint and its separate route space.
packages/…/state.jsDefines the browser event loop, backend connection, state updates, storage sync, navigation events, and browser actions.
packages/…/client_state.jsDefines scoped and global client-only state and its React subscription model.
packages/…/context-registry.jsDefines the shared React contexts, selective state subscriptions, app registration, and stable event-loop bridge.
packages/…/upload.jsDefines file upload transport, progress reporting, streamed event updates, cancellation, and upload failure handling.
packages/…/array.jsDefines Python-compatible ordering for list values used by generated expressions.
packages/reflex-frontend/src/utils/helpers/Provides the Python-compatible helpers and small browser services used by generated code.
packages/…/vite-plugin-react-compiler.jsShows the optional build pass for generated React code.
packages/…/compress-static.jsShows how production frontend assets receive pre-compressed sidecars.
packages/…/public_api.test.jsDefines the import and Node-load contract for generated apps and component packages.
packages/…/array.test.jsProtects list ordering behavior for generated expressions, including nested and non-orderable values.
packages/…/state_connection.test.jsCovers event queue and socket lifecycle behavior at the main runtime boundary.
packages/…/client_state.test.jsCovers client-state scope, subscription, and server-render isolation behavior.