Skip to content

Linker overview ​

Write interaction in Rust. The browser has no business logic and no error handling code.

The problem ​

A "save customer" button: how many places does the traditional approach touch?

Route → handler → validation struct → JSON response
  ↓
Browser: build the request, send it, check the HTTP status, unpack 422 errors next to the fields,
         show "no permission" on 403, ask to reload on 409, show an error card on 500, reload the list on success

Those last seven steps get rewritten for every module, each a bit differently. The actual business logic is just "save a customer".

Linker removes that layer: Rust writes the business logic, and the browser has one shared receiver (linker.js).

What one call looks like ​

Template attribute data-linker-call="search" + args
  → linker.js: build arguments, debounce, confirm, queue
  → POST /{prefix}/linker { component, instance, rev, method, args }
  → Rust: login → lock → read the instance → rev → booted() → referer → METHODS → call()
  → LinkerResponse → { ok, data, pipeline, instance, rev }
  → linker.js: write data into client state (data-state-* display themselves)
               run the pipeline in order (render.fragment, ui.toast…)

A component ​

rust
use cg_component::runtime::linker::{Action, Args, LinkerComponent, LinkerContext, LinkerResponse};
use serde::{Deserialize, Serialize};

#[derive(Default, Serialize, Deserialize)]
pub struct Counter {
    count: i64,
}

impl LinkerComponent for Counter {
    const ALIAS: &'static str = "counter";
    const METHODS: &'static [&'static str] = &["increment"];

    async fn call(&mut self, _: &LinkerContext, _method: &str, _args: Args) -> laravel::Result<LinkerResponse> {
        self.count += 1;
        Ok(LinkerResponse::ok().data("count", self.count).then(Action::toast("success", "+1")))
    }
}
ItemDescription
ALIASThe value of data-linker and the registry key; ^[a-z][a-zA-Z0-9]*$, at most 64 characters
METHODSThe methods the browser may call (PHP's #[Computable]); ^[a-zA-Z][a-zA-Z0-9]*$. Anything else gets policy "不支援的操作。" (unsupported operation)
MODELinkerMode::Stateful (default) or LinkerMode::Stateless; see Stateful and Stateless
ALLOWS_REFERER_URLSPage paths allowed to send requests (/orders/*); empty means no restriction. See Access control
mount(&mut self, ctx, params)Initializes a Stateful instance from page parameters when it's mounted
booted(&mut self, ctx)Runs before every call, after the state is restored
call(&mut self, ctx, method, args)Handles a method. Validation and authorization go here

The struct itself is the state: it needs Serialize + Deserialize + Default + Send + Sync + 'static.

LinkerContext:

FieldContents
userThe logged-in user's id (as text)
aliasThe component's alias
instanceThe Stateful uuid; None for Stateless and while mounting
refererThe Referer the browser sent

Registering and mounting ​

rust
// register() in src/cg/mod.rs, run once at startup
cg_component::runtime::linker::register::<Counter>();
rust
// page handler
use cg_component::runtime::{self, Allow, linker};

let mount = linker::mount::<Counter, User>(&user, linker::Args::new()).await?;
let attrs = mount.html()
    + &runtime::render_object("counter", &[Allow::Render, Allow::StateRead, Allow::StateWrite]).render(&[]);

view("page", data! {}).with_html("counter_attrs", laravel::view::Html::raw(attrs))
html
<div{{ counter_attrs }} data-state-init="count=0">
    Now: <output data-state-text="count">0</output>
    <button type="button" data-linker-call="increment">+1</button>
</div>
  • mount needs a user: the Linker endpoints always require a login, so the handler uses Authenticated<User> or Auth<User>.
  • mount returns an error if the component isn't registered; register panics on an invalid alias or method name.
  • For data to be written into client state, the nearest render object around the triggering element must have StateWrite (the render_object above).

What it guarantees ​

GuaranteeHow
The browser can only call methods you allowOnly methods in METHODS exist; components are registered by hand
The browser can't change server stateStateful state stays in the cache; the browser only has uuid + rev
Only logged-in users can callThe endpoints answer 401 without a user; instances are tied to the user, and someone else's uuid gets expired
The server can't make the browser run arbitrary JSThere's only the named action table, no eval
Error handling is written onceFailures have fixed shapes, handled in one place by linker.js
Arguments are validatedYou validate them in call. Rust has no #[Validate], so this one is on you

Why not Livewire ​

LivewireLinker
StateRound-trips with every request (snapshot + HMAC)Only on the server; the browser gets a uuid
Exposed surfaceEvery public method and propertyOnly METHODS
ReturnsAn HTML diffData + named actions
Server telling the browser what to do$this->js() (effectively eval)A named action table

The cost: in Stateful mode the server stores state (in the cache, 30 minutes idle), so horizontal scaling needs a shared cache store.

What should not go through Linker ​

SituationUse
File bytesA normal multipart route (the resulting file id can go through Linker)
Returning a big block of HTMLRender fragments (Linker returns render.fragment to ask for one)
Pure front-end display togglesdata-state-toggle
Interaction for anonymous usersRender fragments or normal routes (Linker always requires a login)
Needs SEO or must work without JSA normal route + form

Progressive enhancement: keep type="submit" on submit buttons and keep <form action>. Without JS the normal route is used; with JS, Linker takes over.

Next: Template attributes. To build a component hands-on, see Your first Linker component.