livewire·rust

Page components and guards

A page component renders a fragment, and the route wraps it in the layout. The browser then drives it through the same update endpoint as any embedded component.

page-demo.rs
use livewire::LivewireComponent;
use livewire::component;

#[derive(Default, LivewireComponent)]
#[livewire(view = "livewire.page-demo")]
pub struct PageDemo {
    pub title: String,
    pub clicks: i64,
}

#[component]
impl PageDemo {
    pub fn mount(&mut self, title: Option<String>) {
        self.title = title.unwrap_or_else(|| "A page component".to_owned());
    }

    pub fn click(&mut self) {
        self.clicks += 1;
    }
}
Live exampleopen ↗

The frame is the full page component at /livewire/page-demo; its updates morph the fragment and never the document.

One component, one fragment

An embedded component lives inside a page template. A page component is the page: its .livewire view is a fragment with one root element, exactly like an embedded component's, and the route wraps that fragment in the layout.

{# resources/views/livewire/page-demo.livewire #}
<div data-page-demo>
  <h1>{{ title }}</h1>
  <button type="button" wire:click="click" data-click>Click</button>
</div>

The component is written like any other. It is registered under a name, derives LivewireComponent, and publishes its actions with #[component]:

use livewire::LivewireComponent;
use livewire::component;

#[derive(Default, LivewireComponent)]
#[livewire(view = "livewire.page-demo")]
pub struct PageDemo {
    pub title: String,
    pub clicks: i64,
}

#[component]
impl PageDemo {
    pub fn mount(&mut self, title: Option<String>) {
        self.title = title.unwrap_or_else(|| "A page component".to_owned());
    }

    pub fn click(&mut self) {
        self.clicks += 1;
    }
}

Nothing about the update endpoint changes. The fragment carries wire:id, wire:name, wire:snapshot, and wire:effects like any component, and the attributes land on its own root element — never on the layout's <html>. That matters: the client morphs the element that carries wire:id, so a document morphed onto <html> would take the head and body with it.

Mounting the page

There is no router extension in this port. The route handler calls livewire::page::render_page for the fragment and wraps it in the layout:

use std::sync::Arc;

use laravel::container::Inject;
use laravel::view::{View, view};
use livewire::ComponentRegistry;
use livewire::component::Params;
use serde_json::{Map, json};

pub async fn page_demo(registry: Inject<Arc<ComponentRegistry>>) -> View {
    let params = Params::Named(Map::from_iter([
        ("title".to_owned(), json!("A page component")),
    ]));

    let fragment = livewire::page::render_page(®istry, "page-demo", params)
        .expect("the page component renders");

    view(
        "layouts.app",
        json!({"title": "A page component", "content": fragment}),
    )
}

The handler is async so it can fetch data first. The mount itself is synchronous: render_page runs the mount lifecycle and MiniJinja rendering, and returns the finished fragment. A failure comes back as an error the handler decides how to answer: an unregistered name, a failed mount, or a view with no single root element.

The layout renders {{ content|safe }} inside its content block, so the fragment is markup, not text; a view that extends the layout itself still overrides that block and works as before.

Route parameters as mount props

Params reach the component through Params::Named. The derive matches each key to a wire-public field, through camel_case, and hydrates the field before mount runs. The declared mount arguments are read from the same params, by name or by position, and a parameter declared Option<T> may be absent.

use laravel::container::Inject;
use laravel::http::Response;
use laravel::routing::Params as RouteParams;
use serde_json::{Map, json};

async fn edit(
    registry: Inject<Arc<ComponentRegistry>>,
    RouteParams(id): RouteParams<i64>,
) -> Response {
    let params = Params::Named(Map::from_iter([(
        "post-id".to_owned(),
        json!(id),
    )]));

    let html = livewire::page::render_page(&registry, "post-editor", params)
        .expect("the page component renders");

    Response::new(Html::raw(html))
}

Route parameters, layout choices, and data loading belong to the application's routing layer. The component receives the results as props, and does not read the router itself.

The route context a page records

A snapshot belongs to the page that rendered it. At mount, the context records the request's path, method, and origin in the snapshot's memo:

"memo": {
  "id": "Q2xvdWQ4d2F0Y2g5",
  "name": "page-demo",
  "children": {},
  "release": "a-a-a",
  "path": "/livewire/page-demo",
  "method": "GET",
  "origin": "http://127.0.0.1:8000"
}

The RememberPage middleware, which the provider appends, records every request that renders a page, whatever its method. A form submission that re-renders the same page therefore keeps its route context, and a component mounted by that render records the POST it came from.

The Livewire endpoints are excluded: the browser sends X-Livewire only to the update and upload endpoints, and those render no page. A request without that header is recorded, provided the request-local Livewire store exists.

An update with no page context runs no guard. The context is read from all three memo keys; if any is missing from the snapshot, the update proceeds without one.

A foreign origin is refused

An update whose Origin header names another site is refused with 404, even when its checksum is valid. The comparison uses the request's Origin header when there is one, and the host the request was addressed to otherwise, so an older browser that sends no header is not locked out.

This is the only route-context comparison the update makes. path and method are recorded for the guards below; they are not compared against the update request, which has its own path.

Guards that outlive the page

A route's middleware runs when the page is requested, and never again. The browser then drives the component through the update endpoint, which is not that route. A PersistentMiddleware runs on every update, with the update's request and the page the component was mounted from:

use laravel::http::{Request, Response, StatusCode};
use livewire::context::PageContext;
use livewire::persistent::PersistentMiddleware;

pub struct SignedIn;

#[livewire::__private::async_trait]
impl PersistentMiddleware for SignedIn {
    async fn handle(&self, request: &Request, page: &PageContext) -> Option<Response> {
        let signed_in = livewire::persistent::session("user_id").is_some();

        if page.path.starts_with("/dashboard")
            && (!signed_in || request.header("x-tenant").is_none())
        {
            return Some(Response::new("").with_status(StatusCode::UNAUTHORIZED));
        }

        None
    }
}

livewire::persistent::session reads the current request's session synchronously, which suits a guard that runs inside an async handler. None lets the update run; Some(response) is the answer the browser receives.

Register guards in the provider, beside the components:

components
    .register::<crate::livewire::counter::Counter>("counter")
    .expect("the counter component is registered once");

components.persistent(SignedIn);

Guards run in registration order, before the component hydrates or renders. The first guard that answers ends the update with its response, so put the cheapest check first. A refusal is the whole answer: no other component in the batch runs, and no snapshot comes back.

The guard sees the page context recorded at mount, so it can switch on the route the component belongs to and leave other pages alone. The demo application does exactly that: PausedUpdates answers 503 for /livewire/streamer when the request carries x-paused, and every other page's update passes.

What a page does not get

Some upstream page features have no server counterpart here. They are absent, not stubbed: