A web app in Jennifer from scratch

Jennifer

Routes, forms, a database, logins, templates and CSRF protection, with nothing but the modules that ship with the interpreter.

November 2026, by @mplx.
Based on Jennifer 0.26.0

Powered by Jennifer's Cantrip - Markdown into slide decks, https://github.com/jennifer-language/cantrip
1 / 20

What we build, and with what

app.j            config, middleware, handlers, routes, serving
src/store.j      SQL: migrations, members, books
src/views.j      HTML templates
src/store_test.j tests against a throwaway database
addmember.j      a CLI to create a member
healthcheck.j    probes /healthz, for containers
public/static/   CSS

All bundled: web, sql, sqlmigrate, session, kvstore, tengine, crypto. No decks, no vendor/.

2 / 20

The smallest web app

import "web.j" as web;
func hello(ctx as web.Context) {
    web.text($ctx, 200, "hello, " + web.query($ctx, "name") + "\n");
}
def app as web.App init web.new();
$app = web.get($app, "/hello", hello);
web.run($app, "127.0.0.1:8080");
$ jennifer serve hello.j        # --watch: restart on every save
GET /hello?name=Ada -> 200 hello, Ada     HEAD /hello -> 200
GET /nope           -> 404                POST /hello -> 404
3 / 20

Shelf's route table

def app as web.App init web.new();
$app = web.before($app, guardCsrf);        # middleware, in this order
$app = web.before($app, requireLogin);
$app = web.get($app, "/", listBooks);
$app = web.get($app, "/login", showLogin);
$app = web.post($app, "/login", doLogin);
$app = web.post($app, "/logout", doLogout);
$app = web.post($app, "/books", addBook);
$app = web.post($app, "/books/:id/done", markDone);
$app = web.get($app, "/healthz", health);
$app = web.get($app, "/static/*path", staticFile);

Handlers run concurrently: never write a top-level def from one.

4 / 20

Configuration from the environment

# NAME, or the contents of the file NAME_FILE names
func setting(name as string, fallback as string) {
    def path as string init os.getEnv($name + "_FILE");
    if ($path != "") { return strings.trim(fs.readString($path)); }
    if (os.hasEnv($name)) { return os.getEnv($name); }
    return $fallback;
}
def dsn as string init setting("SHELF_DB_DSN", "");
def csrfSecret as string init setting("SHELF_CSRF_SECRET", "");
if ($dsn == "" or len($csrfSecret) < 32) {
    io.eprintf("shelf: set SHELF_DB_DSN, SHELF_CSRF_SECRET\n");
    exit 2;
}
5 / 20

The database: MariaDB through sql

def conn as sql.Connection init sql.open("mariadb", $dsn);
# "shelf:PASSWORD@tcp(127.0.0.1:3306)/shelf"
6 / 20

Migrations with sqlmigrate

def const MIGRATIONS as list of mig.Migration init [
    mig.Migration{version: "001", description: "members",
        up: ["CREATE TABLE members (id INT AUTO_INCREMENT PRIMARY KEY," +
            " name VARCHAR(64) NOT NULL UNIQUE," +
            " pwhash VARCHAR(255) NOT NULL)"],
        down: ["DROP TABLE members"]},
    # 002 "books": id, title, author, added_by -> members(id), done
];

store.open($dsn): sql.open, then mig.migrate($conn, MIGRATIONS), at every start, with errdefer sql.close($conn).

7 / 20

Reading and writing rows

# books(conn): every book, unread first
def rows as sql.Rows init sql.query($conn,
    "SELECT b.id, title, author, name, done FROM books b" +
    " JOIN members m ON m.id = added_by ORDER BY done, b.id");
while (sql.next($rows)) {
    $out[] = Book{id: sql.asInt($rows, 0),
        title: sql.asString($rows, 1),
        author: sql.asString($rows, 2),
        addedBy: sql.asString($rows, 3),
        done: sql.asBool($rows, 4)};
}
8 / 20

Passwords: argon2id

def h as string init crypto.hashPassword("argon2id", $password);  # add
# login(): the member's id, or 0
def rows as sql.Rows init sql.query($conn,
    "SELECT id, pwhash FROM members WHERE name = ?", $name);
defer sql.closeRows($rows);
if (not sql.next($rows)) { return 0; }
def hash as string init sql.asString($rows, "pwhash");
if (not crypto.verifyPassword($password, $hash)) { return 0; }
return sql.asInt($rows, "id");
$ echo 'correct horse battery' | jennifer run addmember.j ada
member 1: ada
9 / 20

Sessions: a fresh id at every login

# doLogin, once store.login returned an id:
def sid as string init session.create($sessions, SESSION_TTL);
def data as json.Value init json.map({"member": $id, "name": $name});
session.save($sessions, $sid, $data, SESSION_TTL);
web.setCookie($ctx, "sid", $sid, cookieOptions(SESSION_TTL));
web.redirect($ctx, 303, "/");
# doLogout:
session.destroy($sessions, web.cookie($ctx, "sid"));
web.setCookie($ctx, "sid", "", cookieOptions(-1));   # expire it now

