Datastar

The Python half of the Datastar browser client.

stario.datastar is the Python side of the Datastar browser client. You emit data-* attributes with data, write @ actions with at, read what the page sent with read_signals, and push updates with SSE. Attribute names and client behaviour are Datastar’s; the upstream reference is the authority on those. This page is the Python surface.

from stario.datastar import SSE, FileSignal, ModuleScript, at, data, read_signals

Stario passes signal names to Datastar unchanged — myCount, my_count, and my-count are all valid. A dot is a nested path: ui.open is {ui: {open: ...}} in the signal object.

Loading the client#

ModuleScript() returns the <script type="module"> that loads Datastar. Put it in <head>. It defaults to a pinned CDN build. Pass src= to self-host, which you should do in production.

ModuleScript(src='https://cdn.jsdelivr.net/gh/starfederation/datastar@v1.0.5/bundles/datastar.js')#

Load the Datastar client as a module script.

from stario.datastar import ModuleScript
from stario.markup import html as h
 
h.Head(ModuleScript())

Attributes#

data is the stock DatastarAttributes instance. Each method returns an Attrs fragment: pre-rendered attribute text you pass to a tag like any other attribute, before the children.

from stario import Route
from stario.datastar import at, data
from stario import h
 
ADD = Route("POST /cart")
 
h.Button(data.on("click", at.post(ADD.href())), "Add")
h.Input(data.bind("email"), {"type": "email"})

Singular helpers (attr, class_, style, signal, computed) set one key. Plural helpers (attrs, classes, styles, signals, computeds) set several at once. Options use None to omit a key and let the client apply its default.

A custom Datastar bundle with another prefix needs another instance: DatastarAttributes("data-star-").

Hold state#

Signals are the page’s state. signals sets several, with if_missing=True to keep values the client already holds. bind ties a form field to a signal in both directions. computed derives one signal from others. ref names an element so expressions can reach it. A name with a leading underscore (_menu_open) is a Datastar local signal: the browser does not send it, so it is missing from read_signals.

DatastarAttributes.signals(payload, *, if_missing=False)#

Patch several signals.

Keys are sent as JSON object keys, so any signal name works. A dotted key is a nested path — {"ui.open": True} sets $ui.open. Values are JSON values, not JavaScript: {"name": "Bob"} is the text Bob. Values may be any Mapping or Sequence (a list[str] variable, a tuple), sent as JSON objects and arrays.

data.signals({"count": 0, "open": False})
# Attrs(" data-signals='{"count":0,"open":false}'")

DatastarAttributes.signal(name, expression, *, if_missing=False)#

Deprecated: patch one signal from a Datastar expression.

expression is JavaScript, unlike the values of data.signals(), so data.signal("name", "Bob") reads a variable named Bob. Write data.signals({"name": "Bob"}) for a value. Removed in 6.0.

DatastarAttributes.bind(signal_name, *, prop=None, event=None)#

Two-way bind an element value to a signal.

data.bind("email")
# Attrs(' data-bind="email"')
 
data.bind("isChecked", prop="checked", event="change")
# Attrs(' data-bind__prop.checked__event.change="isChecked"')

DatastarAttributes.computed(key, expression)#

Create one computed signal from a reactive expression.

expression is JavaScript evaluated in the browser — never pass user-supplied text; use a signal reference or literal().

data.computed("fullName", "$first + $last")
# Attrs(' data-computed="{'fullName':() =&gt; ($first + $last)}"')

DatastarAttributes.computeds(mapping)#

Create several computed signals in one data-computed object.

Values are JavaScript expressions evaluated in the browser — never pass user-supplied text; use a signal reference or literal(). Dotted keys merge into one nested object; using a name both as a signal and as a path prefix raises StarioError.

data.computeds({"fullName": "$a", "ui.label": "$b"})
# Attrs(' data-computed="{'fullName':() =&gt; ($a),'ui':{'label':() =&gt; ($b)}}"')

DatastarAttributes.json_signals(*, include=None, exclude=None, terse=False)#

Render signals as JSON text.

data.json_signals()
# Attrs(' data-json-signals')
 
data.json_signals(include=["email", "password"], terse=True)
# data-json-signals__terse="{'include':'^(?:email|password)(?:\\.|$)'}"

DatastarAttributes.ref(signal_name)#

Store the current element in a signal.

data.ref("searchInput")
# Attrs(' data-ref="searchInput"')

Show state#

