Keyboard shortcuts

Press ← or → to navigate between chapters

Press S or / to search in the book

Press ? to show this help

Press Esc to hide this help

Build your first Slabs app in 10 minutes

You are going to build a working note-taking app from scratch. By the end of this tutorial, you will have a SQLite migration, two self-contained HTTP endpoints with co-located tests, and a running local server with live HTMX form updates.

Prerequisites

Install mise so you have pinned versions of rust, standalone tailwindcss v4, and cargo-nextest. Install the slabs CLI from crates.io (or run it directly inside the Slabs workspace):

cargo install slabs-cli

Create a new application

Generate a standalone project and run slabs doctor to verify your toolchain and defaults:

slabs new app quicknotes
cd quicknotes
slabs doctor

Look at the files slabs new app created:

FileRole
Cargo.tomlDeclares slabs-framework = "0.5" (imported in Rust as slabs), slabs-build = "0.5", axum, maud, sqlx, and safety lints including unsafe_code = "forbid".
build.rsCalls slabs_build::discover(); so Cargo registers every .rs file in slabs/<feature>/ and jobs/ at compile time.
src/lib.rsInvokes slabs::discover_slabs!();, defines MIGRATOR, and exports boot plus a #[cfg(test)] test_app helper.
src/main.rsCalls slabs::init_tracing(), loads AppConfig::from_env("quicknotes"), boots the app, and binds the HTTP server.
assets/input.cssImports Tailwind CSS v4 and scans ../slabs for utility classes.
Dockerfile and litestream.ymlMulti-stage cargo-chef container build with pinned Litestream v0.3.13 replication and docker-entrypoint.sh.
.claude/skills/Five bundled agent skills for authoring slabs, migrations, reviews, deploys, and incident fixes.

There is no routes.rs, models/, or controllers/ folder anywhere in the tree.

Add a SQL migration

Create migrations/0001_notes.sql to define a notes table:

CREATE TABLE IF NOT EXISTS notes (
    id TEXT PRIMARY KEY NOT NULL,
    body TEXT NOT NULL,
    created_at TEXT NOT NULL
);

CREATE INDEX IF NOT EXISTS idx_notes_created_at
    ON notes (created_at DESC);

Apply the migration to a local SQLite database and write the full schema snapshot to schema.sql:

DATABASE_URL="sqlite://quicknotes.db?mode=rwc" slabs db migrate
DATABASE_URL="sqlite://quicknotes.db?mode=rwc" slabs db dump-schema

Open schema.sql. It contains your notes table and the twelve system tables owned by Slabs (slabs_sessions, slabs_jobs, slabs_incidents, slabs_audit_log, and eight others). Read schema.sql before writing any new SQL query.

Write a slab to list notes

Create slabs/notes/list_notes.rs. Do not edit src/lib.rs or any router file. slabs-build discovers and registers this file on the next build.

#![allow(unused)]
fn main() {
use axum::extract::State;
use slabs::prelude::*;

pub fn slab() -> SlabDef {
    SlabDef::get("/", handle)
        .name("notes.list_notes")
        .summary("Render the notes page and creation form")
}

#[derive(sqlx::FromRow)]
struct NoteRow {
    id: String,
    body: String,
    created_at: String,
}

async fn handle(State(ctx): State<AppCtx>) -> SlabResult<Markup> {
    let notes: Vec<NoteRow> = sqlx::query_as(
        "SELECT id, body, created_at
         FROM notes
         ORDER BY created_at DESC, id DESC
         LIMIT 50",
    )
    .fetch_all(ctx.db.reader())
    .await?;

    let styles = ctx.assets.stylesheet_urls();
    let scripts = ctx.assets.behavior_urls();

    Ok(html::document(
        "Quicknotes",
        &styles,
        &scripts,
        maud! {
            main class="max-w-2xl mx-auto p-6 space-y-6" {
                h1 class="text-2xl font-bold" { "Quicknotes" }

                form hx-post="/notes"
                     hx-target="#notes-list"
                     hx-swap="afterbegin"
                     "hx-on::after-request"="this.reset()"
                     class="flex gap-2" {
                    input type="text"
                          name="body"
                          placeholder="Write a note..."
                          required
                          class="input flex-1";
                    button type="submit" class="btn" { "Save" }
                }

                section id="notes-list" class="space-y-2" {
                    @for note in &notes {
                        article id=(format!("note-{}", note.id)) class="card p-3" {
                            p class="text-sm" { (note.body) }
                            p class="text-xs text-muted-foreground mt-1" { (note.created_at) }
                        }
                    }
                }
            }
        },
    ))
}

#[cfg(test)]
mod tests {
    use axum::http::StatusCode;

    #[tokio::test]
    async fn renders_home_page() {
        let app = crate::test_app().await;
        let res = app.get("/").await;
        assert_eq!(res.status, StatusCode::OK);
        assert!(res.text().contains("Quicknotes"));
    }
}
}

