livewire·rust

Actions & validation

An action is one entry in a call list. It decodes its parameters, runs, and answers through the effects map beside the new markup.

request body
{
  "components": [
    {
      "snapshot": "{\"data\":{\"count\":3},\"memo\":{...},\"checksum\":\"...\"}",
      "updates": { "step": "5" },
      "calls": [
        { "method": "increment", "params": [], "metadata": {} }
      ]
    }
  ]
}
Live exampleopen ↗

The left side is the JSON the browser posts; the right side is a component whose buttons exercise parameters, events, and a JSON-returning action.

A call on the wire

An update names a signed snapshot, the fields the browser changed, and the calls it made. One call is {method, params, metadata}.

{
  "components": [
    {
      "snapshot": "{\"data\":{\"count\":3},\"memo\":{...},\"checksum\":\"...\"}",
      "updates": { "step": "5" },
      "calls": [
        { "method": "increment", "params": [], "metadata": {} }
      ]
    }
  ]
}

The answer holds one entry per component, in the order the request sent them, plus the assets the render added:

{
  "components": [
    {
      "snapshot": "{\"data\":{\"count\":4,...},\"memo\":{...},\"checksum\":\"...\"}",
      "effects": {
        "html": "<div wire:id=\"...\" wire:snapshot=\"...\">...</div>",
        "returns": [null]
      }
    }
  ],
  "assets": []
}

The properties are applied before any call runs, so an action reads the values the browser just sent. effects.html has its own wire:snapshot and wire:effects, because the client keeps the component only while the root still names it.

Parameters

params is a list or an object; anything else is a malformed payload and answers 404. A parameter is read positionally, or by name, or by the decimal index as a key, so a call written as add(10) and one written as add({by: 10}) reach the same method.

pub fn add(&mut self, by: i32) {
    self.count += by;
}

pub fn label(&mut self, text: Option<String>) {
    self.label = text.unwrap_or_default();
}

Option<T> makes the parameter optional; a missing required parameter is a 404. The Params type is public: arg(name, index), optional(name, index), decode::<T>() for one struct, and is_empty(). Values are read with serde_json, so a JSON object, an array, a number, and a string all decode into their Rust type.

A parameter declared as &mut ComponentContext (or &ComponentContext) is the call's context, not a wire parameter. That is how an action dispatches an event, adds an effect, records an error, or skips its render.

Internal calls

The client sends some calls that do not name a method of the component. The macro's dispatch handles them before the action arms.

CallParametersWhat it does
$refreshnoneRuns nothing and renders again.
$commitnoneThe model commit. An unchanged reactive child whose calls are all $commit answers {"skip":true} instead of a render.
$setproperty, valueWrites one field through its setter, so a locked field is refused with 419.
$syncnoneNo-op; the client's sync signal.
__dispatchname, paramsResolves a declared listener to its method, which then goes through the action allowlist.
__lazyLoadnoneThe first update of a lazy or deferred component. It renders the real view and sets memo.lazyLoaded.
__lazyLoadIslandisland metadataAccepted by the dispatcher; islands answer through effects.islandFragments.
_startUpload, _finishUpload, _uploadErrored, _removeUploadfrom the runtimeThe upload handshake. These are the client's own and never reach an action of the same name.

Return values

Every call occupies one slot in effects.returns, always. A call that returns () or Result<()> writes null; a call that returns a value writes it, and the browser's promise for that call resolves with it.

MethodAnswer
fn reset(&mut self)returns[i] = null, then the component renders.
fn count(&mut self) -> i32returns[i] = 3, then the component renders.
#[livewire(renderless)]effects.skipRender = true. The entry has effects but no snapshot; the client keeps the one it has.
#[livewire(json)]The value is the body. The method is listed in memo.json and memo.async, and the render is skipped.
#[livewire(async)]The client sends the call ahead of the others; the method is listed in memo.async.

A denied JSON action does not fail the batch: it writes returnsMeta[i] = {"status": 403} and a null return. Any other error from a JSON action becomes returnsMeta[i].status, carrying the status that error has. A denied ordinary action fails the whole response with 403.

Validation

Rules are declared on the field and compiled into the framework's rule constructors. Four exist: required, string, min_length(n), and max_length(n). Any other rule name is a compile error, and so is a rule written with =.

