How Soda works
Soda has three layers:
- The framework (
soda, inkit/): routes,view!, components, actions, forms and typed links. - A backend: where the app runs.
soda-server(server/),soda-local(the repository's root) orsoda-static(static/). - The CLI (
soda, incli/):new,dev,check,test,build,deploy,events.
An app is written against the framework. Its backend decides what a page reads and what an action can change.
Maintainers: the decisions, milestones and measurements behind this are in design-notes.md.
The idea#
A page is a function of what it reads and its address. An action changes something, and every open page re-renders. That removes most of what makes Next.js and SvelteKit complicated: loaders, caching, revalidation, loading states, and the line between server and client components.
| Next.js / SvelteKit | Soda |
|---|---|
app/blog/[slug]/page.tsx, +page.svelte | src/routes/blog/[slug]/page.rs |
layout.tsx, +layout.svelte | layout.rs, nested the same way |
not-found.tsx, error.tsx, +error.svelte | not_found.rs, error.rs |
(group), [...rest], [[optional]] folders | The same |
| Server actions, form actions | #[action] functions beside the page |
<Link href>, goto() | <a href=link::…> (typed); cx.go(…) in an action |
generateMetadata, <svelte:head> | pub fn head(cx) -> Head |
Loaders, fetch, revalidatePath, suspense | Nothing: a page reads what it needs as it renders |
useState, $state | Datastar signals (bind:, show=) |
| Client components, islands | Web components on the app's own utilities |
cn() with tailwind-merge | cn, read off the app's compiled stylesheet |
| Fast Refresh, HMR | soda dev: Rust patched into the running app in about a second |
| API routes | #[download]s, and on app!(plain …) the app's own routes (App::routes) |
An app's files#
pantry/
Cargo.toml
build.rs fn main() { soda_build::routes(); }
events.lock the events' shapes
src/
main.rs mod components; mod model; soda_local::app!(…)
model.rs the model
components.rs shared components
routes/
layout.rs wraps every page
page.rs /
not_found.rs
shelves/
page.rs /shelves
[shelf]/
layout.rs wraps every page under /shelves/:shelf
page.rs /shelves/:shelf
actions.rs what that page's forms post to
(account)/
settings/page.rs /settings
web/
app.html the shell
app.css the design tokens
components/expiry.js a browser component (loads itself)
kit.js any other browser code
tests/e2e.mjssrc/main.rs declares the app's modules and calls the backend's app! macro, naming the model
or state. The macro writes the rest of the program, main included:
app!;Routes#
| File | What it is |
|---|---|
page.rs | The page: pub fn page(cx) -> View (or Result<View>), and an optional head |
layout.rs | pub fn layout(cx, children: View) -> View, around every page at and under its folder |
actions.rs | Actions for the pages in its folder (an #[action] in any of the folder's files counts) |
not_found.rs | Shown when nothing matches, or a page returns NotFound |
error.rs | Shown when a page returns another error |
downloads.rs | #[download]s: pub fn name(cx) -> Result<Download> |
| Folder | Matches |
|---|---|
shelves | /shelves |
[shelf] | One segment, as shelf: String |
[...path] | One or more segments, as path: Vec<String> |
[[lang]] | An optional segment, as lang: Option<String> |
(group) | Nothing: groups routes under a shared layout without adding to the URL |
// src/routes/shelves/[shelf]/page.rs
use Params;
use AddItem;
use crate*;
Cxis what a page reads:cx.params,cx.page(the address and query), and what its backend adds (see Backends).cx.query("tab")reads the query,cx.here_with(…)links to this page with its query changed.- Each folder has a generated
Params, which its files read assuper::Params. Params are text. A page that wants another type parses it and returnsNotFoundwhen it can't. NotFoundrenders the nearestnot_found.rs. Any other error renders the nearesterror.rs.- Layouts nest from the root down. A layout is left alone when you move between the pages under it, so its open menus, scroll and focus stay.
Typed links#
Every page gets a link function, taking its params:
root // "/"
shelf // "/shelves/rice"
shelf.with // "/shelves/rice?tab=history"A link to a page that doesn't exist, or with the wrong params, doesn't compile. Rename a folder and the compiler lists every link to fix.
How the router is built#
Rust can't read a folder at run time, so the compiler does. The backend's app! expands to
soda::__routes!, a procedural macro that reads src/routes/ on every compile (hot patches
included) and writes:
- a module per folder (
[shelf]isshelf,(account)isaccount), with itsROUTE, itsParamsand its files; - the matcher, most specific route first, rendering each page inside its layouts;
- the action dispatcher and the
link::functions; - the app's
Cx,Actandprelude, over its backend.
A route the router can't make sense of is a compile error naming the folder: two pages for one
address, two folders that would be one module, a page.rs without page. The rest of the router is still
written, so the app compiles around it. build.rs (soda_build::routes()) tells Cargo to compile
again when a folder is added. rust-analyzer expands the macro, so completion works on routes and
links.
Moving between pages#
soda.js intercepts links to the same site and asks the backend for the new page, which arrives
over the page's stream and is morphed in. Back and Forward work the same way. On a static site
there's no backend to ask, so the browser follows links itself. After a move to a new
path, it scrolls to the top (or back to where that history entry was) and moves focus to the
<h1>. A move within a page (a tab, a filter) keeps both. Moves between paths animate as view
transitions, unless the reader has reduced motion on.
Views and components#
view! - Text goes in quotes, and everything is escaped.
{…}takes text, numbers, aView, anOptionor an iterator of views. class="…"is literal, so Tailwind finds every class.class:name=condadds one whencondholds;class=expradds classes from a value. They're joined into one attribute bycn.on:click=takes an action or a Datastar expression in quotes.bind:draftbinds a signal andshow="$open"shows and hides. Nothing built from data can become code.view!produces maud'sMarkup, sohtml!still works beside it.
Errors point at the app's own source and say what to write instead.
A component is a function:
// <ItemRow {item} compact class="mt-2" />Props are named arguments. Each is required unless it's a bool, an Option, class, attrs,
children or marked #[prop(default)]. A missing prop is a compile error naming it. Components
render on the backend like pages: no JavaScript, nothing to hydrate.
The SDK's components cover what most apps need: Button, Input, Textarea, Select, Field,
Card, Chip, Tabs, Dialog, Menu, EditInPlace, Lists (drag between lists),
Time, Clock, Countdown, History, Empty, Avatar. The reference lists
their props.
What a page shows belongs in its address. The path is the place; the query refines it (a filter, a tab, an open dialog). So a reload, Back and a shared link all keep it, and two tabs each show their own.
Actions and forms#
// src/routes/shelves/[shelf]/actions.rs
use Params;
use crateCommand;
use crate*;
pub async - A view names an action in CamelCase:
<form action=AddItem>posts toadd_item, andon:click=Remove(id)postsidtoremove. The action's URL is its route's, filled in from the page, so it gets the page'sParamsand nobody writes a URL. #[derive(Form)]parses the posted form into typed fields and checks them (min,max,message). A field that fails goes back to the form with its message, and the action doesn't run.- After an action, every open page re-renders. The form that posted is cleared, except fields the
action keeps (
cx.keep(&["kind"])). An action can also move the page (cx.go), show a message (cx.say) or clear signals (cx.clear). - A
#[download]is a file the page offers (a calendar entry, an export), made when it's asked for:<a href=Calendar download>.
Live pages#
Each open page holds one Datastar stream. When anything changes, the backend renders the page again and Datastar morphs in what's different. How "anything changes" is known depends on the backend:
- Server: a change re-renders the open pages that read it. A page that called
cx.listen(topic)re-renders for changes that touch that topic: on events, the model says what each event touches (Model::touches, so an undo or another server's change says it too); onapp!(plain …), the action does (cx.notify(topic)). A page that never calledlistenre-renders for every change, and the acting session's own pages always do. Undersoda dev, each page that listens is checked: after a change it wasn't drawn again for, it's drawn as a stranger would see it, and one that comes out different says so over it ("/b shows what bump_a changed, but doesn't listen for it"), since someone else's copy of it would go out of date. A topic itlisten_softlys for re-renders it at most once a second (a count that every change touches). Who's here, names and the clock re-render only the pages that read them (cx.here(),cx.name_of,cx.now()), at most once a second each when they crowd in. A page whose tab is hidden waits until it's shown. Changes that come while a page is drawn make one more drawing, however many there were. Each drawing sends the whole page, but the stream is compressed across drawings (zstd in Chrome and Firefox; in Safari gzip while drawings fit its 32 kB window, brotli once they don't), so one much like the last costs what changed: a kanban board's 171 kB drawing goes as about 1 kB. Past a quarter of the machine's memory in encoders, a new stream takes a cheaper encoding its browser takes, or goes uncompressed. Everything else the server answers is compressed too. An app can limit what one person or network does at once (app!(…, limits = …): actions a second, pages open), how many pages it has room for (past that, a page waits in line), and what it sends in a day. A session nothing has used for ten minutes is forgotten, and taken back from its cookie if it comes again. - Local-first: the engine re-renders when it folds a new event, yours or a member's.
- Static: pages don't change once built. Under
soda dev, each has a stream so patches show.
Browser components#
Anything that must run in the browser (a ticking countdown, dragging, a chart) is a web component
in web/components/. Each file there loads itself, and can import npm packages:
// web/components/expiry.js
In view! it's used like any element: <pantry-expiry at=item.expires />. It's written with the
same Tailwind utilities as the views, and each named part takes classes from outside
(badge-class="…"), merged after its own.
Styling#
Styling covers the look: Tailwind v4, with every color, font, radius and shadow a token, and a check that refuses anything else. Under it are three pieces:
cnwith no table. A class given to a component must win over the component's own. The build reads what each utility sets off the app's compiled stylesheet (app.classes.json), andcndrops a class when a later one sets the same properties. It's exact for the app's own utilities and can't drift from Tailwind.- One stylesheet in every shadow root. The build writes
app.styles.js, the app's utilities as oneCSSStyleSheetthat every component adopts. The tokens reach in by inheritance. One shared sheet costs tens of milliseconds where a sheet per component costs hundreds or more. class:names reach Tailwind. The build lists the classesclass:directives use (scripts/view-classes.mjs), and the token check checks them too.
soda dev#
soda dev builds, serves and watches the app. It uses Dioxus's Subsecond to patch changed Rust
into the running program, so nothing restarts:
| You change | What happens | About |
|---|---|---|
| A page, layout, component or action | Patched; the open pages re-render in place | 0.6 to 1.5 s |
| A new or removed route file | Patched like an edit | 1.2 to 1.7 s |
| A style, token or class | The stylesheet is swapped in place | 0.2 to 0.3 s |
A type's shape, Cargo.toml | A full build and restart, then a reload that keeps your place | 5 to 6 s |
| A mistake | It's shown over the page, with where, until it's fixed | 0.2 s for a typo; about 1.4 s for a compile error |
| A panic | It's shown over the page, with where; fixing it brings the page back | about 1 s |
What the app holds survives every patch: a server's state, sessions and open pages, or a
local-first app's data, which lives in the browser. For a local-first app, soda dev also runs a
store of its own over SQLite, so nothing but Rust and the CLI is needed. Hot-patching
explains how the patching works.
Backends#
A backend is where an app runs. The framework doesn't depend on any of them; each depends on the
framework and implements its seam. src/main.rs names one:
app!; // a server, storing a model's events
app!; // the same, a model for each [board] in the address
app!; // a server, storing its own state
app!; // local-first, in each person's browser
app!; // static, rendered at build timeFramework (soda) | Server | Local-first | Static | |
|---|---|---|---|---|
| State | — | A soda::Model's events, or any Send + Sync state (start) | The open space's model | What load reads at build time |
| Per person | — | A session, in a sealed cookie | A device, with its own keys | Nothing: every reader sees the same page |
| Actions | #[action], #[derive(Form)] | cx.act(command), or async code with the session | cx.act(command): signed, sealed, synced | None (refused, saying why) |
| Redraws | The stream, morphs | After every action (by topic on plain) | When an event is folded | Never, once built |
| Browser code | soda.js | Nothing more | soda-local.js: passkeys, the worker, sync | Nothing more |
The seam#
Cx keeps what's the framework's (params, page, links, the query) and derefs to the
backend's Read. Act does the same for Write. So what a page reads beyond its address is the
backend's:
| Backend | A page reads |
|---|---|
| Server, on events | cx.app (the model), cx.me (who's looking), cx.history(), cx.here(), cx.undo(), and with per, cx.spaces() |
Server, plain | cx.state (the app's state), cx.session |
| Local-first | cx.app (the open space's model), cx.space, cx.me |
| Static | cx.state (what load read) |
On a server or a static site, pages, layouts, heads and downloads may be async fn; the router
awaits them.
soda::backend::Bare, a backend that reads only the address, is what Soda's own tests run on.
On a server#
soda-server serves the app with axum:
| Request | Answer |
|---|---|
GET /any/path | The shell with the page rendered in it, and a session for a new browser |
GET /api/stream?page=… | The page's Datastar stream: rendered now, then after every change |
POST /api/page | The page moved to another address |
POST /api/_/<route>/<action> | Runs an action |
GET /api/_/<route>/<download> | A download |
/api/undo, /api/redo, /api/scrub, /api/me, /api/focus | On events: undo, history, names, presence |
| Anything else | A file from dist/, or on app!(plain …) the app's own routes (App::routes) |
A session is a random id and its memory, in a cookie the server seals with its key
(soda-session). The key and the app's files live in its data folder (SODA_DATA, data/ by
default), so a restarted server takes every browser back as it was. soda deploy builds a
container image, or with --to ssh://… runs it on any Docker host.
On events (the default), the app is a soda::Model: decide turns a command into events,
evolve applies one, and step and travel undo. soda::timeline::Timeline folds the changes
into the state now, the state after any change, the history in words, and each person's undo.
soda-store keeps the events in SQLite or Postgres, and checks every append against the shapes
events.lock records. Events covers the model.
app!(board::Board per board) makes each [board] in the address a model of its own: its own
stream in the store (app:<board>), history, undo, who's here and open pages. A change in one
draws only that board's pages, and changes to different boards don't wait for each other. A board
is read from the store when a page first opens it, and let go (saving a checkpoint, if the model
saves them) once no page has had it open for ten minutes. A page outside [board] (/, listing
them) reads cx.spaces(): each board with something kept in it, and when it last changed. Its
cx.app is a model with nothing in it, and it can't act. Every request soda.js sends to /api/
says which page sent it (Soda-At), so Undo, history, names and presence go to that page's board.
per board with no [board] folder in src/routes doesn't compile.
A page that shows everyone at its address the same takes &Everyone<Params> in place of
&Cx<Params>. Everyone reads what Cx does of the app (cx.app, who's here, the history, the
address and links, the clock) and nothing of who's looking: a page that reads cx.me, the session
or undo doesn't compile. So the server draws it once a change for each address, the first page
there to be drawn again drawing it and the rest taking that drawing, and keeps it while a page shows
it. What's each person's own goes in <Mine with=you />: fn you(cx: &Cx) -> View is drawn for
each of them into the drawing they share (their name, their Undo). What's marked data-person with
someone's id is marked data-you on their page, so their own roundel can be ringed and their own
"is editing" tag hidden with no <Mine> at all. Layouts on &Everyone around it are drawn into it
too (the board's sign and history line); a layout on &Cx, and the head, are drawn for each person
around it, and someone looking back at the history has the page drawn for them alone. A thousand
pages on the kanban template, drawn for each change, cost the server 673% of a core; on Everyone,
193% (soda load counts the shared drawings by route).
// src/routes/b/[board]/page.rs
Local-first#
soda-local runs the app in each person's browser, in its service worker. Each space is a
signed, encrypted log, synced through a store that can't read it. Accounts, passkeys, devices,
sharing, presence and undo come with it. The address names the space (/~3fa9c2e1b0/shelves/rice),
so two tabs can show two spaces. The model is the same soda::Model a server runs.
Local-first builds one, and the engine explains how it stays
correct.
Static#
soda-static renders every page once, at build time, into files. A route with params lists its
pages with params(cx) -> Vec<Params>; leaving it out is a compile error. not_found.rs becomes
404.html, each page's head fills its <title>, description and og: tags, and when the site sets its
url the build writes a sitemap. Actions, #[prerender], and downloads that take arguments or sit
under params are refused. Under
soda dev, it serves its pages like a server and re-renders them when a file WATCH names changes.
sodakit.dev is one. Static sites builds one.
This page is docs/framework.md in the SDK, built into this site as it is.