Three mechanisms are at work in this file:

  1. ctx.db.reader() executes the SELECT on the 16-connection read-only SQLite WAL pool.
  2. html::document(...) loads Basecoat UI, HTMX 2, SSE, Idiomorph, Alpine.js 3, and your compiled Tailwind stylesheet from /_slabs/vendor/ and /assets/{hash}/....
  3. #[cfg(test)] mod tests boots an isolated in-memory SQLite database through crate::test_app().await.

Write a slab to create a note

Create slabs/notes/create_note.rs. It validates form input, generates a prefixed ULID with id::new("nte"), inserts the row inside a BEGIN IMMEDIATE transaction, and returns an HTML fragment that HTMX prepends to #notes-list.

#![allow(unused)]
fn main() {
use axum::{extract::State, http::StatusCode, Form};
use chrono::Utc;
use serde::Deserialize;
use slabs::prelude::*;

pub fn slab() -> SlabDef {
    SlabDef::post("/notes", handle)
        .name("notes.create_note")
        .summary("Insert a note and return an HTML fragment")
}

#[derive(Debug, Deserialize)]
pub struct Input {
    pub body: String,
}

async fn handle(
    State(ctx): State<AppCtx>,
    Form(input): Form<Input>,
) -> SlabResult<(StatusCode, Markup)> {
    let body = input.body.trim().to_string();
    if body.is_empty() {
        return Err(SlabError::validation("body", "note body cannot be blank"));
    }

    let note_id = id::new("nte");
    let now = Utc::now().to_rfc3339();

    let mut tx = ctx.db.begin().await?;
    sqlx::query("INSERT INTO notes (id, body, created_at) VALUES (?, ?, ?)")
        .bind(&note_id)
        .bind(&body)
        .bind(&now)
        .execute(&mut *tx)
        .await?;
    tx.commit().await?;

    let fragment = maud! {
        article id=(format!("note-{note_id}")) class="card p-3" {
            p class="text-sm" { (body) }
            p class="text-xs text-muted-foreground mt-1" { (now) }
        }
    };

    Ok((StatusCode::CREATED, fragment))
}

#[cfg(test)]
mod tests {
    use axum::http::StatusCode;

    #[tokio::test]
    async fn creates_note_and_rejects_blank_input() {
        let app = crate::test_app().await;

        let bad = app.post_form("/notes", &[("body", "   ")]).await;
        assert_eq!(bad.status, StatusCode::UNPROCESSABLE_ENTITY);

        let created = app.post_form("/notes", &[("body", "Ship Slabs")]).await;
        assert_eq!(created.status, StatusCode::CREATED);
        assert!(created.text().contains("Ship Slabs"));

        let list = app.get("/").await;
        assert!(list.text().contains("Ship Slabs"));
    }
}
}

Format, check, and run the server

Format both src/ and the auto-discovered slabs/ directory, then run the full 6-step slabs check gate (formatting, static [security] scan, Clippy, Rustdoc, doctests, and parallel tests):

slabs fmt
slabs check --no-docs

Compile Tailwind CSS and start the live development server:

slabs dev

Open http://127.0.0.1:3000. Submit a note and watch HTMX prepend it without a full page reload. In development mode (SLABS_ENV=development), visit http://127.0.0.1:3000/_slabs/manifest to inspect the JSON route manifest and http://127.0.0.1:3000/health/ready to check database readiness.

What you built

  • slabs-build discovered every .rs file in slabs/<feature>/ at compile time without a central router file.
  • ctx.db.reader() ran reads concurrently, and ctx.db.begin().await? opened a BEGIN IMMEDIATE write transaction.
  • Each slab carried its own input validation, SQL, HTML template, and isolated #[tokio::test] tests.

Next, follow Add live updates with SSE, HTMX, and Idiomorph to push live DOM updates and online presence to every connected browser.