Appearance
The server
The same Weft runs in the browser, compiled to JavaScript, and on the server, as bytecode on Weft's virtual machine. A backend can be all Weft, or a Rust or JavaScript server that hosts Weft modules.
weft run and weft dev serve an app or run a backend on the server runtime: Weft's VM on tokio, with std/http, std/auth, std/app, std/s3, std/sandbox, std/db and std/live (the reference).
Server functions
Three kinds of function run only on the server: a query fn reads, a mutation fn writes the database in a transaction, and an action fn does anything else (I/O, memory, calling other services). The client calls each like any async fn, and the compiler generates the network call:
Notes.weft
weft
import { uuid } from "std/random"
type Note = { id: string, text: string }
let mut notes: Note[] = []
let mut draft = ""
let mut problem = ""
action fn save(text: string): Note {
return Note { id: uuid(), text: text.trim() }
}
async fn add() {
if draft.trim() == "" { return }
let note, err = try await save(draft)
if err != null {
problem = err.message
return
}
notes.push(note)
draft = ""
problem = ""
}
---
<Box class="flex flex-col gap-2">
<TextField bind:value={draft} onsubmit={add} placeholder="A note" />
<Text>{problem}</Text>
@for note of notes key note.id {
<Text>{note.text}</Text>
}
</Box>A server function is implicitly async: save returns a Task<Note> to the client. Its parameters and result must be data: no functions, handles or type parameters. Because Weft values are copies, they serialize exactly, with no question of what else points at them. The server checks the arguments again when a call arrives, since it comes from the network.
A server function can't reach the client's world. Component state, props, globals, contexts and timers are errors inside it:
Leak.weftrejected by the compiler (E4007)
weft
let mut secret = "client state"
action fn peek(): string {
return secret
}
---
<Text>{secret}</Text>Errors cross typed. A server function that can fail, action fn f(…): R ! E, is a Task<R ! E | NetworkError> to the client: its own errors arrive as data, checked like its result, and a call that fails on the way (no connection, an answer that isn't a value, a panic on the server, which answers 500) fails with std/http's NetworkError { message, status? }. That is why add above checks err even though save can't fail. Server code calling a server function directly gets only its own errors. Errors has an example that matches each one.
The three kinds. The compiler holds each to what it says:
| does | database | runs | |
|---|---|---|---|
query fn | reads | the caller's, one snapshot | once a call; awaited in a derived value it is live |
mutation fn | writes | the caller's, one serializable transaction | again on a conflict |
action fn | I/O, memory, other services | through queries and mutations, or pool.as(user) | once |
A query or mutation fn may run more than once, so it does no I/O and changes no module state, even through a function it calls; now() and random() there are the call's own, the same on every run. A query fn doesn't read a module's let mut either: pass the value as an argument, or use an action fn. In a query or mutation fn, the pool is the caller's handle: pool.query.todos() runs under the policies for whoever called. Data shows them over a table. There is no server fn any more: the compiler's fix-it turns one into a query fn or an action fn.
A backend in plain Weft
A backend doesn't need the app framework. It is a program: a file whose top level builds its API with std/http and calls serve. Resources live in modules, which run once per process, so the connection is made once and imported where it's needed:
db/schema.weft
weft
import { table, schema, primary, index, flag } from "std/db"
export type User = { @primary id: string, name: string }
export type Todo = { @primary id: number, title: string, done: boolean, @index shared: boolean }
export let todos = table<Todo, User>("todos", { read: flag("shared") })
export let app = schema({ tables: { todos } })lib/server/db.weft
weft
import { postgres } from "std/db"
import { env } from "std/process"
import { app } from "db/schema"
export let db = try await postgres(app, env("DATABASE_URL")!)server/main.weft
weft
import { router, json, serve } from "std/http"
import { db } from "lib/server/db"
let anyone = db.as(null)
let api = router()
.get("/todos", async req => json(try await anyone.sql"select id, title, done from todos"))
try await serve({ port: 8080 }, api)weft run server/main.weft serves GET /todos from Postgres; with main = "server/main.weft" in weft.toml, weft run on the project does the same. The schema is Weft; db.as(user) queries through the tables' policies, and sql"…" is checked against the schema when the program compiles (std/db). A query can fail with a DbError: the handler passes it on with try, and the request is answered with a 500, the error printed. A handler that wants another answer handles the error itself (try … else). A connection that fails stops the program before it serves: lib/server/db fails to load, and weft run exits with code 1. std/http is in the reference (std/http), with how the server runs (the server runtime).
Per-request values, such as the signed-in user or a transaction, are std/http's business: there is no context or global on the server.
Signing in
std/auth signs users in on top of std/http's sessions: passwords, passkeys, email links and codes, and OAuth or OpenID Connect. The app keeps its users; signIn starts a new session for one, and its cookie goes on the answer of whatever is being served, a server function included:
lib/server/accounts.weft
weft
import { request } from "std/http"
import { signIn, verifyPassword, requireRole } from "std/auth"
type Account = { id: string, hash: string, roles: string[] }
let mut accounts: Map<string, Account> = Map<string, Account>()
export action fn logIn(name: string, password: string): boolean {
let req = request()!
let a = accounts.get(name)
// As slow for an unknown name as for a known one; guesses are limited per account and address.
let ok = try await verifyPassword(req, { account: name, hash: a?.hash, password })
if !ok { return false }
try await signIn(req, { id: a!.id, name, roles: a!.roles })
return true
}
export action fn userCount(): number {
try await requireRole(request(), "admin") // Unauthorized signed out, Forbidden without the role
return accounts.size
}std/auth's functions fail with an AuthError (and the session store's StoreError). Passed on, an AuthError is an answer: Unauthorized is a 401, Forbidden a 403 and RateLimited a 429. From a server function it reaches the client as data, so a call to userCount() fails with Forbidden { message } for a signed-in user without the role, which the client can match.
Server function calls are refused from other sites, cookies are HttpOnly and SameSite=Lax, and a session ends after its maxAge or when it sits idle. Every flow is in the reference (std/auth); examples/todos signs in with a password or a passkey.
The standard library
The project's own code imports what it needs, like any module:
| module | what it does |
|---|---|
std/http | an HTTP client, and a server with typed routes and middleware |
std/auth | sign-in: passwords, passkeys, email links and codes, OAuth and OpenID Connect, roles and guards |
std/db | Postgres, MySQL and SQLite behind one API; parameterized queries only, rows decoded into record types, transactions and migrations |
std/s3 | get, put, list, delete and presigned URLs, against any S3-compatible store |
std/live | live queries (a server function's call kept current in the page) and typed channels, over WebTransport or WebSocket, resuming after a reconnect |
std/process | the program's arguments (args()), environment (env(name)) and exit code (exit(code)) |
std/app | the app framework as code, for a program that sets it up itself |
std/sandbox | runs user code: loads it, checks it and runs it with only what the app passes in |
User code
main.weft
weft
import { memory, run } from "std/sandbox"
import { log } from "std/log"
let trees = memory()
try await trees.save("anna", { files: [{ id: "main", source: "export fn main(caps: json, input: json): json {\n return `hi ${input}`\n}\n" }] })
log(try await run(trees.tree("anna"), { input: "there" }))text
$ weft run main.weft
hi thereAn app can let its users write Weft. Their code doesn't run like the project's own: it goes through std/sandbox, which loads it (from the app's database, S3 or a mounted tree), checks it, and runs it with its own fuel, memory cap and deadline. Sandboxed code can import no I/O module. It reaches only what the app hands it: functions scoped to the user's rows, and the app's own components and functions under the names the app gives them (imports: { money: cash } lets user code write money while the app is free to rename cash). A user's own pages and components are checked by the compiler before they are saved, like any other file (User-editable apps).