← All posts

Laravel Rust for the backend, Topcoat for the frontend, in one binary

Laravel Rust's frontend options meant React plus Node or plain templates. So I put Topcoat in front of it instead, shared Laravel's login with it, and shipped both as one Rust binary.

This week I compared Laravel in PHP, Go and Rust on YouTube. Laravel Rust and Laravel Go had just come out in beta, and the backend side surprised me. Models, migrations, validation, sessions: it really feels like Laravel, only compiled.

The frontend side is where I got stuck. Out of the box both ports give you two choices. The first is Inertia with React, Vue or Svelte, built by Vite. That's great, but if you want server-side rendering you're back to running a Node process next to your nice small binary. The second is server templates (MiniJinja in Rust, html/template in Go). Those are light, but every bit of interactivity becomes htmx or hand-written JavaScript.

I already use Topcoat for this site. It renders HTML on the server, and the interactive parts are Rust too, compiled to JavaScript for the browser. So the obvious question was: can Laravel Rust be the backend and Topcoat the frontend, in one binary?

It can. The whole prototype is about 380 lines of Rust, and the code is on GitHub: nick-friedrich/laravel-topcoat.

Why this works at all

Both frameworks are built on the same Rust web stack. Laravel Rust sits on axum, and Topcoat can mount any tower service or run inside one. So neither has to know about the other. One just treats the other as a service.

The demo is a tiny Chirper: users, chirps, a login, a feed. Laravel owns the database, the models, validation, sessions and login. Topcoat owns the pages and everything you click.

First attempt: Topcoat in front

My first version put Topcoat in front and mounted Laravel's router under /api. Topcoat pages called Laravel models directly, which already felt a bit crazy. A Topcoat page running a Laravel query, no JSON in between:

let chirps = Chirp::feed(50).await?;

That version worked for reading data. Then I wanted login, and that's where it broke down. Laravel's session, its CSRF check and its Auth only run on Laravel's own routes. Topcoat pages were outside all of that. So I flipped it around.

Second attempt: Laravel in front

Now Laravel answers every request. /api goes to normal JSON routes. Everything else falls through to the web group's fallback route, after Laravel's session, CSRF and auth middleware have run:

Application::configure()
    .with_auth(|auth, _| { auth.session::<Users<User>>(); })
    .with_routing(|routing, _| {
        routing
            .api(api::routes).api_prefix("/api")
            .web(|route| { route.fallback(bridge::to_topcoat); })
    })

The fallback is the whole bridge. It takes Laravel's Auth for this request, attaches it to the request, and hands it to the Topcoat router:

pub async fn to_topcoat(auth: Auth<User>, request: Request) -> impl IntoResponse {
    let mut request = request.into_http();
    request.extensions_mut().insert(LaravelAuth(auth));
    TOPCOAT.get().unwrap().clone().oneshot(request).await
}

pub fn auth(cx: &Cx) -> &Auth<User> {
    &original_parts(cx).extensions.get::<LaravelAuth>().unwrap().0
}

That's not an HTTP hop. oneshot passes the request object to Topcoat in memory, like a function call. And because Topcoat's response goes back out through Laravel's middleware, Laravel still writes the session cookie when a Topcoat handler logs someone in.

Login across both frameworks

The login button is Rust that runs in the browser. log_in looks like a normal function call, but it's a Topcoat procedure, so Topcoat turns it into a POST for me:

<button @click=$(async |_e: Event| {
    let message = log_in(email.get(), password.get()).await;
    error.set(message);
    revision.increment();
})>"Log in"</button>

On the server, the procedure just asks Laravel:

#[procedure]
async fn log_in(cx: &Cx, email: String, password: String) -> Result<String> {
    Ok(match auth(cx).attempt(&email, &Password::from(password)).await {
        Ok(_) => String::new(),
        Err(_) => "These credentials do not match our records.".to_owned(),
    })
}

revision.increment() makes the page's shards fetch themselves again. The account shard asks Laravel for the current user, finds Ferris, and swaps the login form for the composer. No page reload, and no frontend state to keep in sync with the backend. Reload the page and you're still logged in, because it's Laravel's normal session cookie.

Posting a chirp reuses Laravel's validation rules, declared once on the struct:

#[derive(Deserialize, Validate)]
#[validate(authenticated)]
pub struct NewChirp {
    #[validate(required, max_length(280))]
    pub text: String,
}

The procedure checks the user again on the server before it saves anything. Hiding the composer in the browser isn't the security. Posting without a session cookie just returns "Log in first."

Two layers of CSRF protection

I assumed Topcoat had no CSRF protection of its own. I was wrong. A cross-site POST never even reaches Laravel: Topcoat's router checks the origin first and answers 403. Laravel's own CSRF check sits behind that. You get two layers without writing any code for it.

What I like, and what's rough

What I like:

  • One Rust binary, one port. No Node, no separate frontend project, no API layer written only so the frontend can call it.
  • The frontend calls Chirp::feed() directly. The API route calls the same function for anyone outside.
  • The debug build uses about 35 MB of RAM.
  • The glue is one small file.

What's rough:

  • Both projects are young: Laravel Rust is 0.1, Topcoat 0.12. Expect APIs to move.
  • Every page request goes through two routers, a thin outer Topcoat one (so topcoat dev can build the browser code and live reload) and the real one behind Laravel.
  • Browser-side Rust is a subset. .chars() isn't available there yet, so my 280 counter counts bytes.
  • Registration, password reset and "remember me" aren't wired up. Laravel has them, and they'd go through the same bridge.

Try it

git clone https://github.com/nick-friedrich/laravel-topcoat
cd laravel-topcoat
cargo run -- migrate
cargo run -- key:generate
topcoat dev

Then open http://127.0.0.1:3000 and log in as ferris@example.com with password.

Next I want to build the same Chirper with Laravel Rust's default Inertia and React setup, and compare binary size, build time, RAM and how much JavaScript ends up in the browser. Would you use a combination like this, or would you rather keep a JavaScript frontend?