Tutorial: a guestbook

Build Guestbook: one book anyone can sign. New notes show up for everyone at once, a note's writer can take it back, and the whole book downloads as text. It runs on a server. The finished app is in examples/guestbook.

You need Rust (through rustup), Node 22, and the soda command (Getting started).

1. Make the app#

soda new --plain guestbook
cd guestbook
soda dev

--plain starts from a shared checklist that stores its own state in SQLite. (Without it you get the event-sourced board: see Events.) Open the address soda dev prints in two windows and add an item: it shows in both. Edit the words in src/routes/layout.rs and save. Both windows update in about a second, and the list is still there.

PathWhat
src/list.rsThe app's state: the list, in SQLite
migrations/The database schema, one file per change, run at startup
src/routes/The pages: a folder is an address, page.rs renders it, actions.rs handles its forms
src/components.rsShared #[component]s
src/main.rssoda_server::app!, naming the state
web/app.html, web/app.cssThe page shell, and the design tokens
tests/e2e.mjsEnd-to-end tests in real browsers

Delete what the guestbook doesn't need: src/list.rs, src/components.rs, src/routes/items/, migrations/0001_items.sql, and web/components/. Delete data/ too, for an empty database.

2. Store the entries#

The app's state is one type, made at startup and shared by every request (so it's Send + Sync). The guestbook's state is a SQLite pool in the app's data folder: soda_server::data(), which is data/ in the folder the app was built in, or SODA_DATA.

migrations/0001_entries.sql:

CREATE TABLE entries (
    id TEXT PRIMARY KEY,
    name TEXT NOT NULL,
    text TEXT NOT NULL,
    at INTEGER NOT NULL,
    by_session TEXT NOT NULL
);
CREATE INDEX entries_by_time ON entries (at);

src/book.rs, with sqlx:

use std::path::Path;

use sqlx::sqlite::{SqliteConnectOptions, SqliteJournalMode, SqlitePool, SqlitePoolOptions};

#[derive(Clone, Debug, sqlx::FromRow)]
pub struct Entry {
    pub id: String,
    pub name: String,
    pub text: String,
    #[sqlx(try_from = "i64")]
    pub at: u64,
    #[sqlx(rename = "by_session")]
    pub by: String,
}

pub struct Book {
    db: SqlitePool,
}

impl soda_server::App for Book {
    async fn start() -> Result<Self, Box<dyn std::error::Error + Send + Sync>> {
        Ok(Book::open(&soda_server::data().join("guestbook.db")).await?)
    }
}

impl Book {
    pub async fn entries(&self) -> soda::Result<Vec<Entry>> {
        sqlx::query_as("SELECT id, name, text, at, by_session FROM entries ORDER BY at, rowid").fetch_all(&self.db).await.map_err(unavailable)
    }

    // open, sign and take_back: see examples/guestbook/src/book.rs
}

fn unavailable(error: sqlx::Error) -> soda::Error {
    eprintln!("guestbook: the database: {error}");
    "The book can't be reached just now. Try again in a moment.".into()
}

Each method returns a soda::Result, so pages and actions can use ?. A soda::Error carries a message for the person using the app. Soda logs nothing itself: unavailable prints the database's error for you. If start returns an error, the server stops and prints it.

Name the state in src/main.rs:

mod book;

soda_server::app!(plain book::Book);

app! reads src/routes at compile time. It generates the router, a typed link for every page (link::about()), the app's Cx, Act and prelude, and main. The template's Cargo.toml already has sqlx (and tokio, for tests). build.rs rebuilds when a migration is added.

3. Render the page#

src/routes/page.rs is /. It imports Everything, the download from step 7, so it won't compile until then: leave that import and the "Download them" link out until you get there.

use super::actions::{Sign, TakeBack};
use super::downloads::Everything;
use crate::prelude::*;

pub fn head(_cx: &Cx) -> Head {
    Head::title("The book")
}

