Actions, Forms and UI
---
static TODOS: Table<String> = Table::new();
#[action]
fn add(#[validate(len = 1..=100)] text: String) {
TODOS.add(text)?;
}
#[action]
fn remove(id: u64) {
TODOS.remove(id)?;
}
---
<form action="?/add">
<input name="text">
<button>Add</button>
</form>
{#each TODOS.all() as todo}
<p>${todo} <button action="?/remove&id=${todo.id}">Delete</button></p>
{/each}
Actions
Example: Todos shows its code and downloads as a project.
action="?/like"posts to#[action] fn likein the same page and addsmethod="post". A form with noactionposts todefault. A#[remote] fnofsrc/*.rsthat returns nothing also counts (Forms every page shares). The build fails if the action does not exist.- A
<button action="?/remove&id=${todo.id}">outside a form becomes its own form. It works without JS. - An action reads query parameters like form fields (
id: u64above). An action argument missing from a POST body falls back to the query string, so?/act&id=5fillsideven on a post. An attacker can pin such a parameter in a link. If an action must not take a value from the URL, check that it came from the body, or carry it only in the form. - A body with
.awaitmakes the actionasync. Do not writeasyncyourself. <form fields>writes a labelled input per action parameter (fields=${post}fills them frompost). Text withone_ofbecomes a<select>. It adds a button if the form has none.<form fields="Log in" />names it.- Cookies, sessions and sign-in: Cookies and sign-in.
Validation
Parameter rules go in #[validate(...)]:
| Rule | Checks |
|---|---|
len, min, max, min_len, max_len | length or value range |
email, slug, uuid, alnum, phone, date, url | format (slug is my-post, date is 2026-10-04) |
not_blank, ascii, lowercase, no_html | content (no_html refuses tags, a < b passes) |
min_date, max_date, step = 5 | date bounds, whole multiples |
same_as = password | repeats another field (actions only, runs last) |
one_of = "draft live" | one of these words |
max_size, types | uploads (below) |
A Password has no length rule: add #[validate(min_len = 8)]. A parameter may be a struct with #[derive(FromJson)] or Rest (fn default(post: Post)), checked by its own rules.
The action checks every parameter first, so one 422 lists each failure by field (wisp::rt::input::read, and wisp::rt::input::whole for a struct). return invalid("text", "...") does the same by hand.
Two #[validate] attributes on one parameter or field check all their rules, as one attribute with all of them. with and pattern can repeat, and each one runs. The input of a text field gets one pattern attribute, from the first rule that sets one. Any other rule that is twice on one item fails the build with this error:
`len` is twice in the #[validate] of `name`: keep one
On the 422 page, only the form whose action refused changes:
- Each field shows what the client sent (
wisp::rt::kept), then<small class="problem">with its problems (wisp::rt::problem). Checkboxes and radios usewisp::rt::ticked,<select multiple>useswisp::rt::sent. Passwords and files show the problem but are never sent back. - A field with a problem gets
aria-invalid="true"andaria-describedby(wisp::rt::invalid). wisp::rt::summarizeadds<div class="problems" role="alert" tabindex="-1" autofocus>at the top of<main>, with a link per field. A problem in lower case (is required) follows the field name. One with a capital stands alone. A 429 fromcx.limitorBackoffhas, on a native build, a message such asToo many requests. Try again in 20 seconds.and shows the form again with it.<form action="?/join" guard>adds a token, a honeypot and a clock, checked first (Auth). A failure is a 422 here.value=${post.title}sets your own value.${cx.problem("text")}places a field's<small>yourself.- A GET pays nothing for this.
Browser checks come from the same rules, only where the server agrees. They are required, type="email", minlength, pattern for max length and for a literal pattern rule, and min/max on number inputs.
Request Flow
- Same-origin check:
Origin, if present, must matchHost(else 403). On a native build, anOriginthat is not UTF-8 is a 403. Only withoutOrigin,Sec-Fetch-Siteother thansame-originornoneis 403. A client sending neither (curl) passes.Origin: nullpasses withSec-Fetch-Site: same-origin, or, with noSec-Fetch-Site, with a validguardtoken. - A
guardform checks its token, honeypot and clock. - The action runs.
redirect("/...")is a 303. Forwisp.js(requests carryx-wisp) a redirect is a 200 withx-wisp-location. The script navigates itself becausefetchwould follow with the post's headers and not at all to another site. - On success the page's
loadruns and renders. wisp.jssends the form withfetch(multipart for files) and morphs<body>in place, keyed byid, so focus and scroll survive. It disables the submit button meanwhile and fires awisp:updateevent after each morph.data-wisp-keepon an element leaves it alone (a map, an editor).
In a {:...} hole, in a directive value and in a <script>, ${ starts a JavaScript template literal. It is not a server hole. Write the server's ${expr} outside them.
Without JavaScript
Every form works with scripts off. wisp.js only smooths it.
- A good post is a 303, so Reload never posts again. End an action in
redirect(..). A refused post shows the form again as a 422 with the typed values. cx.flash("Saved")waits in a session cookie for the next page with{@flash}, shows once and lives 5 minutes. A page that shows a flash iscache-control: private, no-store.- A page that read a signed cookie (
cx.signed_in(),cx.user()?) is alsoprivate, no-store. - An onion site (
WISP_ONIONon, also by an.onionORIGINorSITE_URL) getsReferrer-Policy: no-referrer(WISP_REFERRERnames another). - Two clicks to delete:
<button action="?/rm&id=${x.id}" confirm>Delete</button>becomes a<details class="confirm">with the real button inside.confirm="Yes, delete"words it. <form action="?/add" once>adds a hidden_oncetoken. A repeat post is a 303 and does nothing. It is a slip guard, not a lock.- Two steps with no session: keep the first answer in a hidden field of the second form.
---
#[action]
fn first(#[validate(len = 1..=20)] name: String) {
cx.set(2u8); // end of step one: show the page, as step two
}
#[action]
fn last(#[validate(len = 1..=20)] name: String, color: String) {
redirect("/done")
}
let step = cx.get::<u8>().copied().unwrap_or(1);
---
{#if step == 2}
<form action="?/last"><input type="hidden" name="name" value=${cx.input("name")}>
<input name="color"><button>Finish</button></form>
{:else}
<form action="?/first" fields />
{/if}
- An upload over the route's limit gets a 413 before the client sends the rest. State the size beside the field.
Table::pagelinks ({@pager}) are plain links. Write a search as a<form>with no method.
Forms and Files
cx.form() reads urlencoded and multipart bodies. cx.form().file("photo") is the file of <input type="file" name="photo">, None when empty, with name, content_type and bytes. files("photo") returns every file of a multiple input. Wisp cleans the name (no folders, drives, streams, control characters, device names, at most 255 bytes). The type is visitor input too. Files held this way stay in memory: use Upload for large ones.
Images
avatar: Image (or Option<Image>) is an action parameter.
- Max 2 MB (
wisp::MAX_SIZE), or#[validate(max_size = 5 * MB)]. The build adds each action'smax_sizeto the page's body limit, so it needs noBODY_LIMIT. - The form gets
enctype="multipart/form-data"and the inputaccept="image/*". - The kind comes from the first bytes: PNG, JPEG, GIF, WebP, AVIF, BMP or ICO. Anything else (SVG too) is a 422 by the field. A header that claims more than 8192 by 8192 pixels is also a 422 (a decompression bomb). A header with a size that Wisp cannot read is a 422 too. Wisp reads the size of an AVIF from its largest
ispe. It reads an ICO by its largest entry or the DIB header of a BMP entry. It reads a PNG inside an ICO by its IHDR. It reads a GIF by its largest frame. - As a response,
fn get(id: u64) -> Option<Image> { USERS.get(id)?.value.avatar }sends bytes and type with an ETag andnosniff.
SVG: Svg
#[action]
fn logo(#[validate(max_size = 256 * KB)] logo: Svg) -> Result<()> {
TEAMS.update(cx.signed_in()?, |t| t.logo = Some(logo));
Ok(())
}
SVG is XML that can carry script, so it is opt-in: logo: Svg (or Option<Svg>), never Image or image/*.
- Max 512 KB (
wisp::MAX_SVG), ormax_size. The input getsaccept="image/svg+xml". - A strict parser reads it. It takes UTF-8 only (one BOM allowed, no UTF-16). It refuses NUL, DOCTYPE, ENTITY and any processing instruction but the
<?xml?>line. It takes only the five XML entities and character references. The limits are 64 deep, 20,000 elements, 64 attributes an element, 32 namespace bindings in scope and 128 KB an attribute. A break of any rule is a 422 by the field. - Wisp writes the tree out again from an allowlist. It never filters the text. Elements and attributes match by namespace URI, not prefix. Shapes, text, gradients, patterns, clips, masks, markers, filters and
<a>stay.script,foreignObject,styleelements, animation (animate,set, ...),iframe/embed/object,feImage, everyon*attribute and anything unknown go with their content. hrefstays only as#fragment(ona,use,textPath, gradients, patterns, filters), or on<image>as adata:image/png|jpeg|gif|webp;base64URL whose bytes are that image. Attribute andstylevalues lose anyurl()buturl(#id), CSS escapes, comments,@rules andexpression. They also loseimage(),image-set(),cross-fade(),src(), andjavascript:,vbscript:ordata:in any case, with any spacing, or entity-encoded. Thestyleattribute keeps presentation properties only.- Show it only through
<img>:logo.data_url()(adata:image/svg+xml;base64URL) or a route that returns it.logo.as_str()is the sanitized text, to store or send as a file. Never inline it: in a page its ids and styles would mix with the page's. The sanitizer dropsclass. A table keeps it as that URL and sanitizes it again when it reads it back. As JSON (a table row, a REST body), it takes at most 512 KB (wisp::MAX_SVG), as sent and as sanitized. More is a 422 (must be at most 512 KB). - As a response (
fn get(..) -> Option<Svg>) Wisp sends it asimage/svg+xmlwithnosniffandcontent-security-policy: default-src 'none'; img-src data:; style-src 'unsafe-inline'; sandbox.
Any File: Upload
#[action]
fn send(#[validate(max_size = 50 * MB, types = "application/pdf")] report: Upload) -> Result<()> {
report.save_to(format!("reports/{}.pdf", cx.signed_in()?))?;
Ok(())
}
Upload (or Option<Upload>) works in an action or a +server.rs handler. It streams each file to a temporary file, so Wisp never holds one whole.
| Item | Behavior |
|---|---|
| Size | 10 MB (wisp::MAX_UPLOAD) unless max_size. All files of a route share WISP_UPLOAD_LIMIT (100 MB). Past either: 413. A broken form: 400. At most 256 parts and 64 files |
| Rate limit | A page's RATE_LIMIT runs before a multipart upload streams to disk. Over HTTP/1.1 it runs when the head names a body over 64 KB that is not yet in the read buffer. A spent limit gets its 429 with no 100 Continue and no body read. Then the connection closes. Wisp checks a body that came with its head late, after a read that the read buffer bounds. Over HTTP/2 it runs when the form starts to stream (after 64 KB). The stream gets its 429 and a reset. This early 429 comes before a layout SIGNED_IN or MIDDLEWARE refusal. It has no CORS headers. The early check counts nothing: parallel uploads under the limit all stream. The same holds for the methods of the +server.rs of the page's route. MIDDLEWARE, before and cx.limit(&L)? can read the form, so they run after the read. All count requests, not bytes. When the route takes an upload, a SIGNED_IN of the page or of a layout runs at the same point. It runs right after the rate limit and before the body. A visitor who is not signed in gets the sign-in answer (303, or 401 for JSON) with no body read. Over HTTP/1.1 the connection closes. Over HTTP/2 the stream gets that status and a reset (a 303 has its location, a 401 has no JSON body). The check reads the cookie alone. The page's own SIGNED_IN counts for every upload of its route: a page action and a +server.rs handler. The gate is per route, not per method. A signed-out PUT or PATCH upload to a +server.rs handler gets the refusal before its body. max_size, WISP_UPLOAD_LIMIT and WISP_SPOOL_LIMIT limit the bytes. |
| Spool budget | All requests together stream at most WISP_SPOOL_LIMIT bytes to temp files at once (default: 16 times WISP_UPLOAD_LIMIT). Over it, Wisp refuses a new file part with 503 until space frees. The bytes release as each Upload drops. It guards the disk against many concurrent uploads |
types = "application/pdf image/*" | Checks the bytes, not the browser header. Also sets accept. image/* is any image but SVG: image/svg+xml must be named, and that file is not sanitized (take an Svg to show one) |
kind() | By bytes. Images: png, jpeg, gif, webp, avif, bmp, image/x-icon, heic, image/heic-sequence, heif, tiff, jxl, image/svg+xml. Audio and video: mpeg, flac, ogg, wav, audio/mp4 (M4A), mp4, video/quicktime, webm, video/x-matroska. Documents: pdf, gzip, zip, docx, xlsx, pptx, odt, ods, odp, epub. Wisp reads docx, xlsx and pptx from the zip's central directory. A file with a vbaProject.bin, or any .bin part under word/, xl/ or ppt/, is the ...macroEnabled.12 kind, never the plain one. Epub is the zip's mimetype entry, only when the central directory has no Office or macro part. Text: Wisp reads all of it. It is application/json (it parses) or text/csv (two or more records of the same two or more fields) within 1 MB, else text/plain. A control byte or bad UTF-8 anywhere makes it application/octet-stream |
| Methods | name(), kind(), len(), path(), bytes()?, save_to(path)? |
save_to | Moves the file (makes folders, copies across disks), mode 0600 on Unix. Wisp deletes an unsaved temporary file when the Upload drops |
Serving Files
// [...name]/+server.rs
async fn get(name: String) -> Result<Response> {
Response::file_in("uploads", &name).await
}
Response::file_in(dir, name) reads without blocking and types by extension. It always sends nosniff and a CSP that sandboxes the file and lets it load nothing. Only a raster image, audio, video or plain text shows in the browser. HTML, SVG, XML, PDF, scripts, archives and Office files get content-disposition: attachment, and the browser saves them. A name that leaves the directory (.., absolute paths, drives, Windows devices like CON.txt) gets a 404. A name that the file system refuses (too long, a file used as a directory) also gets a 404. The name may come straight from the URL. Response::download("report.csv", bytes) sends bytes that the browser saves under that name. Wisp sends a .js, .mjs, .css or .wasm file as application/octet-stream. So an upload cannot act as a script of the site (serve your own assets from static/). Response::file_in_code(dir, name) is the same, but it sends .js, .mjs, .css and .wasm as their real type (still nosniff). A page that loads such a file runs it with the site's full power. Use it only for files that your own code or a trusted user wrote. Never use it for a public upload or a directory that the public can write to.
wisp.js sends a form post, and the answer can be a file (not HTML, no attachment). wisp.js shows the file only for an image that is not SVG, audio, video or plain text. It saves any other type as a download, PDF and JSON too, because the blob address loses the answer's own CSP.
Error Pages and Ready-Made UI
A route uses the nearest +error.wisp above it. So does an unmatched path under a folder (/blog/nope uses blog/+error.wisp). A folder with a parameter, blog/[slug]/+error.wisp, answers only its own routes. Route groups do not count in the URL. The layout guards of its folder run first. A guard that refuses answers in its place (a redirect, or Wisp's own error page, not the folder's own). So a guarded section never shows its error page to a visitor that the guard turns away. Without +error.wisp you get a plain HTML error page. It has the status and one line, light or dark as the system is. The page inlines its CSS (under 2 KB). API clients get JSON (APIs and platforms).
Run wisp ui list, then wisp ui add <name> to copy a button, dialog or tab into src/components (Tooling).
Built-in UI
Wisp's own screens share this site's palette (OKLCH, violet accent, red only for failures, light and dark). Their tokens are in crates/wisp/src/client/tokens.css. All are --wisp-* and .wisp-*, so they never touch app CSS. Wisp downloads no fonts.
| Piece | What it is |
|---|---|
Error page in wisp dev | A "Wisp dev" badge, the status, the message (what caused a 5xx) in a mono panel, the request. |
| Server errors in dev | WISP_SERVER_TIMING adds a Server-Timing header (it is on in wisp dev). Only an answer that a route handler or its error page made has the header. An early upload refusal (a 429 or the sign-in answer) has none. The header always has total. A debug build adds before, handler and render, each one that ran. A 5xx dev page holds its message in <template id="wisp-server-error">, which wisp-dev.js opens in the dialog. |
| Build error dialog (dev) | One row: the kind in a red pill, with a pager (1 of 3 errors), the version and Close on the right. Below it: where to look, the first file:line as an editor link, and the output with Copy and the compiler's line marked. The output scrolls sideways with this site's thin scrollbars and a shade where more lies. The browser scrolls it with the keys (tabindex="0"). Shadow root, so app CSS cannot touch it. Closes on the next good build. |
| Rebuild bar | A two-pixel accent line once a rebuild takes 200 ms. |
| Scripts off | Error pages are plain HTML and CSS. /_wisp/docs says that script draws it and links /_wisp/openapi.json (With JavaScript off). |
Only debug builds carry the dev styles and scripts. A release binary carries none of them.
Is This Page Useful?