Repository navigation
reflex-base@0.12.0a1
Pre-release
Pre-release
Breaking Changes
- Session ownership is enforced by default. State access needs the browser session that owns the client token:
app.modify_stateand event enqueueing raiseSessionAuthorizationErrorfor a token that the session does not own, and unauthorized uploads return HTTP 403. Trusted server-side code passessession_token=SessionToken.SYSTEM. A tab that presents an unowned token gets a new token and fresh state. Keep the default:REFLEX_SESSION_TOKEN_MODE=warnoroffturns this protection off and is only an escape hatch for a deployment that breaks before its code is fixed. Before you deploy, setREFLEX_SECRET_KEYon every backend and route/_reflex/sessionto the backend in your reverse proxy: without them, state resets on each restart or reload. See the browser sessions guide. (#7364) on_submithandlers annotateddict(or not annotated) now receive a field name ending in[], such as therange[]a two-thumbrx.slider(name="range")submits, as the list of its values (["20", "80"]) instead of its last value ("80"). Readform_data["range[]"][-1]for the last value, or annotate the form data asrx.form.FormData, whoseform_data["range[]"]is the last value andgetlist("range[]")every value. (#7540)
Deprecations
BaseVarShadowsInheritedVarErroris deprecated, and importing it warns: nothing raises it since a substate may redeclare an inherited var. It will be removed in 1.0. (#7381)
Features
EventContext.modify_stateholds the lock on a state tree for the event, andEventContext.state_locksrecords the locks it holds: a state loaded by an event is writable only while its event holds its lock. (#7313)- Add
reflex_base.state, holding whatrx.Statebuilds on:StateNode(a node of a state tree, with dirty tracking, deltas, locking and pickling),MutableProxy, delta building and state tokens. The old import pathsreflex.istate.proxy,reflex.istate.deltaandreflex.istate.manager.tokenstill work. (#7314) - Add
Var.dispatch_valueto show a value for a state var on the frontend right away, until the backend sends one:on_click=[State.loading.dispatch_value(True), State.work]. (#7315) - Add signed browser sessions and session-bound client tokens, signed with keys from
REFLEX_SECRET_KEY(comma-separated, newest first, for rotation) and with configurable session lifetimes. WithoutREFLEX_SECRET_KEY,reflex rungenerates a temporary key, so browser sessions reset on every restart. Signed session credentials are scoped to the app name, even when apps share secret keys. (#7361) - Browser sessions end at a maximum age:
session_token_max_ageinrx.Config(seven days by default) counts from the first issue of a session, and renewal cannot extend a session past it. (#7362) - Add session ownership checks to event contexts, including chained events and streamed upload responses. See the browser session guide for rollout and deployment configuration. (#7362)
- Establish browser sessions over the WebSocket while hydration begins, then persist them through HTTP-only cookies with automatic refresh. New routing-token and freshness keys are scoped to each backend URL. Idle tabs renew their session cookies automatically; transient cookie-exchange failures retry without blocking WebSocket events, and queued uploads remain cancellable. See the browser sessions guide for configuration and migration. (#7363)
- JSON log records (
REFLEX_LOG_JSON=true) emitted inside an OpenTelemetry span now also includetrace_flags, the span's W3C trace flags as two hex digits, so a record from an unsampled span can be told apart from one that was sampled. (#7734) console.deprecate()no longer requiresreasonordeprecation_version; when either is empty, it is left out of the warning. (#8079)- Add the
Plugin.post_frontend_compilehook. It runs once a compile has written the whole frontend, and never on a dry run. A plugin can save there what only the full compile sees, and read it inpost_compileon a backend start that skips the frontend compile. See Plugin Architecture. (#8090)
Bug Fixes
- A state var declared with
dataclasses.field(...)now raises aStateValueErrorwhen the class is defined, naming the var and pointing torx.field(...), instead of the app failing to compile withTypeError: cannot pickle 'mappingproxy' object. (#7017) - Give buffered uploads their own event transaction so canceling an upload cannot cancel unrelated clients' events. (#7362)
- Compile the
%operator on number Vars with Python semantics, so the result takes the sign of the divisor (-7 % 3is now2on the frontend, not-1). (#7638) - List Var ordering comparisons (
<,<=,>,>=) now follow Python list semantics instead of comparing comma-joined strings in the browser: items compare one by one, strings by code point, dates and datetimes by value, and equal dicts as equal. For example,State.version >= [1, 9, 0]is now true for[1, 10, 0]. An optional list Var whose value isNonemakes every ordering false instead of crashing the page. (#7656) - Return the serialized fields and
dicttype when serializing a dataclass withget_type=True. (#7699) - Generate UTF-8 Python stubs and consistent stub hashes on systems using non-UTF-8 default encodings. (#7700)
ChildrenTypeErrornow names the invalid child's type instead of printing its full repr, and an event passed as a child adds a note that says to bind it to a trigger such ason_click, or toon_load. (#7706)- On Windows,
REFLEX_HOT_RELOAD_INCLUDE_PATHS,REFLEX_HOT_RELOAD_EXCLUDE_PATHSandREFLEX_HOT_RELOAD_OVERRIDE_PATHScan now be separated by;, so an absolute path is no longer split at its drive letter. A value without;is still split on:, except at a drive letter, so existing lists such asdata:libkeep working. Other platforms still use:. (#7743) - File uploads now log an update chunk that fails to parse once the upload response completes. Before, the error was logged only when the response had a
Content-Lengthheader. (#7759) - Fixed a client's events stalling for good after a long backlog of its queued events (over about a thousand) was cancelled at once; the backlog is now skipped without hitting Python's recursion limit. (#7777)
- Allow assignments to unannotated state vars initialized with empty dictionaries or tuples. (#7783)
- Fix nested
PropsBasevalues being emptied when their parent usesincludeorexcludefilters. (#7788) - Reach a backend whose
api_urlnames the IPv6 wildcard (http://[::]:8000) through the host the page was served from, as0.0.0.0already was. The browser was handed the unconnectable address. (#7794) - Stop the page freezing when the connection drops while queued events are being sent. An event that awaited JavaScript (an
rx.call_scriptorrx.call_functionwith a callback) with a state event queued behind it left the tab unresponsive if the socket closed before the script finished. (#7794) - Generate session tokens that are valid version 4 UUIDs. About half carried a reserved variant, which a strict UUID parser rejects. (#7794)
- Stop an unmounted app reconnecting to the backend when its tab becomes visible again. An embedded app that the host page had unmounted opened a new connection, as did every hot-reloaded copy of the event loop in dev mode. (#7794)
- Stop an endless loop of errors when the browser blocks site storage. The page reported each failed connection attempt by attempting another, thousands of times a second, and never showed a connection error; the failure is now recorded as one. (#7794)
- DataEditor now displays the cell value when an unsupported column type falls back to a text cell. (#7823)
rx.downloadwithdatasaves the file on iOS (Safari, other iOS browsers and installed web apps) instead of only showing it. (#7853)StringVar.split()with the default or an explicit empty separator now splits by Unicode code points, like the other string operations, instead of breaking emoji and other characters outside the Basic Multilingual Plane into surrogate halves. (#7866)- Vars typed as a parametrized generic
TypedDict(such asP[int]) can now be indexed by their keys instead of raisingVarAttributeError. (#7887) - An event handler argument annotated
set[...],frozenset[...]ortuple[...]now arrives as that type instead of alist; set elements that arrive as arrays or objects are built from the element annotation (for exampleset[tuple[int, int]]). When the elements still cannot go in a set, the argument arrives as thelistthat was sent. (#7890) - Type checkers now accept
@rx.event(...)stacked on another@rx.event, typing the handler like a single decorator does. (#7893) - String methods of an optional string var (
str | None) holdingNone, such assplit(" "),strip,lowerandcontains, no longer crash the page: the var acts as an empty string, solowergives""andcontains("a")givesFalse. Concatenation with+and f-strings still renderNoneasnull. (#7902) rx.set_focus,rx.event.blur_focusandrx.set_valuenow act on the right element when the id is built from a Var, such asrx.set_value(f"row-{item}", "")insiderx.foreach. Every row named the same ref, so each row's button acted on the last row. The three events also accept a plainVarid, such asrx.set_focus(State.target_id). (#7904)- Awaiting an event handler from a background task now behaves like the inline call: an exception the task catches is no longer also reported to the backend exception handler (no error toast), and a
supersedes=Truehandler run that finished before a newer one superseded it returns its result instead of raisingCancelledError. (#7907) - Using a backend var such as
State._secretas a component child, a typed prop (rx.el.div(title=State._secret),rx.link(href=State._secret)) or an event handler argument now raisesBackendVarFormatError, which names the var and the fix. A child used to raise aChildrenTypeErrorthat named neither, and a typed prop or event argument a generic error that printed the var's default value. Comparing a backend var or a mixin's field with a value (State._secret == "x") or truth-testing it now raises the same error, instead of a plainFalseorTruethat maderx.condalways take one branch. Fields still compare equal to themselves. (#7908) - Allow
rx.Var.rangeto use a reactive step, including a step stored in state. Omitted and zero steps retain the default stride of one, including when a reactive step becomes zero. (#7914) rx.cond(condition, client_state.set(...), None)bound to an event trigger no longer throwsTypeError: ... is not a functionwhen the condition is false: a function var whose type admitsNoneis now called with?.(), so theNonebranch is a no-op like it is for anEventSpecbranch. (#7917)- The development event-loop blocking monitor reports an event handler from an installed package once per process instead of on every event. The warning names the package and shows the stack from the handler on, without the frames that dispatch it. (#7920)
- In development, a blocking warning caused by the first import of a module now names that module and the app line that imports it, suggests importing it with the app or in a thread, and leaves Python's import machinery out of the stack. The stack is now titled "Stack when the threshold was reached", since it is one sample taken at that moment. (#7920)
- Link errors about undecorated state methods to the Explicit Event Handlers documentation. (#7936)
- ty 0.0.92 and later now type
var.to(StringVar),var.to(StringVar, str)and otherVarsubclasses passed as the output type as that subclass, as pyright does, instead ofUnknown. (#7942) ClientStateVar.global_valueandglobal_setnow work inrx.call_scriptcode, andpushaccepts a Var that reads another client state var'sglobal_value; both raisedReferenceErrorin the browser before. (#7946)rx.foreachaccepts a bound method (a classmethod or an instance method) as its render function: itscls/selfno longer counts as a render argument. Only positional parameters take the item and its index; keyword-only parameters and**kwargsnever receive the index. (#7957)- A callable passed to an event trigger gets the trigger's arguments only through its positional parameters:
lambda *args: ...gets all of them, even none, andlambda key, **kwargs: ...orlambda key, *, flag=1: ...no longer raisesTypeError. A callable with a keyword-only parameter that has no default now fails when the page is built, with an error saying how to fix it. (#7961) ClientStateVar.global_setis typed as theFunctionVarit returns, socs.global_set.call(value)type-checks without.to(FunctionVar). (#7966)passthrough_event_spectakes a union such asstr | Nonewithout a type error under ty, and every type checker types its argument asVar[Any]. Pyright used to infer one callable per member of the union. (#7967)- The development event-loop blocking monitor no longer reports time spent in garbage collection as blocking by the task it interrupts, neither against the threshold nor in the reported total. (#7968)
- Type checkers now see a call that gives an
@rx.eventhandler all of its arguments, such asState.increment(1), asEventSpec, the type it returns at runtime, instead ofEventCallback[()]. A handler annotated-> EventSpecor-> list[EventSpec]that returns such calls now type-checks. If your code annotates such a call asEventCallback[()], change the annotation toEventSpec. (#7992) constants.DefaultPage.IMAGEis now empty andconstants.Page404.IMAGEis gone: pages get no defaultog:image. (#8006)- Assigning to a state var typed with a specialized generic TypedDict (
P[str]) no longer crashes the event handler or logs a false type error. A dict that leaves out aNotRequiredkey of a TypedDict declared underfrom __future__ import annotationsno longer logs a false type error either. (#8022) StringVar.title()now title-cases like Python'sstr.title(): a word starts after any character that has no case, such as a hyphen, an apostrophe, a digit or a newline, not only after a space, so"jean-luc picard"renders asJean-Luc Picardinstead ofJean-luc Picard. (#8041)data-*andaria-*attributes keep their names when they hold an underscore, e.g.custom_attrs={"data-url_code": "en"}, instead of being rendered camel-cased asdata-urlCode. (#8056)- A failing session cookie exchange, for example behind a reverse proxy that does not forward
/_reflex/session, no longer shows a "Cannot connect to server" error while the WebSocket works. The browser console logs the failure once and names the route to check. (#8061) StringVar.capitalize()now capitalizes like Python'sstr.capitalize(): the first character takes its titlecase form, so"džemal"renders asDžemaland"ßa"asSsainstead ofDŽemalandSSa, a first character outside the BMP is capitalized whole, and a final capital sigma lower-cases toςas it does in Python. (#8071)- Bumped react-router to 8.5.3, which fixes a denial of service in server-side route discovery (GHSA-2rq8-3rm6-2w8f) and a prototype pollution in its turbo-stream deserializer (GHSA-qhgm-jj2j-75wj). (#8080)
- Apps now override
wsto 8.23.0, the transitive dependency ofsocket.io-clientthat is vulnerable to a pong-flood memory exhaustion (GHSA-37g9-w4hg-h9qr) up to 8.22.x. (#8086)
Performance
- Components re-render only when a state field they read through a state Var changes, instead of on every change to their state. (#7583)
- Shrink the shared JavaScript chunk by about 88 KB (11 KB gzipped) when
frontend_lazy_bundled_librariesis on: server-provided scripts and callbacks no longer use a directeval, so the minifier can shorten every name in that chunk. Scripts passed torx.call_scriptandrx.call_functionstill see every export ofutils/state.js(such asReflexEvent,refsandqueueEvents), plusaddEvents,socket,navigate,params,tokenand the globals; names the module does not export, such as its imports, are no longer in scope. (#7870) - Validating a list, set, tuple or dict assigned to a state var is faster: items whose type is exactly the declared item type no longer go through the full type check one by one. (#7878)
- Production builds now also pre-compress WebAssembly (
.wasm) modules, writing the same sidecars as for the text assets in everyfrontend_compression_formatsformat, so hosts that serve the sidecars send them compressed. (#7987) - Cache the serializer lookup for up to 4096 types instead of 128, so apps that serialize between 129 and 4096 distinct types no longer repeat the lookup on every state delta. (#8074)
Miscellaneous
- Move the frontend javascript into a package of its own,
packages/reflex-frontend, tested with its real npm dependencies. The wheel embeds it as the same.templates/webfiles as before. (#7794)