pub async fn page(cx: &Cx) -> Result<View> {
    let entries = cx.state.entries().await?;
    Ok(view! {
        <h1 class="sr-only">"The book"</h1>
        <Card class="grid gap-4 p-5">
            <form action=Sign class="grid gap-4">
                <Field label="Your name" name="name">
                    <Input name="name" value=cx.recall("name") placeholder="Ada" required attr:maxlength="60" attr:autocomplete="name" />
                </Field>
                <Field label="Your note" name="text">
                    <Textarea name="text" placeholder="What brought you here?" required attr:maxlength="280" attr:rows="3" />
                </Field>
                <div><Button primary submit>"Sign the book"</Button></div>
            </form>
        </Card>
        <section class="grid gap-3" aria-label="Entries">
            <div class="flex items-baseline justify-between gap-3">
                <h2 class="font-display text-xl font-semibold">{match entries.len() { 0 => "No one yet".to_string(), 1 => "1 entry".to_string(), n => format!("{n} entries") }}</h2>
                {(!entries.is_empty()).then(|| view! { <a class="soda-btn soda-btn-quiet" href=Everything download>"Download them"</a> })}
            </div>
            {if entries.is_empty() {
                view! { <Empty title="Be the first">"Sign the book above: your note shows here, for everyone who opens it."</Empty> }
            } else {
                view! {
                    <ol id="entries" class="grid gap-3">
                        {entries.iter().rev().map(|e| view! {
                            <li class="entry grid gap-1.5 rounded-card bg-surface p-4 shadow-raised" data-entry=&e.id>
                                <p class="flex items-baseline gap-2">
                                    <strong class="name font-semibold">{&e.name}</strong>
                                    <span class="text-sm text-muted"><Time at=e.at /></span>
                                    {(e.by == cx.session.id).then(|| view! {
                                        <Button quiet small class="ml-auto" on:click=TakeBack(e.id.clone()) attr:aria-label=format!("Take back your note, {}", e.name)>"Take back"</Button>
                                    })}
                                </p>
                                <p class="text whitespace-pre-line">{&e.text}</p>
                            </li>
                        })}
                    </ol>
                }
            }}
        </section>
    })
}
  • A page can be an async fn. It reads cx.state (the book) and cx.session (the browser's session, from a cookie).
  • cx.recall("name") is a value this session saved earlier: here, the last name it signed with. Sessions survive a server restart.
  • In view!, text goes in quotes and Rust in braces. Any expression can be an attribute value.
  • Card, Field, Input, Textarea, Button, Empty and Time are Soda components (Reference). <Time at=…/> shows "5 minutes ago" in the reader's time zone.
  • head sets the tab title.

4. Post a form#

The form posts to Sign. Write it in src/routes/actions.rs:

use crate::book::Entry;
use crate::prelude::*;

#[derive(Form)]
pub struct Signing {
    #[form(max = 60)]
    pub name: String,
    #[form(max = 280)]
    pub text: String,
}

#[action]
pub async fn sign(cx: &mut Act, form: Signing) -> Result {
    let entry = Entry { id: new_id(), name: form.name.clone(), text: form.text, at: soda_server::now_ms(), by: cx.session.id.clone() };
    cx.state.sign(entry).await?;
    cx.remember("name", form.name);
    cx.keep(&["name"]);
    cx.say("Signed the book.");
    Ok(())
}
  • #[derive(Form)] parses the fields. A missing or too-long field shows an error under it, and the action doesn't run.
  • #[action] generates Sign, which the form names, at /api/_/sign.
  • cx.remember saves the name for this session. cx.keep keeps the name field filled when the form clears. cx.say shows a toast.

When an action finishes, every open page re-renders. The other window shows the new note with no extra code.

5. Check who's acting#

The page only shows "Take back" on your own notes, but anyone can post to an action. So the action checks too:

#[action]
pub async fn take_back(cx: &mut Act, entry: String) -> Result {
    if !cx.state.take_back(&entry, &cx.session.id).await? {
        return Err("That note isn't yours to take back.".into());
    }
    cx.say("Took your note back.");
    Ok(())
}

A button passes arguments: on:click=TakeBack(e.id.clone()) posts the id as entry. Returning Err with a message refuses the request: the person sees the message and nothing changes. Soda rejects cross-site requests before any action runs.

6. Add a page and a layout#

src/routes/about/page.rs is /about:

use crate::prelude::*;

pub fn head(_cx: &Cx) -> Head {
    Head::title("About")
}

pub fn page(_cx: &Cx) -> View {
    view! {
        <article class="grid gap-3 text-lg">
            <h1 class="font-display text-2xl font-semibold">"About this book"</h1>
            <p><a class="font-semibold text-accent underline underline-offset-4" href=link::root()>"Back to the book"</a></p>
        </article>
    }
}

src/routes/layout.rs wraps every page:

use crate::prelude::*;

pub fn layout(cx: &Cx, children: View) -> View {
    view! {
        <header class="mx-auto mt-8 mb-6 grid w-full max-w-160 gap-4 px-4">
            <p class="font-display text-3xl font-bold tracking-tight">"Guestbook"</p>
            <Tabs label="Pages">
                <Tab href=cx.link(link::root())>"The book"</Tab>
                <Tab href=cx.link(link::about())>"About"</Tab>
            </Tabs>
        </header>
        <div class="mx-auto grid w-full max-w-160 gap-6 px-4 pb-16">{children}</div>
    }
}

Links are typed: renaming or removing a page is a compile error at every link to it. cx.link marks the current page, so the tab shows as selected. Following a link updates the page in place, and Back works. src/routes/not_found.rs renders unknown addresses.

7. Offer a download#

src/routes/downloads.rs:

use crate::prelude::*;

#[download]
pub async fn everything(cx: &Cx) -> Result<Download> {
    let text: String = cx.state.entries().await?.iter().map(|e| format!("{} ({}):\n{}\n\n", e.name, soda::ui::utc(e.at), e.text)).collect();
    Ok(Download::text("guestbook.txt", "text/plain", text))
}

Link to it like a page: href=Everything download. For a page to print instead of a file, use Download::page.

8. Change the look#

web/app.css holds the design tokens. Every color, font, radius and shadow in the views must be one (bg-surface, text-muted, rounded-card); the build fails on any that isn't. Warm the accent:

@theme {
  --color-accent: light-dark(oklch(0.55 0.15 40), oklch(0.78 0.12 50));
}

Save, and open pages pick up the new styles in about 0.2 s. See Styling.

What soda dev does#

You changeResult
A page, layout, component or actionPatched in about a second. Pages re-render; data, sessions and open pages stay
A new routePatched the same way
web/app.htmlPages reload
web/app.cssStyles swap in place
A type's fields (say, on Book)Full rebuild and restart. Pages reload; the database and sessions stay
A compile error or a panicShown over the page, with its location, until you fix it

println! output goes to the soda dev terminal. More in soda dev.

9. Test it#

soda check   # cargo test, Clippy, and the token check
soda test    # check, then the build and tests/e2e.mjs in real browsers

tests/e2e.mjs runs the built server on a free port, with its own SODA_DATA, and drives two people in Chromium and WebKit. Ada signs and Bob sees it live; Bob can't take back Ada's note; the download has the book; and a server restart keeps the book and the sessions. Copy its patterns: wait for what the page shows, never for time.

10. Ship it#

soda build            # dist/ and target/release/guestbook
cargo run --release   # http://127.0.0.1:3000

A host needs the program, dist/ and a data folder:

VariableSets
SODA_ADDRThe address to listen on, e.g. 0.0.0.0:8080
SODA_DATAThe data folder
SODA_DISTWhere dist/ is

SODA_DATA and SODA_DIST default to data/ and dist/ in the folder the program was built in, so a host that has only the program and dist/ must set both.

Or let soda deploy build a container image (about 150 MB, serving on 8080, data in a volume):

soda deploy --to ssh://you@your-server     # build for that host and run it there on port 80
soda deploy                                 # just the image, guestbook:latest
soda deploy --image registry.example.com/guestbook:1 --platform linux/amd64 --push

--to takes any host Docker can reach (ssh://…, tcp://…). Each deploy replaces the running container and keeps the guestbook-data volume, so the book and sessions survive. A later deploy rebuilds only what changed (about 11 s for a one-line page change).

As it grows#

  • Schema changes. Add a migration (0002_entries_by_name.sql); it runs once at startup.
  • Fewer re-renders. A page declares what it shows with cx.listen("book"); an action declares what it changed with cx.notify("book"). Then pages listening for something else are skipped. Pages that listen for "book", pages that never call listen, and the acting session's pages still re-render. If a page shows something an action changed without listening for it, soda dev says so over the page.
  • Your own routes. For a webhook, feed or health check, App::routes returns an axum Router with the app's state. A handler that changes what pages show takes the Pages extractor and calls pages.notify(["book"]). See Reference.

Next#

  • Reference: components, view!, routes, actions, forms, Cx, the CLI.
  • Events: an app built on events, with history and undo.
  • Local-first: the same framework, running in each person's browser.
  • Styling: tokens and components.

This page is docs/tutorial.md in the SDK, built into this site as it is.

Esc