These bind an element’s text, visibility, classes, styles, or attributes to an expression. indicator makes a boolean signal true while a request from this element is in flight; read that signal through attr, class_, or show.

DatastarAttributes.text(expression)#

Bind text content to a Datastar expression.

data.text("$greeting")
# Attrs(' data-text="$greeting"')

DatastarAttributes.show(expression)#

Show or hide an element from a boolean expression.

data.show("$error != null")
# Attrs(' data-show="$error != null"')

DatastarAttributes.class_(name, expression)#

Toggle one CSS class from a reactive expression.

data.class_("hidden", "!$expanded")
# Attrs(' data-class:hidden="!$expanded"')

DatastarAttributes.classes(mapping)#

Toggle several CSS classes from a mapping of expressions.

data.classes({"loading": "$pending"})
# Attrs(' data-class="{'loading':$pending}"')

DatastarAttributes.style(prop, expression)#

Set one inline style property from a reactive expression.

data.style("width", "$pct + '%'")
# Attrs(' data-style:width="$pct + '%'"')

DatastarAttributes.styles(mapping)#

Set several inline style properties from expressions.

data.styles({"opacity": "$visible ? '1' : '0'"})
# Attrs(' data-style="{'opacity':$visible ? '1' : '0'}"')

DatastarAttributes.attr(key, expression)#

Set one HTML attribute from a reactive expression.

expression is JavaScript evaluated in the browser — never pass user-supplied text; use a signal reference or literal().

data.attr("title", "$item.label")
# Attrs(' data-attr:title="$item.label"')

DatastarAttributes.attrs(mapping)#

Set several HTML attributes from a mapping of expressions.

Values are JavaScript expressions evaluated in the browser — never pass user-supplied text; use a signal reference or literal().

data.attrs({"open": "$sidebarOpen"})
# Attrs(' data-attr="{'open':$sidebarOpen}"')

DatastarAttributes.indicator(signal_name)#

Track in-flight fetch state in a signal.

data.indicator("saving")
# Attrs(' data-indicator="saving"')

React to events#

on runs an expression on a DOM event; the expression is usually an at.* action. init runs once when the element mounts, which is where a page opens its live stream. effect re-runs when the signals it reads change. The on_* helpers cover intersection, intervals, and signal patches.

DatastarAttributes.on(event, *statements, expression=None, once=False, passive=False, capture=False, delay=None, debounce=None, throttle=None, view_transition=False, window=False, document=False, outside=False, prevent=False, stop=False, case='kebab', target=None)#

Listen for an event and run the statements in order.

data.on("click", at.get("/cart/count"))
# Attrs(' data-on:click="@get('/cart/count')"')
 
data.on("submit", at.post("/rename"), "$_edit = false", prevent=True)
# Attrs(' data-on:submit__prevent="@post('/rename'); $_edit = false"')
 
data.on("click", "$open = false", outside=True)
# Attrs(' data-on:click__outside="$open = false"')
 
data.on("input", at.get("/search"), debounce="300ms")
# Attrs(' data-on:input__debounce.300ms="@get('/search')"')

Modifiers have Datastar’s names: window, document and outside pick where the listener sits (one at most). target= is the deprecated spelling of the same three.

DatastarAttributes.init(*statements, expression=None, delay=None, view_transition=False)#

Run statements when the element initializes.

data.init("setup()")
# Attrs(' data-init="setup()"')
 
data.init("setup()", delay="200ms", view_transition=True)
# Attrs(' data-init__delay.200ms__viewtransition="setup()"')

DatastarAttributes.effect(*statements, expression=None)#

Run statements when the element initializes and when a signal they read changes.

data.effect("el.focus()")
# Attrs(' data-effect="el.focus()"')

DatastarAttributes.on_intersect(*statements, expression=None, threshold=None, once=False, exit=False, delay=None, debounce=None, throttle=None, view_transition=False)#

React to viewport intersection.

data.on_intersect("load()", threshold=0.25, once=True, view_transition=True)
# Attrs(' data-on-intersect__threshold.25__once__viewtransition="load()"')

DatastarAttributes.on_interval(*statements, expression=None, duration='1s', leading=False, view_transition=False)#

Run statements on an interval.

data.on_interval("tick()")
# Attrs(' data-on-interval="tick()"')
 
data.on_interval("tick()", duration="2s", leading=True)
# Attrs(' data-on-interval__duration.2s.leading="tick()"')

DatastarAttributes.on_signal_patch(*statements, expression=None, delay=None, debounce=None, throttle=None, include=None, exclude=None)#