$sessions is kvstore.inProcessStore(); the cookie is HttpOnly, SameSite=Lax, Path=/, and Secure.

10 / 20

Middleware: who may see what

func requireLogin(ctx as web.Context) {
    def p as string init web.path($ctx);
    if ($p == "/login" or $p == "/healthz" or
        strings.startsWith($p, "/static/")) {
        return true;
    }
    if (json.has(current($ctx), "/member")) { return true; }
    web.redirect($ctx, 303, "/login");
    return false;
}

current($ctx): the sid cookie; if session.exists, touch and load it, else an empty object.

11 / 20

Forms: validate, write, redirect

# addBook(ctx), for POST /books
def title as string init strings.trim(web.formValue($ctx, "title"));
def author as string init strings.trim(web.formValue($ctx, "author"));
if ($title == "" or $author == "" or len($title) > 200 or
    len($author) > 200) {
    web.text($ctx, 422, "title and author: 1 to 200 characters\n");
    return;
}
def me as int init json.asInt(current($ctx), "/member");
store.addBook($db, $me, $title, $author);
web.redirect($ctx, 303, "/");     # post, redirect, get
12 / 20

Templates: tengine, escaped by hand

def const LIST as string init '{{ define "main" }}
<ul>
{{- range .books }}
  <li>{{ .title | html }} by {{ .author | html }}
  {{- if .done }} - read{{ else }}
    <form method="post" action="/books/{{ .id }}/done">
      <input type="hidden" name="csrf" value="{{ $.csrf }}">
      <button>Mark as read</button></form>{{ end }}</li>
{{- end }}
</ul>{{ end }}';
<li>&lt;script&gt;alert(1)&lt;/script&gt; by Mallory - read</li>
13 / 20

CSRF: a token in every form

func showLogin(ctx as web.Context) {
    def token as string init web.csrfToken($ctx, $csrfSecret);
    web.html($ctx, 200, views.login("", "", $token));
}
func guardCsrf(ctx as web.Context) {
    if (web.method($ctx) != "POST" or web.csrfCheck($ctx, $csrfSecret)) {
        return true;
    }
    web.text($ctx, 403, "CSRF check failed\n");
    return false;
}

Plain-HTTP development: JENNIFER_WEB_INSECURE_COOKIES=1.

14 / 20

What the server answered

POST /login  without a token                  -> 403 Forbidden
POST /login  token, wrong password            -> 401 "Wrong name or password."
POST /login  token, right password            -> 303 Location: /
             Set-Cookie: sid=...; Path=/; Max-Age=28800; HttpOnly; SameSite=Lax
POST /books  title "<script>alert(1)</script>"  -> 303, stored, shown escaped
POST /books/1/done                            -> 303
POST /books/1/done  (again)                   -> 404
GET  /       without a session                -> 303 Location: /login
15 / 20

Tests against a throwaway database

func fresh() {
    def server as string init os.getEnv("SHELF_TEST_DSN");
    def name as string init "shelftest_" + uuid.v4()[..8];
    def admin as sql.Connection init sql.open("mariadb", $server);
    sql.exec($admin, "CREATE DATABASE " + $name);
    def conn as sql.Connection init open($server + $name); # migrated
    return Fixture{admin: $admin, conn: $conn, name: $name};
}
func dispose(f as Fixture) {
    sql.close($f.conn);
    sql.exec($f.admin, "DROP DATABASE " + $f.name);
    sql.close($f.admin);
}
16 / 20

A test

func testBooksListUnreadFirst() {
    if (os.getEnv("SHELF_TEST_DSN") == "") { return; }   # skip
    def f as Fixture init fresh();
    defer dispose($f);
    def ada as int init addMember($f.conn, "ada", "correct horse battery");
    def first as int init addBook($f.conn, $ada, "Kindred", "O. E. Butler");
    addBook($f.conn, $ada, "Solaris", "Stanislaw Lem");
    testing.assertTrue(markDone($f.conn, $first));
    testing.assertFalse(markDone($f.conn, $first));     # already read
    testing.assertEqual(books($f.conn)[0].title, "Solaris");
}
17 / 20

Running the tests

$ docker run -d --rm --name shelf-testdb -e MARIADB_ROOT_PASSWORD=test \
    -p 127.0.0.1:3399:3306 --tmpfs /var/lib/mysql mariadb:11.4
$ SHELF_TEST_DSN='root:test@tcp(127.0.0.1:3399)/' \
    jennifer test src/store_test.j
PASS testBooksListUnreadFirst (67 ms)
PASS testLoginChecksThePassword (353 ms)
PASS testNamesAreUnique (121 ms)
18 / 20

A clean stop

os.catchSignal("term"); os.catchSignal("int");
def watcher as task of null init spawn {
    while (not os.gotSignal("term") and not os.gotSignal("int")) {
        time.sleep(time.fromMilliseconds(200));
    }
    httpd.shutdown($srv);     # from httpd.listen($addr)
    return null;
};
web.serveOn($app, $srv);      # returns after the shutdown
sql.close($db);
shelf: shutting down
shelf: stopped
19 / 20

Where to go from here

Based on Jennifer 0.26.0, November 2026.

20 / 20