Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
31 commits
Select commit Hold shift + click to select a range
71e7381
feat(frontend): move the backend transport out of state.js and run ap…
benedikt-bartscher Nov 26, 2026
018f676
feat(compiler): fail the compile when an app without state imports th…
benedikt-bartscher Nov 26, 2026
3d59e0d
Merge remote-tracking branch 'upstream/main' into stateless-runtime
benedikt-bartscher Nov 26, 2026
eb7b4a1
Merge branch 'stateless-runtime' into stateless-transport-guard
benedikt-bartscher Nov 26, 2026
cb8aaf6
fix(frontend): keep browser storage events and dispatch order in the …
benedikt-bartscher Nov 26, 2026
294d8ce
fix(compiler): check only the memos an app without state renders, and…
benedikt-bartscher Nov 26, 2026
9b3d806
Merge branch 'stateless-runtime-review' into stateless-runtime
benedikt-bartscher Nov 26, 2026
e438848
Merge branch 'stateless-transport-guard-review' into stateless-transp…
benedikt-bartscher Nov 26, 2026
c1ad09d
Merge branch 'stateless-runtime' into stateless-transport-guard
benedikt-bartscher Nov 26, 2026
c1fb4ce
fix(frontend): drop temporal events in apps without state, as with th…
benedikt-bartscher Nov 26, 2026
3ea5b33
fix(compiler): check the document head of an app without state for ba…
benedikt-bartscher Nov 26, 2026
045efc1
Merge branch 'stateless-transport-guard-review' into stateless-transp…
benedikt-bartscher Nov 26, 2026
3715230
Merge branch 'stateless-runtime-review' into stateless-runtime
benedikt-bartscher Nov 26, 2026
4f8d4f8
Merge branch 'stateless-runtime' into stateless-transport-guard
benedikt-bartscher Nov 26, 2026
bed35f2
test: read isTrue and evalReactComponent from the modules that now de…
benedikt-bartscher Nov 26, 2026
8bde227
Merge branch 'stateless-runtime' into stateless-transport-guard
benedikt-bartscher Nov 26, 2026
10f7d39
fix(compiler): check the hydrate fallback of an app without state for…
benedikt-bartscher Nov 26, 2026
7a984f0
Merge branch 'stateless-transport-guard-review' into stateless-transp…
benedikt-bartscher Nov 26, 2026
a95baf1
test: compare every export statement of state.js
benedikt-bartscher Nov 26, 2026
2c64f76
Merge branch 'stateless-runtime-review' into stateless-runtime
benedikt-bartscher Nov 26, 2026
ca00354
Merge branch 'stateless-runtime' into stateless-transport-guard
benedikt-bartscher Nov 26, 2026
e56e3dc
Merge remote-tracking branch 'upstream/main' into stateless-runtime
benedikt-bartscher Nov 30, 2026
de1775c
Merge branch 'stateless-runtime' into stateless-transport-guard
benedikt-bartscher Nov 30, 2026
fc7a6e1
fix(compiler): check the styled memo bodies of an app without state f…
benedikt-bartscher Nov 30, 2026
d32fb1c
Merge branch 'main' into stateless-transport-guard
benedikt-bartscher Nov 30, 2026
c373966
fix(compiler): reach a memo of an app without state only through an i…
benedikt-bartscher Nov 30, 2026
d0e0a40
docs(news): say that apps without state drop temporal events without …
benedikt-bartscher Nov 30, 2026
3387771
docs(news): tell rx.get_upload_url's transport import apart from the …
benedikt-bartscher Nov 30, 2026
2276047
test: fail the stateless app test on uncaught page errors too
benedikt-bartscher Nov 30, 2026
e5d8247
Merge branch 'stateless-runtime' into stateless-transport-guard
benedikt-bartscher Nov 30, 2026
8d7b46b
fix(compiler): catch transport names an app without state imports thr…
benedikt-bartscher Nov 30, 2026
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
18 changes: 9 additions & 9 deletions docs/app/tests/frontend_quality.test.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -154,28 +154,28 @@ with RegistrationContext(), patch('reflex.compiler.compiler.get_config', return_
bundle_library('constructor')
print(json.dumps({'root': compile_app_root(rx.el.div('Quality'))[1], 'component': serializers.serialize(Quality.create())}))
`], {cwd: root, encoding: "utf8"}).trim().split("\n").at(-1));
const setup = new Function("window", "React", "emotion_react", "utils_context", "utils_context_registry", "utils_state", "loadFixture", "loadConstructor",
const setup = new Function("window", "React", "emotion_react", "utils_context", "utils_context_registry", "utils_state", "utils_transport", "loadFixture", "loadConstructor",
generated.root.replace(/^import .*$/gm, "")
.replace(/^export default function/gm, "function")
.replace(/^export /gm, "")
.replace('import("quality-lazy-fixture")', 'loadFixture()')
.replace('import("constructor")', 'loadConstructor()'));
// Render the component's jsx call directly, so a component returns the fixture's value.
const emotion = {jsx: (type, props) => type(props)};
const stateSource = await readFile(path.join(root, "packages/reflex-frontend/src/utils/state.js"), "utf8");
const transportSource = await readFile(path.join(root, "packages/reflex-frontend/src/utils/transport.js"), "utf8");
// Parse the complete module so nested statements cannot truncate the export.
const { parseAst } = await import(resolve("rolldown/parseAst"));
const stateModule = parseAst(stateSource);
const evaluateExport = stateModule.body.find(node => node.type === "ExportNamedDeclaration" &&
const transportModule = parseAst(transportSource);
const evaluateExport = transportModule.body.find(node => node.type === "ExportNamedDeclaration" &&
node.declaration?.declarations?.some(declaration => declaration.id.name === "evalReactComponent"));
assert(evaluateExport, "state.js exports evalReactComponent");
const { evalReactComponent: evaluate } = await import(moduleUrl(stateSource.slice(evaluateExport.start, evaluateExport.end)));
assert(evaluateExport, "transport.js exports evalReactComponent");
const { evalReactComponent: evaluate } = await import(moduleUrl(transportSource.slice(evaluateExport.start, evaluateExport.end)));
const previousWindow = globalThis.window;
const react = {quality: "same React instance"};
try {
let calls = 0;
globalThis.window = {};
setup(window, react, emotion, {}, {}, {}, async () => {calls++; return {Quality: () => 42};});
setup(window, react, emotion, {}, {}, {}, {}, async () => {calls++; return {Quality: () => 42};});
assert.equal(calls, 0);
assert.equal(window.__reflex.react, react);
assert.equal(window.__reflex["quality-lazy-fixture"], undefined);
Expand All @@ -189,7 +189,7 @@ with RegistrationContext(), patch('reflex.compiler.compiler.get_config', return_

let attempts = 0;
globalThis.window = {};
setup(window, react, emotion, {}, {}, {}, async () => {
setup(window, react, emotion, {}, {}, {}, {}, async () => {
if (++attempts === 1) throw new Error("Temporary download failure");
return {Quality: () => 43};
});
Expand All @@ -203,7 +203,7 @@ with RegistrationContext(), patch('reflex.compiler.compiler.get_config', return_
let constructorCalls = 0;
globalThis.window = {};
const constructorModule = {name: "constructor library"};
setup(window, react, emotion, {}, {}, {}, async () => ({}), async () => {constructorCalls++; return constructorModule;});
setup(window, react, emotion, {}, {}, {}, {}, async () => ({}), async () => {constructorCalls++; return constructorModule;});
await window.__reflex_load(["constructor"]);
assert.equal(constructorCalls, 1);
assert.equal(window.__reflex.constructor, constructorModule);
Expand Down
1 change: 1 addition & 0 deletions news/+stateless-transport-guard.feature.md
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
Compiling an app with `enable_state=False` now fails when a page, a memo it renders, the app root, the document head or the hydrate fallback imports from `utils/transport.js`, directly or through the re-exports of `utils/state.js` (for example through `rx.get_upload_url`), and the error names each of them and what it imports. Such code needs the backend, which the app does not have, and used to fail only in the browser.
1 change: 1 addition & 0 deletions packages/reflex-base/news/+stateless-runtime.feature.md
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
Apps with `enable_state=False` run a local event loop that applies frontend events (`rx.redirect`, `rx.call_script`, `rx.call_function`, client state, focus, value and browser storage events) in the browser, in the order they were dispatched, and never connects. Temporal events are dropped, as while the backend is down; any other event that needs the backend logs an error in the browser console instead of being dropped. `utils/state.js` now re-exports two modules: `utils/runtime.js`, with the helpers and events every app needs, and `utils/transport.js`, with the backend connection, which only apps with state use: the context module of an app without state never imports it. Imports from `utils/state.js` keep working. In an app without state, `rx.call_script` code and callbacks see the exports of `utils/runtime.js`, `addEvents`, `navigate` and `params`.
175 changes: 107 additions & 68 deletions packages/reflex-base/src/reflex_base/compiler/templates.py
Original file line number Diff line number Diff line change
Expand Up @@ -323,6 +323,65 @@ def theme_template(theme: str):
return f"""export default {theme}"""


_CLIENT_STATE_STORE = """// Dispatch updates happen outside render; useSyncExternalStore keeps reads
// consistent while notifying only consumers of the changed substate.
function createStateStore(initialState) {
const state = {};
const listeners = new Map();
const dispatchers = {};
const notify = (substateName) =>
listeners.get(substateName)?.forEach((listener) => listener());
// Hot reload passes the recompiled initial state: new substates are added,
// and existing substates gain new fields at their defaults while keeping
// their live values.
const mergeInitialState = (nextInitialState) => {
for (const [substateName, value] of Object.entries(nextInitialState)) {
const liveState = state[substateName];
if (liveState !== undefined) {
if (Object.keys(value).some((key) => !Object.hasOwn(liveState, key))) {
state[substateName] = { ...value, ...liveState };
notify(substateName);
}
continue;
}
state[substateName] = value;
dispatchers[substateName] = (delta) => {
const currentState = state[substateName];
const nextState = applyDelta(currentState, delta);
if (nextState === currentState) return;
state[substateName] = nextState;
notify(substateName);
};
notify(substateName);
}
};
mergeInitialState(initialState);

return {
dispatchers,
mergeInitialState,
getSnapshot: (substateName) => state[substateName],
subscribe: (substateName, listener) => {
let substateListeners = listeners.get(substateName);
if (!substateListeners) {
substateListeners = new Set();
listeners.set(substateName, substateListeners);
}
substateListeners.add(listener);
return () => substateListeners.delete(listener);
},
};
}

function ClientStateProvider({ children }) {
const [store] = useState(() => createStateStore(initialState));
useEffect(() => store.mergeInitialState(initialState), [store, initialState]);
return createElement(StateStoreProviders, { children, store });
}

"""


def context_template(
*,
is_dev_mode: bool,
Expand Down Expand Up @@ -457,8 +516,40 @@ def context_template(
else ""
)

# Without state the app never connects, so nothing here imports
# utils/transport.js and the build leaves it out.
if state_name:
runtime_imports_str = (
f'import {{ ReflexEvent, refs }} from "$/{constants.Dirs.STATE_PATH}"\n'
"import { applyDelta, hydrateClientStorage, useEventLoop, warmUpTransport } "
f'from "$/{constants.Dirs.TRANSPORT_PATH}"'
)
event_loop_str = """ const dispatch = useContext(DispatchContext)
const [addEventsLocal, connectErrors] = useEventLoop(
dispatch,
initialEvents,
clientStorage,
)"""
warm_up_str = """
warmUpTransport();
"""
client_state_store_str = _CLIENT_STATE_STORE
state_provider_str = """export const StateProvider =
typeof document === "undefined" ? ServerStateProvider : ClientStateProvider;"""
else:
runtime_imports_str = (
f'import {{ refs, useLocalEventLoop }} from "$/{constants.Dirs.STATE_PATH}"'
)
event_loop_str = (
""" const [addEventsLocal, connectErrors] = useLocalEventLoop()"""
)
warm_up_str = ""
client_state_store_str = ""
state_provider_str = """// Without state the client never applies a delta either.
export const StateProvider = ServerStateProvider;"""

return rf"""import {"React, " if disable_react_owner_stacks else ""}{{ useContext, useMemo, useState, createElement, useEffect }} from "react"
import {{ applyDelta, ReflexEvent, hydrateClientStorage, useEventLoop, refs }} from "$/utils/state"
{runtime_imports_str}
import {{ ColorModeContext, UploadFilesContext, DispatchContext, EventLoopContext, StateStoreContext, registerApp, eventLoop }} from "$/utils/context-registry"
import {{ jsx }} from "@emotion/react";
{disable_owner_stacks_str}
Expand Down Expand Up @@ -488,7 +579,7 @@ def context_template(
isDevMode,
defaultColorMode,
}});

{warm_up_str}
export function addEvents(events, args, event_actions) {{
return eventLoop.addEvents(events, args, event_actions);
}}
Expand Down Expand Up @@ -532,12 +623,7 @@ def context_template(
}}

export function EventLoopProvider({{ children }}) {{
const dispatch = useContext(DispatchContext)
const [addEventsLocal, connectErrors] = useEventLoop(
dispatch,
initialEvents,
clientStorage,
)
{event_loop_str}
// Publish the dispatchers so JSX literals constructed outside the
// React-tree path (e.g. ``ErrorBoundary.onError``) can call ``addEvents``.
eventLoop.addEvents = addEventsLocal;
Expand All @@ -553,70 +639,14 @@ def context_template(
);
}}

// Dispatch updates happen outside render; useSyncExternalStore keeps reads
// consistent while notifying only consumers of the changed substate.
function createStateStore(initialState) {{
const state = {{}};
const listeners = new Map();
const dispatchers = {{}};
const notify = (substateName) =>
listeners.get(substateName)?.forEach((listener) => listener());
// Hot reload passes the recompiled initial state: new substates are added,
// and existing substates gain new fields at their defaults while keeping
// their live values.
const mergeInitialState = (nextInitialState) => {{
for (const [substateName, value] of Object.entries(nextInitialState)) {{
const liveState = state[substateName];
if (liveState !== undefined) {{
if (Object.keys(value).some((key) => !Object.hasOwn(liveState, key))) {{
state[substateName] = {{ ...value, ...liveState }};
notify(substateName);
}}
continue;
}}
state[substateName] = value;
dispatchers[substateName] = (delta) => {{
const currentState = state[substateName];
const nextState = applyDelta(currentState, delta);
if (nextState === currentState) return;
state[substateName] = nextState;
notify(substateName);
}};
notify(substateName);
}}
}};
mergeInitialState(initialState);

return {{
dispatchers,
mergeInitialState,
getSnapshot: (substateName) => state[substateName],
subscribe: (substateName, listener) => {{
let substateListeners = listeners.get(substateName);
if (!substateListeners) {{
substateListeners = new Set();
listeners.set(substateName, substateListeners);
}}
substateListeners.add(listener);
return () => substateListeners.delete(listener);
}},
}};
}}

function StateStoreProviders({{ children, store }}) {{
{client_state_store_str}function StateStoreProviders({{ children, store }}) {{
return createElement(
StateStoreContext,
{{ value: store }},
createElement(DispatchContext, {{ value: store.dispatchers }}, children),
);
}}

function ClientStateProvider({{ children }}) {{
const [store] = useState(() => createStateStore(initialState));
useEffect(() => store.mergeInitialState(initialState), [store, initialState]);
return createElement(StateStoreProviders, {{ children, store }});
}}

// The server renders once and never applies a delta, so it only reads the
// initial state.
const serverStateStore = {{
Expand All @@ -629,8 +659,7 @@ def context_template(
return createElement(StateStoreProviders, {{ children, store: serverStateStore }});
}}

export const StateProvider =
typeof document === "undefined" ? ServerStateProvider : ClientStateProvider;"""
{state_provider_str}"""


def component_template(component: Component):
Expand Down Expand Up @@ -892,9 +921,13 @@ def vite_config_template(
react_compiler_plugin = " reactCompiler(),\n" if react_compiler else ""
return rf"""import {{ fileURLToPath, URL }} from "url";
import {{ reactRouter }} from "@react-router/dev/vite";
import {{ defineConfig }} from "vite";
import {{ defineConfig, normalizePath }} from "vite";
import safariCacheBustPlugin from "./vite-plugin-safari-cachebust.js";
{react_compiler_import}
const transportModule = normalizePath(
fileURLToPath(new URL("./utils/transport.js", import.meta.url)),
);

// Ensure that bun always uses the react-dom/server.node functions.
function alwaysUseReactDomServerNode() {{
return {{
Expand Down Expand Up @@ -970,6 +1003,12 @@ def vite_config_template(
cssMinify: {"true" if minify else "false"},
sourcemap: {"true" if sourcemap is True else "false" if sourcemap is False else repr(sourcemap)},
rollupOptions: {{
// utils/transport.js runs nothing when it loads, so an app that never
// calls into it (one without state) builds without it and socket.io.
// utils/state.js re-exports it, which would keep it otherwise.
treeshake: {{
moduleSideEffects: (id) => id !== transportModule,
Comment thread
benedikt-bartscher marked this conversation as resolved.
Resolved
}},
onwarn(warning, warn) {{
if (warning.code === "EVAL" && warning.id && warning.id.endsWith("state.js")) return;
warn(warning);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -313,7 +313,7 @@ def evaluate_component(js_string: Var[str]) -> Var[Component]:
merge_var_data=VarData.merge(
VarData(
imports={
f"$/{constants.Dirs.STATE_PATH}": [
f"$/{constants.Dirs.TRANSPORT_PATH}": [
imports.ImportVar(tag="evalReactComponent"),
],
"react": [
Expand Down
4 changes: 3 additions & 1 deletion packages/reflex-base/src/reflex_base/constants/base.py
Original file line number Diff line number Diff line change
Expand Up @@ -31,8 +31,10 @@ class Dirs(SimpleNamespace):
EXTERNAL_APP_ASSETS = "external"
# The name of the utils file.
UTILS = "utils"
# The name of the state file.
# The module compiled code imports the runtime from.
STATE_PATH = UTILS + "/state"
# The backend connection, which only apps with state load.
TRANSPORT_PATH = UTILS + "/transport"
# The name of the components file, where memos that can't be mirrored to a
# user module (``__main__``, unsafe names) get one file per memo.
COMPONENTS_PATH = UTILS + "/components"
Expand Down
4 changes: 2 additions & 2 deletions packages/reflex-base/src/reflex_base/constants/event.py
Original file line number Diff line number Diff line change
Expand Up @@ -51,7 +51,7 @@ class SocketEvent(SimpleNamespace):
EVENT = "event"
CLIENT_ERROR = "client_error"
# Sent on connect when the frontend was compiled for another state tree
# (must match STATE_MISMATCH_EVENT in packages/reflex-frontend/src/utils/state.js).
# (must match STATE_MISMATCH_EVENT in packages/reflex-frontend/src/utils/transport.js).
STATE_MISMATCH = "state_mismatch"

def __str__(self) -> str:
Expand All @@ -68,7 +68,7 @@ class ClientErrorType(SimpleNamespace):

The backend receives them via the client_error socket event, and the
connection banners read them from the connection errors.
Must match the ERROR_TYPE_* constants in packages/reflex-frontend/src/utils/state.js.
Must match the ERROR_TYPE_* constants in packages/reflex-frontend/src/utils/transport.js.
"""

DISPATCH_MISSING = "dispatch_function_missing"
Expand Down
1 change: 1 addition & 0 deletions packages/reflex-base/src/reflex_base/registry.py
Original file line number Diff line number Diff line change
Expand Up @@ -34,6 +34,7 @@ def _default_bundled_libraries() -> list[str]:
f"$/{constants.Dirs.CONTEXTS_PATH}",
f"$/{constants.Dirs.UTILS}/context-registry",
f"$/{constants.Dirs.STATE_PATH}",
f"$/{constants.Dirs.TRANSPORT_PATH}",
Comment thread
benedikt-bartscher marked this conversation as resolved.
Resolved
]


Expand Down
2 changes: 1 addition & 1 deletion packages/reflex-base/src/reflex_base/utils/form.py
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,7 @@
]

# Wire key wrapping a form's ordered ``[name, value]`` entries; must match
# ``FORM_DATA_ENTRIES_KEY`` in ``state.js``.
# ``FORM_DATA_ENTRIES_KEY`` in ``runtime.js``.
FORM_DATA_ENTRIES_KEY = "__reflex_form_data__"

# Suffix of field names that submit a list, like the ``range[]`` of a slider.
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
`rx.get_upload_url` imports `getBackendURL`, and the connection banner `getBackendURL` and `isBackendDisabled`, from `$/utils/transport`, the backend connection that only apps with state load; `$/utils/state` still re-exports both.
Original file line number Diff line number Diff line change
Expand Up @@ -70,7 +70,7 @@ def create(cls) -> Var:
_var_data=VarData(
imports={
"$/env.json": [ImportVar(tag="env", is_default=True)],
f"$/{Dirs.STATE_PATH}": [ImportVar(tag="getBackendURL")],
f"$/{Dirs.TRANSPORT_PATH}": [ImportVar(tag="getBackendURL")],
},
),
_var_type=WebsocketTargetURL,
Expand Down Expand Up @@ -346,7 +346,7 @@ def create(cls, **props) -> Component:
"useEffect(() => { setBackendDisabled(isBackendDisabled()); }, []);": None,
},
imports={
f"$/{constants.Dirs.STATE_PATH}": [
f"$/{constants.Dirs.TRANSPORT_PATH}": [
ImportVar(tag="isBackendDisabled")
],
},
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -166,7 +166,7 @@ def get_upload_dir() -> Path:
_js_expr="getBackendURL(env.UPLOAD)",
_var_data=VarData(
imports={
f"$/{Dirs.STATE_PATH}": "getBackendURL",
f"$/{Dirs.TRANSPORT_PATH}": "getBackendURL",
Comment thread
benedikt-bartscher marked this conversation as resolved.
Resolved
"$/env.json": ImportVar(tag="env", is_default=True),
}
),
Expand Down
Loading