Protocol Structure
Overview¶
ReactPy renders on the server and paints in the browser. A single websocket carries four message types: the server sends "layout-update" patches, the client sends "layout-event" interactions, and a handler which wants to read the browser goes back and forth over "event-proxy-request" / "event-proxy-response".
server --{"type": "layout-update", "path": ..., "model": ...}---------------> client
server <--{"type": "layout-event", "target": ..., "data": [...]}------------ client
server --{"type": "event-proxy-request", "eventId": ..., "path": ...}-------> client
server <--{"type": "event-proxy-response", "requestId": ..., "value": ...}- client
The last two are new, and they change what an event is. Nothing about the DOM event is serialized at all: the client keeps the live object in a registry of its own and sends the server a handle. What the server can do with that handle — and what happens when the browser never answers — is the subject of The event proxy round trip.
The connection¶
Every mounted component opens exactly one websocket. The client builds it from the pathPrefix and componentPath it was handed at mount time (static/index.js, mountReactPy):
ws://<host><pathPrefix><componentPath>?path=<page path>&qs=<page query string>
With the default REACTPY_PATH_PREFIX of "/reactpy/" and a component registered as "main.counter/", mounting on /page?tab=1 opens:
ws://127.0.0.1:8000/reactpy/main.counter/?path=%2Fpage&qs=%3Ftab%3D1
Two things about that URL are load-bearing:
-
The trailing slash after the dotted path is required. The server matches the websocket path against
^{path_prefix}(?P<dotted_path>[a-zA-Z0-9_.]+)/$which ends in
/$. Without the slash the route never matches, the request falls through to your own ASGI app, and the handshake is refused. Verified from a page:ws://…/reactpy/main.counter/?path=/opens,ws://…/reactpy/main.counter?path=/fails withUnexpected response code, and the console logs[ReactPy] Failed to connect!. -
pathandqsare how the component learns its URL. ReactPy runs on the server, where the browser'slocationdoes not exist. The client copieswindow.location.pathnameintopathandwindow.location.searchintoqs; the server parses them back out (executors/asgi/middleware.py,_location_from_websocket_query_string) into theLocationthatuse_location()returns. They are percent-encoded and carried in the websocket's own query string, so a server that normalises the handshake URL cannot silently rewrite them.
Reconnection does not re-read the mount
When the socket drops, the client waits and reconnects. Each attempt refreshes path and qs from the current page, but it never re-reads componentPath or the connect options — those were captured when the element mounted. A client-side navigation that changes which component belongs on the page needs a fresh mount, not a reconnect.
The client retries with exponential backoff: REACTPY_RECONNECT_INTERVAL (750 ms) times REACTPY_RECONNECT_BACKOFF_MULTIPLIER (1.25) per attempt, capped at REACTPY_RECONNECT_MAX_INTERVAL (60 s), for REACTPY_RECONNECT_MAX_RETRIES (150) tries. Those are arguments to mountReactPy(...); see ReactPyMiddleware for the bootstrap that emits them.
The server-to-client message¶
One message type goes down the wire. Its keys are fixed (reactpy.types.LayoutUpdateMessage):
| Key | Value | Meaning |
|---|---|---|
"type" | "layout-update" | Always this literal. |
"path" | str | A JSON Pointer into the client's copy of the model. "" means replace everything. |
"model" | dict | The value to place at that pointer. |
The model is JSON, not a VdomDict. Six key names are legal (reactpy/types.py, ALLOWED_VDOM_KEYS), and only tagName is required:
| Key | Value | Notes |
|---|---|---|
"tagName" | str | The DOM tag, or "" for a wrapper element. |
"children" | list | Nested models or plain strings. |
"attributes" | dict | Sent to the client as written, and written to the DOM essentially verbatim. Two ReactPy-specific exceptions: key is read for reconciliation and consumed, never becoming an attribute, and _reactpy_ack_seq is deleted by the client before render. |
"eventHandlers" | dict | Handler name to target spec, described below. |
"inlineJavaScript" | dict | Handler name to JavaScript source string. |
"importSource" | dict | Marks an element as coming from a JavaScript module. |
Any other key name is rejected by VdomDict while the element is being built (reactpy/types.py):
ValueError: Invalid keys: {'bogus'}.
The wire schema in core/vdom.py, VDOM_JSON_SCHEMA is a looser thing: it lists these six plus "error" (which the layout injects when a component raises), and it is only consulted when REACTPY_CHECK_VDOM_SPEC or REACTPY_DEBUG is on.
Here is a real mount message for a counter, captured off the wire:
{
"type": "layout-update",
"path": "",
"model": {
"tagName": "",
"children": [
{
"tagName": "",
"children": [
{
"tagName": "",
"children": [
{
"tagName": "div",
"children": [
{"tagName": "h1", "children": ["count is 0"]},
{
"tagName": "button",
"eventHandlers": {
"onClick": {
"target": "/0/0/0/1:onClick",
"preventDefault": false,
"stopPropagation": false
}
},
"children": ["Add"]
}
]
}
]
}
]
}
]
}
}
Wrapper elements¶
Read from the top, that model is three elements with "tagName": "" before the div appears. ReactPy needs somewhere to put a component's output that is not itself a DOM node, and it does not reuse your tag for the purpose.
Do not depend on how many there are. The count is an implementation detail that shifts with structure: the same component produced one wrapper rendered bare through Layout, and three behind the ASGI executor's context provider. Never index the tree by position, and never assume the root has a tag name. The client renders a wrapper as a fragment, so it costs you nothing on screen.
Patches, not re-renders¶
The server does not resend the tree. When only an inner component's state changes, it sends the subtree rooted where that component renders:
{
"type": "layout-update",
"path": "/children/0/children/0",
"model": {
"tagName": "",
"children": [
{
"tagName": "div",
"children": [
{"tagName": "h1", "children": ["count is 1"]},
{
"tagName": "button",
"eventHandlers": {
"onClick": {
"target": "/0/0/0/1:onClick",
"preventDefault": false,
"stopPropagation": false
}
},
"children": ["Add"]
}
]
}
]
}
}
That is the whole reply to a click: one-third the depth of the mount, and the only text that changed is inside it. The pointer indexes the model, and path: "" replaces the root — which is what a state change in the topmost component produces.
A patch replaces rather than merges, so whatever subtree it carries is complete: keys you would expect to be sticky, eventHandlers among them, are resent inside it. Nothing is deleted by a patch; a smaller subtree simply arrives with fewer children.
Errors arrive as a model¶
A component that raises during render does not kill the socket. The layout sends an element whose tagName is empty and whose error is the message, which the client prints in a <pre> in place of the component:
{
"type": "layout-update",
"path": "",
"model": {
"tagName": "",
"error": "ValueError: Expected a VDOM element dict, not {'noTag': True}"
}
}
The schema ties the two together: when error is present, tagName must be empty. Without REACTPY_DEBUG=1 the same element carries "error": "" — an empty string, which the client renders as nothing, so the component silently disappears instead of showing a blank box.
The client-to-server message¶
One message type goes up (reactpy.types.LayoutEventMessage):
| Key | Value | Meaning |
|---|---|---|
"type" | "layout-event" | Always this literal. |
"target" | str | The handler's target, copied from the model. |
"data" | list | The arguments for the handler. Usually one event handle. |
"seq" | int | Optional. A client-assigned counter, per element. |
A real click on the button above:
{
"type": "layout-event",
"target": "/0/0/0/1:onClick",
"data": [{"__reactpy_event__": {"id": "lzk4q1-0"}, "type": "click"}],
"seq": 1
}
How data is built¶
The client does not serialize the DOM event. It stores the live object in a registry and sends a handle — {"__reactpy_event__": {"id": ...}} — plus "type", the one plain value the client attaches because the server needs it to name the event and it is too cheap to be worth a round trip (vdom.tsx). Anything else the handler wants is fetched, per property, over the proxy messages described below.
That replaced the old event-to-object package, which walked the event and its target: enumerable properties, plus value, checked, files, type and name read off the element even though they are accessors, plus dataset, plus every named control of a form on submit. A single <input> used to put the whole element on the wire — around ninety keys, of which a handler reads one. What goes over the wire for an event now is a handle and a type: on the order of a hundred and fifty bytes.
The consequence for you: the second element of data is whatever the event was dispatched with, and the first is the handle — a dict of the marker and nothing but the id, never a copy of the event. Handlers are still free to take more than one argument — vdom.tsx builds the list from the event plus any extra values the dispatch supplied — so index data positionally rather than counting on a specific key surviving.
Unpacking, and why the two handler forms differ¶
Layout._process_event_queue turns data into arguments and calls the handler — but not the same way for both kinds of handler (core/events.py, to_event_handler_function):
function(*data) # a plain coroutine: the list is unpacked
function(data) # an EventHandler: the list itself
So async def f(event) receives the event when passed directly, while async def f(data) must index into the list once wrapped in EventHandler. Converting a working handler just to add prevent_default breaks it in a way the traceback does not explain. Both forms are coroutines: EventHandler.__init__ and to_event_handler_function each run the value through check_is_async_handler, so a sync function or a lambda raises at element-build time. Common Props shows both shapes side by side.
The event proxy round trip¶
A handler which reads await event.target.value makes the server ask the browser. Layout.set_event_proxy_sender wires the backend to the connection, and the request that goes down is one per property (_event_proxy.py):
{
"type": "event-proxy-request",
"requestId": "f5a9b645f0a145e984b7c2d8e19f753c",
"eventId": "lzk4q1-0",
"path": ["target", "value"],
"call": false,
"args": [],
"reply": true,
"maxDepth": 10
}
The two ids come from different sides and mean different things. "requestId" is a fresh uuid4().hex per request, minted by the server so it can match the answer to whoever asked. "eventId" is the client's own registry key for the object behind the handle — an opaque string such as "lzk4q1-0" from EventProxyRegistry.register, never a handler target — so build it from the handle you were given and do not try to guess one.
The client answers with the value, or with a failure it can name:
{
"type": "event-proxy-response"