React to signal patches.

data.on_signal_patch("save()", debounce="500ms", include=["draft"])
# data-on-signal-patch__debounce.500ms="save()"
# data-on-signal-patch-filter="{'include':'^(?:draft)(?:\\.|$)'}"

Control the morph#

When the server patches HTML, Datastar morphs it into the live tree. These attributes tell the morph to leave an element alone or to keep one attribute as the browser has it.

DatastarAttributes.ignore(self_only=False)#

Skip Datastar processing for this element or subtree.

data.ignore()
# Attrs(' data-ignore')
 
data.ignore(self_only=True)
# Attrs(' data-ignore__self')

DatastarAttributes.ignore_morph()#

Prevent backend patches from morphing this subtree.

data.ignore_morph()
# Attrs(' data-ignore-morph')

DatastarAttributes.preserve_attr(attrs)#

Preserve selected attributes during DOM morphing.

data.preserve_attr(["data-testid", "id"])
# Attrs(' data-preserve-attr="data-testid id"')

Datastar Pro#

These helpers emit the same attribute names as upstream Datastar Pro. The open-source bundle ignores them.

DatastarAttributes.animate(expression)#

Animate element attributes over time. Datastar Pro.

data.animate("$x")
# Attrs(' data-animate="$x"')

DatastarAttributes.custom_validity(expression)#

Set a custom validity message. Datastar Pro.

data.custom_validity("$msg")
# Attrs(' data-custom-validity="$msg"')

DatastarAttributes.match_media(signal_name, expression)#

Sync a signal with matchMedia. Datastar Pro.

data-match-media has no value form, so the key is spelled to survive HTML lowercasing and Datastar’s case conversion and still yield signal_name exactly.

data.match_media("isDark", "'prefers-color-scheme: dark'")
# Attrs(' data-match-media:is-dark="'prefers-color-scheme: dark'"')
data.match_media("is_dark", "'prefers-color-scheme: dark'")
# Attrs(' data-match-media:is_dark__case.kebab="'prefers-color-scheme: dark'"')

DatastarAttributes.on_raf(expression, *, throttle=None)#

Run an expression on every animation frame. Datastar Pro.

data.on_raf("draw()", throttle="100ms")
# Attrs(' data-on-raf__throttle.100ms="draw()"')

DatastarAttributes.on_resize(expression, *, debounce=None, throttle=None)#

React to element resize. Datastar Pro.

data.on_resize("layout()", debounce="50ms", throttle="100ms")
# Attrs(' data-on-resize__debounce.50ms__throttle.100ms="layout()"')

DatastarAttributes.persist(*, include=None, exclude=None, storage_key=None, session=False)#

Persist signals. Datastar Pro.

data.persist(include=["draft"], storage_key="prefs", session=True)
# data-persist:prefs__session="{'include':'^(?:draft)(?:\\.|$)'}"

DatastarAttributes.query_string(*, include=None, exclude=None, filter_empty=False, history=False)#

Sync signals with the URL. Datastar Pro.

data.query_string(include=["page"], history=True)
# data-query-string__history="{'include':'^(?:page)(?:\\.|$)'}"

DatastarAttributes.replace_url(expression)#

Replace the current browser URL. Datastar Pro.

To change the URL from a handler with the free bundle, send SSE(w).replace_url(url).

data.replace_url("`/page/${$page}`")
# Attrs(' data-replace-url="`/page/${$page}`"')

DatastarAttributes.scroll_into_view(*, behavior=None, horizontal=None, vertical=None, focus=False)#

Scroll this element into view. Datastar Pro.

data.scroll_into_view(behavior="smooth", vertical="center", focus=True)
# Attrs(' data-scroll-into-view__smooth__vcenter__focus')

DatastarAttributes.view_transition(expression)#

Set view-transition-name. Datastar Pro.

data.view_transition("$id")
# Attrs(' data-view-transition="$id"')

Actions#

at is the stock DatastarActions instance. Each method returns an action string such as @post('/cart'), which you place inside data.on(...) or data.init(...). Build the URL with route.href(); query and fragment belong on href(), not on the action.

Requests#

get, post, put, patch, delete, and query share one set of options: which signals to send, a selector for form content, extra headers, retry, and request cancellation. The response is an SSE stream that Datastar applies to the page. Values in payload are JavaScript expressions; wrap literal text with string_literal() from stario.datastar.format.

