Visualising biological data — why we’re building a web app
The most useful tool you can give a biologist colleague is one they don’t have to install. A web page in a browser is exactly that: paste a sequence, see GC content, click to load a sample, no setup.
Today we build one — entirely in Rust, frontend and backend.
Frontend, backend, full-stack — the words
These three words come up constantly. They name the parts of every web app you’ve ever used. Today we go full-stack, in Rust, end to end.
What each word actually means
Frontend [the code that runs in the user’s browser — HTML + JS, or in our case Rust compiled to WASM (WebAssembly, a binary format browsers can execute)]
Backend [the code that runs on a server — receives requests, talks to databases, sends responses; ours is axum]
Full-stack [writing both ends]
What today is about
A web app written entirely in Rust — frontend, backend, shared types
Frontend compiled to WebAssembly, runs in the browser
The shape of the day
One workspace with three crates: shared, frontend, backend
frontend builds to .wasm, served by trunk [a build tool and dev server for Rust web frontends — like webpack for Yew, with hot reload (auto-rebuild + browser refresh on save) built in]
backend builds native, serves /api/samples
Both crates depend on shared — same Rust types on the wire
After class you are clicking a button, fetching a sequence, plotting GC content over a sliding window
Today: foundations (HTML, HTTP, JSON, ports) → axum backend → Yew frontend compiled to WASM → integrated app.
This is what we’re building
A mockup of the capstone: pick a sample, see the sequence, live GC stats, and an inline SVG plot.
Before you start — tooling checklist
rustup target add wasm32-unknown-unknown [one-time; teaches rustc (the Rust compiler) to emit WASM]
cargo install trunk [one-time; trunk is the build tool that runs the Yew dev server]
curl or HTTPie installed [for sanity-checking the backend from the command line]
Two terminals ready [one for the backend, one for trunk]
Before we touch Rust: three things to know
Most browser-based code rests on three building blocks. None of them is Rust-specific:
HTML — how a page is structured.
HTTP — how the browser talks to a server.
JSON — how structured data moves between the two.
Plus one more cross-cutting concept: ports.
HTML — a page is a tree of boxes
HTML is just text marked up with tags. The browser turns those tags into nested boxes on the screen.
<!-- HTML --><html><body><h1>Sequence inspector</h1><p>Paste DNA below:</p><div><textarea></textarea><p>GC content: 50%</p></div></body></html>
The <div> is the workhorse: a generic box that can contain other boxes. Almost every interactive component you’ve seen on the web is a <div> (or a few <div>s) with style and code attached.
Same HTML, two views: the source on the left, the rendered page on the right.
The DOM — the in-memory tree the browser builds
When the browser parses your HTML, it builds an in-memory tree of nodes called the DOM (Document Object Model). Every box in the rendered page is a node in this tree. Everything that changes the page after load — JavaScript, jQuery, React, Yew — does so by manipulating the DOM tree.
When you click a link, the browser sends an HTTP request to a server somewhere. The server sends back an HTTP response.
A request has:
a method (GET, POST, …),
a URL (https://api.example.com/samples/42),
optional headers (auth, content type, …),
optional body (for POST / PUT).
A response has:
a status code (200 OK, 404 Not Found, …),
headers,
a body (HTML, JSON, an image, anything).
An HTTP request goes out; a response comes back.
Ports — finding the right service on a machine
A single computer can run many services at once: a web server, a database, an SSH daemon, your dev backend. To direct traffic to the right one, every service listens on a port — a number from 0 to 65535.
The browser combines IP + port to reach a service:
http://127.0.0.1:3000/api/samples/42
─────────── ─── ──────────────
host port path
Common ports: 80 HTTP, 443 HTTPS, 22 SSH, 5432 PostgreSQL. Dev backends usually pick something high like 3000, 8000, or 8080 so they don’t clash with real services.
One machine, many ports, one client connecting to one of them.
JSON — how structured data crosses the wire
HTTP bodies are bytes. When you want to send structured data — a list of samples, a record with named fields — the most common encoding is JSON (JavaScript Object Notation).
An async fn [a function that does not block; it returns immediately] returns a Future [a description of work to be done later, not the result itself].
// Rustasyncfn fetch_one() ->Result<SampleRecord,gloo_net::Error>{let resp =Request::get("/api/samples/lambda").send().await?;let data = resp.json::<SampleRecord>().await?;Ok(data)}
.await [the operator that waits for a future to be ready] means: pause this task until the future is ready, let the runtime [the scheduler that decides which task runs when] do other work in the meantime.
We do not teach Future internals today — treat it as a single pattern.
What .await actually does
.await yields; the runtime resumes you when the work is done.
A REST server in 20 lines of axum
REST [HTTP verbs + URL paths to access named resources]. axum [a Rust web framework for HTTP servers] is the backend library we use today. The smallest possible backend — accepts a DNA sequence, returns its GC content:
useaxum::{routing::get, Router,extract::Query};useserde::{Serialize, Deserialize};#[derive(Deserialize)]struct GcQuery { seq:String}#[derive(Serialize)]struct GcAnswer { length:usize, gc:f64}asyncfn gc(Query(q): Query<GcQuery>) ->axum::Json<GcAnswer>{let n = q.seq.len();let g = q.seq.bytes().filter(|b|matches!(b,b'G'|b'C')).count();axum::Json(GcAnswer { length: n, gc: g asf64/ n.max(1) asf64})}#[tokio::main]asyncfn main() {let app =Router::new().route("/gc", get(gc));let l =tokio::net::TcpListener::bind("127.0.0.1:3000").await.unwrap();axum::serve(l, app).await.unwrap();}
REST server — the call flow
The flow: client requests GET /gc?seq=ACGT → axum routes → gc() handler → JSON response.
Calling it with curl
You can hit any REST endpoint from the command line — no browser needed:
curl is your sanity check: does the backend work? Yes? Then add the frontend.
WebAssembly: a binary the browser can run
WebAssembly (or WASM) [a portable, sandboxed (isolated execution environment) binary format that every modern browser can load and execute] is just that: a compiled binary the browser knows how to run.
Rust source compiled to a .wasm binary the browser loads.
Why it matters for us
Rust → .wasm → browser, with near-native performance
A compile target, not a language — Rust, C, C++, Go can all produce .wasm
We write Rust today, change the build target, get a .wasm file the browser runs
No JavaScript runtime cost on the hot path
The build pipeline — step 1: Rust source
Step 1: your Rust source.
The build pipeline — step 2: cargo + wasm-bindgen
Step 2: cargo compiles to a .wasm; wasm-bindgen generates JS glue.
The build pipeline — step 3: trunk bundles
Step 3: trunk bundles everything into a /dist directory the browser loads.
wasm32-unknown-unknown
# bashrustup target add wasm32-unknown-unknown
Rust target triples are arch-vendor-os:
wasm32 — 32-bit WebAssembly instruction set
unknown — no specific vendor
unknown — no specific OS (it is just a VM)
cargo build --target wasm32-unknown-unknown invokes rustc with that target. Output is target/wasm32-unknown-unknown/debug/your_crate.wasm.
wasm-bindgen — the JS glue layer
Pure WebAssembly only speaks integers and floats. It cannot return a String to JavaScript, and it cannot touch the DOM directly.
wasm-bindgen generates a tiny JavaScript shim that:
marshals strings, structs, closures across the JS↔︎WASM boundary
exposes browser APIs (DOM, fetch, setTimeout) to your Rust code
lets you #[wasm_bindgen] a Rust function and call it from JS
wasm-bindgen is the bridge: it lets your Rust code in the .wasm file read and modify the DOM that the browser built from your HTML.
You will rarely touch it directly — Yew and gloo_net use it under the hood.
Both frontend and backend depend on shared. The same struct is serialised by the server and deserialised by the client.
Yew — Rust UI framework
Yew is modelled on React [the dominant JavaScript UI library — Yew works similarly].
Components are functions that return Html
State lives in hooks [reusable functions starting with use_ that hold per-component state across re-renders] like use_state, use_effect_with
The framework re-runs the function on every state change
// Rustuseyew::prelude::*;#[function_component(App)]fn app() -> Html {let title ="Sequence inspector";let length =42;html!{<div><h1>{ title }</h1><p>{format!("Loaded {} bases", length) }</p></div>}}
Yew renders a <div> containing an <h1> and a <p>. Inside { ... } you put any Rust expression.
The render loop
Each render Yew builds a virtual DOM [an in-memory tree of the HTML you want, cheaper to construct and compare than the real browser DOM], then performs a diff/patch [compare the new vDOM to the previous one and apply only the minimal real-DOM changes] step.
You describe the page; state changes drive the rerender.
The html! macro
// Rust — html!{} looks like HTML but is parsed as Rust tokenshtml!{<div><h1>{"Sequence inspector"}</h1><p>{format!("length: {} bp", seq.len()) }</p></div>}
HTML-shaped syntax in Rust source. { ... } slots embed any Rust expression.
Differences from plain HTML:
Every tag must be closed (<br/>, not <br>)
Text goes inside { }: <p>{ "hi" }</p>
Multiple top-level elements: wrap in <></>
#[function_component(App)]
// Rust#[function_component(App)]fn app() -> Html {let sequence = use_state(String::new);let dna:&str=&sequence;html!{<p>{ dna }</p>}}fn main() {yew::Renderer::<App>::new().render();}
The attribute turns a plain fn into a Component named App. main mounts it.
Closures and move — 30 seconds
A closure [an inline anonymous function that captures variables from its enclosing scope] looks like |x| x + 1. move [keyword that makes the closure take ownership of its captured variables] is needed when the closure outlives the scope — for example when an event handler runs later, after the surrounding function has returned.
// Rustlet name =String::from("lambda");let say_hi =move|_|log::info!("hello, {name}");// owns `name`// `say_hi` can now be stored in a Callback and called from an event
Event handlers in Yew are stored in the framework and called later — so the closures we hand them are almost always move closures.
use_state — a value that survives re-renders
The handle is stable across renders; only its value changes.
State is the input’s value. Keystroke writes; the value attribute reads.
use_effect_with — run something when deps change
// Rustuse_effect_with((),move|_|{// body runs once on mount, because deps = ()log::info!("sequence inspector mounted");|| () // cleanup closure; () == "nothing to clean up"});
deps = () → run once, on first render
deps = some_state.clone() → run again whenever that state changes
The body returns a cleanup closure (for unsubscribing, cancelling timers, etc.)
spawn_local — run an async block on the event loop
spawn_local [the function that schedules an async block on the browser’s single-threaded event loop] hands an async block to the browser’s event loop. From there it runs cooperatively, just like a JS promise.
A route maps URL+method to a handler — an async fn returning something serialisable. See axum.
Path parameters and JSON bodies
// Rustuseaxum::extract::Path;asyncfn get_sample(Path(id):Path<String>) -> Json<SampleRecord>{let record = lookup_sample(&id);// your code Json(record)}let app =Router::new().route("/api/samples", get(list_samples)).route("/api/samples/{id}", get(get_sample));
Path<T> is an extractor [a typed argument in a handler signature that tells axum what to pull out of the incoming request — the URL path, a query string, a JSON body, headers, …] — axum parses the URL segment for you and hands you the typed value.
CORS — and why we usually avoid it
An origin [scheme + host + port] is the browser’s unit of trust. :8080 and :3000 are different origins.
The Same-Origin Policy blocks fetch from one origin to another unless the server opts in with CORS [Cross-Origin Resource Sharing headers].
Two ways to handle it:
Enable CORS on axum with tower_http::cors::CorsLayer::permissive() (real apps)
Proxy through trunk — trunk forwards /api/... to axum, browser sees one origin (today)