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 successThose 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
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")))
}
}| Item | Description |
|---|---|
ALIAS | The value of data-linker and the registry key; ^[a-z][a-zA-Z0-9]*$, at most 64 characters |
METHODS | The methods the browser may call (PHP's #[Computable]); ^[a-zA-Z][a-zA-Z0-9]*$. Anything else gets policy "不支援的操作。" (unsupported operation) |
MODE | LinkerMode::Stateful (default) or LinkerMode::Stateless; see Stateful and Stateless |
ALLOWS_REFERER_URLS | Page 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:
| Field | Contents |
|---|---|
user | The logged-in user's id (as text) |
alias | The component's alias |
instance | The Stateful uuid; None for Stateless and while mounting |
referer | The Referer the browser sent |
Registering and mounting
// register() in src/cg/mod.rs, run once at startup
cg_component::runtime::linker::register::<Counter>();// 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))<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>mountneeds a user: the Linker endpoints always require a login, so the handler usesAuthenticated<User>orAuth<User>.mountreturns an error if the component isn't registered;registerpanics on an invalid alias or method name.- For
datato be written into client state, the nearest render object around the triggering element must haveStateWrite(therender_objectabove).
What it guarantees
| Guarantee | How |
|---|---|
| The browser can only call methods you allow | Only methods in METHODS exist; components are registered by hand |
| The browser can't change server state | Stateful state stays in the cache; the browser only has uuid + rev |
| Only logged-in users can call | The 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 JS | There's only the named action table, no eval |
| Error handling is written once | Failures have fixed shapes, handled in one place by linker.js |
| Arguments are validated | You validate them in call. Rust has no #[Validate], so this one is on you |
Why not Livewire
| Livewire | Linker | |
|---|---|---|
| State | Round-trips with every request (snapshot + HMAC) | Only on the server; the browser gets a uuid |
| Exposed surface | Every public method and property | Only METHODS |
| Returns | An HTML diff | Data + 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
| Situation | Use |
|---|---|
| File bytes | A normal multipart route (the resulting file id can go through Linker) |
| Returning a big block of HTML | Render fragments (Linker returns render.fragment to ask for one) |
| Pure front-end display toggles | data-state-toggle |
| Interaction for anonymous users | Render fragments or normal routes (Linker always requires a login) |
| Needs SEO or must work without JS | A 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.