#[derive(Default, LivewireComponent)]
#[livewire(view = "livewire.contact")]
pub struct Contact {
    #[livewire(validate(required, max_length(10)))]
    pub name: String,
}

#[component]
impl Contact {
    pub async fn save(&mut self, context: &mut ComponentContext) {
        context.validate(self).await.ok();
    }
}

context.validate(self) runs every declared rule against the component's current state. A failure is not an HTTP failure: the messages go to memo.errors in the new snapshot, the response is 200, and the component still renders, so the field keeps what the browser typed. context.add_error(field, message) records one message without running a rule.

memo.errors is an object keyed by field. Each value is one message string. Upstream sends a list per field; this port sends the first message as a plain string, and the client's $errors bag reads the object as it is. Errors belong to the request that produced them, so the next update starts with none.

There is no @error directive and the server does not flash old input. The error(field) and old(field) template helpers exist, but nothing fills them from a failed validation: read the messages in the browser from $errors.

Events

A listener is declared on the method. The event name reaches the browser in effects.listeners, the client registers it, and a dispatch comes back as __dispatch with the event name and its params.

#[livewire(on = "counter-reset")]
pub fn reset_from_event(&mut self) {
    self.count = 0;
}

pub fn announce(&mut self, context: &mut ComponentContext) {
    context.push_effect(
        "dispatches",
        serde_json::json!({"name": "counter-announced", "params": {"count": self.count}}),
    );
}

The server resolves a dispatch only for an event the component declares, and the resolved method must still be reachable: a dispatch cannot call a method an ordinary call could not. An undeclared event is a 500. The dispatch entry may carry self, component, ref, or el to target the page, another component, a wire:ref, or one element instead of broadcasting.

effects.listeners and effects.url are written at mount only. The client keeps them from the first render, so they do not reappear in later responses.

Effects

KeyWritten byWhat the browser does
htmlthe renderMorphs the new markup over the component's element.
islandFragmentsan action that came from an islandMorphs each named island fragment instead of the whole component.
slotFragmentsa parent that stubbed a childMorphs the slot content inside the child that was not re-rendered.
skipRenderrenderless, json, a downloadLeaves the markup alone.
redirectadd_effect("redirect", url)Leaves the page. The render is skipped unless render_on_redirect is enabled.
redirectUsingNavigateadd_effect("redirectUsingNavigate", url)The same, through wire:navigate.
downloadcontext.download(name, content, content_type)Saves a file from {name, content, contentType}, with the content base64. The render is skipped.
dispatchespush_effect, or a mount-time listDispatches each {name, params} after the DOM morphs.
listenersthe declared on methodsRegisters the events the component listens for.
urlthe url fields at mountDescribes the query-string bindings, as {as, use, alwaysShow, except}.
transitionthe class transition optionRuns the named Alpine transition around the change.
xjsadd_effect("xjs", "js")Evaluates the string in the browser. The legacy js key is read by the same client code and is not written by the server.
returnsevery update with callsOne entry per call, aligned with the order the calls were sent.
returnsMetaa JSON call that failed or was deniedPer-call metadata keyed by call index, such as {"status": 403}.
pub fn celebrate(&mut self, context: &mut ComponentContext) {
    context.add_effect("xjs", serde_json::json!("window.celebrated = true"));
}

pub fn leave(&mut self, context: &mut ComponentContext) {
    context.add_effect("redirect", serde_json::json!("/posts"));
}

pub fn export(&mut self, context: &mut ComponentContext) {
    context.download("counter.csv", format!("count,{}\n", self.count), "text/csv");
}

context.stream(name, content) is the one effect that leaves through a different transport: it becomes a frame sent before the response body. Streaming covers it.

Properties the browser may not set

A locked field is in the snapshot, so the page can print it, but an update that names it answers 419. A field with session is written to the session and removed from data before signing, so nothing about it crosses the wire; it is read back from the session on the next request. A field with url is ordinary wire state whose first value comes from the page's query string.

When a call fails

FailureStatus
params is neither a list nor an object, or a required parameter is missing or does not decode404
The method is not in the annotated impl419
The field is locked, or its value cannot be hydrated419
The update names a field the component does not publish500
The dispatch names an event the component does not listen for500
A policy refuses the call403, unless the action is a JSON one

Three of these render the framework's detailed error page in debug mode instead of the bare status: corrupt snapshot, release-token mismatch, and unknown method. In production the status alone is the answer.