DatastarActions.get(url, queries=None, *, content_type=None, include=None, exclude=None, selector=None, headers=None, open_when_hidden=None, payload=None, retry=None, retry_interval=None, retry_scaler=None, retry_max_wait=None, retry_max_count=None, request_cancellation=None, retry_interval_ms=None, retry_max_wait_ms=None)#

Build @get(...). Datastar sends the signals in the datastar query parameter.

Data and code: headers= values are data. payload= is one JavaScript expression: payload=literal({"title": title}) sends the text, payload="{id: $id, title: el.value}" reads the browser. A payload replaces the signals, so it does not go with include= / exclude=. A payload= dict with a str value is the 5.8 form (the str is an expression); it warns, and in 6.0 it becomes text.

SEARCH = Route("GET /items")
h.Button(data.on("click", at.get(SEARCH.href())), "Search")
h.Div(data.init(at.get(LIVE.href(), retry="always", retry_interval="2s")))

queries= is deprecated: build the URL with ROUTE.href(query={...}). A signal travels in the signals, not in the URL.

DatastarActions.post(url, queries=None, *, content_type=None, include=None, exclude=None, selector=None, headers=None, open_when_hidden=None, payload=None, retry=None, retry_interval=None, retry_scaler=None, retry_max_wait=None, retry_max_count=None, request_cancellation=None, retry_interval_ms=None, retry_max_wait_ms=None)#

Build @post(...) with the same option surface as get.

DatastarActions.put(url, queries=None, *, content_type=None, include=None, exclude=None, selector=None, headers=None, open_when_hidden=None, payload=None, retry=None, retry_interval=None, retry_scaler=None, retry_max_wait=None, retry_max_count=None, request_cancellation=None, retry_interval_ms=None, retry_max_wait_ms=None)#

Build @put(...) with the same option surface as get.

DatastarActions.patch(url, queries=None, *, content_type=None, include=None, exclude=None, selector=None, headers=None, open_when_hidden=None, payload=None, retry=None, retry_interval=None, retry_scaler=None, retry_max_wait=None, retry_max_count=None, request_cancellation=None, retry_interval_ms=None, retry_max_wait_ms=None)#

Build @patch(...) with the same option surface as get.

DatastarActions.delete(url, queries=None, *, content_type=None, include=None, exclude=None, selector=None, headers=None, open_when_hidden=None, payload=None, retry=None, retry_interval=None, retry_scaler=None, retry_max_wait=None, retry_max_count=None, request_cancellation=None, retry_interval_ms=None, retry_max_wait_ms=None)#

Build @delete(...) with the same option surface as get.

DatastarActions.query(url, queries=None, *, content_type=None, include=None, exclude=None, selector=None, headers=None, open_when_hidden=None, payload=None, retry=None, retry_interval=None, retry_scaler=None, retry_max_wait=None, retry_max_count=None, request_cancellation=None, retry_interval_ms=None, retry_max_wait_ms=None)#

Build @query(...) with the same option surface as get.

Sends a QUERY request with signals in the body, like post.

Signals in the browser#

These act on signals without a request.

DatastarActions.peek(callable_expr)#

Build @peek(expr) to read a value without subscribing.

DatastarActions.set_all(value, include=None, exclude=None)#

Build @setAll(...) to assign matching signals in bulk.

DatastarActions.toggle_all(include=None, exclude=None)#

Build @toggleAll(...) to flip matching boolean signals.

Datastar Pro#

DatastarActions.clipboard(text, is_base64=False)#

Build @clipboard(...). Datastar Pro.

DatastarActions.intl(type, value, options=None, locale=None)#

Build @intl(...). Datastar Pro.

value is a JavaScript expression. String values inside options are emitted as JavaScript string literals; numbers and booleans pass through.

DatastarActions.fit(v, old_min, old_max, new_min, new_max, should_clamp=False, should_round=False)#

Build @fit(...) to remap a numeric expression. Datastar Pro.

Reading what the page sent#

Every Datastar request carries the page’s signals as one JSON object. read_signals(req) returns it as a dict. GET, HEAD, and DELETE carry it in the datastar query parameter; other methods carry it in the body. read_signals(req, max_size=...) passes the limit to body(); the default is RequestPolicy.max_body_bytes (10 MiB). Treat the result as untrusted input. Parsing goes through stario.json. Malformed JSON or a payload that is not an object raises RequestBodyError, so the client gets a 400.

A file input bound with data.bind arrives as a signal too, not as multipart/form-data. FileSignal is the TypedDict for one such value: name, base64 contents, and mime, which may be None. Base64 makes a file about a third larger, so pass a larger max_size for signals that carry a file. For an HTML form with <input type="file">, use read_form.

from stario.datastar import FileSignal, read_signals
 
 
async def upload(c, w):
    signals = await read_signals(c.req, max_size=20 * 1024 * 1024)
    avatar: FileSignal = signals["avatar"]

async read_signals(req, *, max_size=None)#

Parse the JSON signals blob Datastar sends.

GET, HEAD, and DELETE use the datastar query parameter. Other methods use the request body, limited by max_size as in Request.body(). Pass a larger max_size for signals that carry a FileSignal.

This is convenience parsing only. Incoming signals are untrusted; validate types, sizes, and nested shapes before using them as application data. Signal names pass through unchanged; names starting with _ are Datastar local signals, so the browser does not send them by default and they are missing here. Nested client state arrives as nested JSON objects.

from stario import Route
from stario.datastar import SSE, read_signals
 
ACTION = Route("POST", "/action")
 
async def action(c, w):
    sig = await read_signals(c.req)
    SSE(w).patch_signals({"n": int(sig.get("n", 0)) + 1})

SSE#

SSE(w) binds the Datastar event stream to one Writer. Create one per response. Each method appends one event. The first event sends the text/event-stream headers; call open() to send them earlier. Do not start an SSE stream on a writer that has already sent a response, and do not call a w.* response method after it.

from stario.datastar import SSE, read_signals
 
 
async def increment(c, w):
    signals = await read_signals(c.req)
    sse = SSE(w)
    sse.patch_signals({"count": int(signals.get("count", 0)) + 1})

patch_elements accepts bytes, text, or a markup tree. mode defaults to outer, which morphs the matched element. The others are inner, replace, prepend, append, before, and after. Without selector, elements match by id. navigate moves the browser from inside a stream by sending a short script, the same way the official Datastar client SDKs redirect. A 3xx status on a Datastar request does not navigate: fetch follows it and Datastar morphs the final page into the current one. Use w.redirect only for requests the browser itself makes, such as a plain form post. execute_script streams JavaScript you wrote; never interpolate user input into it.

Every event method takes event_id= and retry=. An event id lets a reconnecting client resume where it left off; retry sets the reconnect delay in milliseconds — the Datastar default of 1000 is never emitted. ping() writes an SSE comment, a heartbeat that keeps proxies and clients alive on a quiet stream.

SSE.open()#

Send text/event-stream headers now, before the first event.

SSE.patch_elements(content, *, mode=None, selector=None, namespace=None, view_transition=False, view_transition_selector=None, event_id=None, retry=None)#

Patch DOM elements with Stario markup, a SafeString, or bytes.

Markup built with h.* is rendered with escaping. A SafeString and bytes are finished HTML and go out as they are. A plain str is the 5.8 form: it goes out as HTML and warns; wrap finished HTML you built in SafeString.

SSE.patch_signals(payload, *, only_if_missing=False, event_id=None, retry=None)#

Patch Datastar signals from a JSON-shaped mapping.

Dotted keys expand to nested objects, so {"ui.open": True} patches $ui.open. Values may be any Mapping or Sequence (a list[str] variable, a tuple), sent as JSON objects and arrays.

SSE.remove(selector, *, event_id=None, retry=None)#

Remove nodes matching selector.

SSE.navigate(url, *, event_id=None, retry=None)#

Navigate the browser from an SSE response; not an HTTP redirect.

SSE.execute_script(code, *, auto_remove=True, event_id=None, retry=None)#

Run trusted developer-authored JavaScript by appending a script element.

The code is streamed verbatim; do not interpolate untrusted input (put values in with literal()). Code that holds </script or <!-- raises, as in h.Script.

SSE.ping(comment='')#

Write an SSE comment (: ...) to keep proxies and clients alive.

A heartbeat loop looks like:

async with c.alive():
    while True:
        sse.ping()
        await asyncio.sleep(15)

By the way#

  • stario.datastar.format holds the wire helpers Case, js_object, and string_literal. js_object treats string values as JavaScript expressions.

  • JSEvent is a type hint for the event names data.on accepts. At runtime any string works.

  • ContentType, RequestCancellation, and Retry are Literal aliases in stario.datastar.actions.

See also: the Datastar from Python how-to for the common patterns, and Live pages for why a page holds one stream open.