Wisp is in pre-release, self-hosted since GitHub suspended us. Install it, or see the changelog.

Wisp

Pages and Templates

A page's Rust goes between two --- lines at the top of its .wisp. The markup follows.

The Block

  • Items (fn, struct, use, static, const, impl, #[action]) belong to the page's module. Statements run per request before the markup, in an async function returning a Result (.await, ?, return redirect("/")). cx is &mut Cx there and &Cx in markup.
  • Route params are locals: slug: String for [slug], id: u64 for [id=int], Option<String> for [[lang]].
  • cx.route() is the matched pattern (/blog/[slug], "" on a 404): class:on=${cx.route() == "/blog/[slug]"}. Browser code has page.value.route.
  • +page.rs is for Rust that outgrows the block (a load returning Data, plus actions). A page has a block or a +page.rs, not both.
  • mod server { … } in the block holds the route's endpoints (get post put patch delete list, before). Not with a +server.rs beside it. Example.
  • A page and its endpoints can both take a GET (or list), and a POST when the page has actions. The page answers a request from Wisp's client (x-wisp) or one whose accept names text/html (a browser navigation). The endpoint answers the other requests, and every put, patch and delete. HEAD follows GET. A form post to ?/name from a browser goes to the action. Both answers send vary: accept, x-wisp, and CACHE keeps them apart. Every endpoint method of the route passes the page's guards (SIGNED_IN, MIDDLEWARE, RATE_LIMIT or CORS): also a put, patch or delete, a post of a page with no action, and the member route /[id]. It passes the layouts' guards and its own guards too. CORS runs once, first: the endpoint's, else the page's. An endpoint that must stay public goes to another route. Any text/html in accept picks the page: Wisp reads no q-values (SvelteKit does), so text/html;q=0 picks the page too. A mod server and a +server.rs together are still a build error. The build adds this test only to such routes.
  • +layout.wisp and +template.wisp take a block with no .await or ?. Components and error pages take none.
  • fn entries() -> Vec<…> in a page under [params] lists the pages wisp build --static writes (Deploying).

Parent data and imports

fn load(parent: &Parent) -> Data reads the Data of the nearest +layout with a load (its Data must be pub). The build rejects &Parent elsewhere.

A route file needs no use or pub. It has wisp::prelude, the pub items of the app's modules, HashMap HashSet BTreeMap BTreeSet VecDeque Arc Rc Cow Duration Instant SystemTime, and what [package.metadata.wisp] auto = ["chrono::{Utc, DateTime}"] lists. A name two modules make pub is a build error. wisp check --explain-imports shows where each name comes from. {@flash} and active work in pages and layouts, not components.

One File or Several

One +page.wisp holds models, Tables, #[action]s, helpers and the load, then markup (A Page Is One File shows its code). This is src/routes/todos/+page.wisp:

---
#[model]
struct Todo {
    #[validate(len = 1..=100)]
    text: String,
}
static TODOS: Table<Todo> = Table::saved(); // "todos"

#[action]
fn add(todo: Todo) {
    TODOS.add(todo)?;
}
---

<title>Your todo list (${TODOS.len()})</title>
<meta name="description" content="Add todos with a form; each one is kept in a saved table.">
<h1>Todos</h1>
<form action="?/add" fields><button>Add</button></form>
{#each TODOS.all() as todo}
  <p>${todo.text}</p>
{/each}

Items in a block are private to the page. Models and tables several pages use go in src/db.rs (or any src/NAME.rs), including the users table behind cx.user and login (Sessions). +server.rs is a route with no page; src/hooks.rs runs before once the route is found, for every app request and a 404, but not for /_wisp/*, /_app/*, static files, trailing-slash 308s, redirects or the sitemap/robots fallbacks.

Signatures and Inputs

load, actions and +server.rs endpoints may be fn or async fn, take cx or not, and return a plain value or a Result. Other parameters are inputs, read by name: route param, then POST/PUT/PATCH form, then query.

TypeBehavior
T (any FromStr)Required. Missing: 400 naming the field (422 from a JSON body). Sent but not a T: 422 by field (400 from the query). A route param that does not parse: 404
Option<T>None when missing or blank
boolCheckbox: sent, and not false, off, no, 0 or empty
Vec<T>Every value of a repeated field
&str, Option<&str>Borrowed from the request (read owned when the handler also takes cx)

cx.form() reads anything else, files too. cx.input(name) finds one field.

Errors, Actions, Validation

  • ? on a std::error::Error is a 500. return error(404, "…") stops with that status, return redirect("/…") is a 303. Error::new(status, "…") and Error::redirect(status, "/…") build them. Option::or_404() and or_status(409) (trait OrStatus) are shortcuts. Err(error(..)) is a build error.
  • An action returns nothing, a Result<()> or a Response sent instead of the page.
  • Validation: return invalid(field, problem). The page renders again as a 422 with each input showing what was typed and what is wrong (Actions). A param that does not parse (email: Email) gives the same 422. ${cx.problem(field)} places a message; cx.fail(status, value) keeps a value the load takes with cx.take().
  • +server.rs methods return a Response, any other value as JSON (#[derive(Json)]), nothing as 204. body: T reads a JSON body as FromJson. Errors under /api are JSON (APIs).

Limits and Caching

ConstEffect
const BODY_LIMIT: usize = 20 * wisp::MB;Max body (default 1 MB, WISP_BODY_LIMIT), else 413
const CACHE: u32 = 60;Keep GET answers, seconds
const CACHE_PUBLIC: u32 = 60;Also for cookie requests
const CACHE_STALE: u32 = 600;Serve stale, refresh behind
const CACHE_TAGS: &[&str] = &["posts"]; or cx.cache_tag("post-7")Name kept answers

wisp::revalidate_tag("posts") drops a tag's answers on every worker and the wisp::cache_tagged answers with that tag, wisp::revalidate_path("/blog/x") one path, uncache a path and those below it. Each const is a u32 set once per route, not in a layout (BODY_LIMIT is a usize). The build adds each upload action's max_size to the body limit, so uploads need no BODY_LIMIT.

To share cache times across routes (as named cache profiles), set each pub const once in src/conf.rs (with mod conf; in main.rs). Then use it in each route. CACHE_STALE can use one the same way.

pub const HOURS: u32 = 3600; // src/conf.rs
pub const DAY: u32 = 86400; // src/conf.rs
const CACHE: u32 = crate::conf::HOURS;
const CACHE_STALE: u32 = crate::conf::DAY;

CACHE is per worker, keyed by Host, path and query. Only a 200 without a cookie or cache-control: private/no-store is kept, with an ETag. A write does not clear it; use uncache or revalidate_*. A new process starts empty. Requests with a cookie or authorization header skip it unless CACHE_PUBLIC. A kept CACHE_PUBLIC answer sends cache-control: public, s-maxage=<CACHE>, stale-while-revalidate=<CACHE_STALE> (no stale-while-revalidate when CACHE_STALE is 0), so a CDN can keep it. Your own cache-control wins. No such header when the app has a before or after hook, or when the page or its layouts have a guard (SIGNED_IN, MIDDLEWARE, RATE_LIMIT, CORS). The same holds when a +server.rs has a before function or a guard. Those run on each request and a CDN skips them. Set your own cache-control then. There is also no such header when the answer depends on accept: a page that shares its path with an endpoint, or a #[derive(Rest)] list. A CDN that skips vary can send one answer to the wrong client. A plain CACHE page sends none: a CDN that keys on the URL can send its copy to a signed-in visitor. Set your own cache-control on it if your CDN keys on the cookie too. A stale reply keeps s-maxage=<CACHE>, so a CDN can keep a page up to 2 × (CACHE + CACHE_STALE) after its render. A PPR page (a shell with holes) gets no such header: its holes are per request. In an app with locales, a page whose locale comes from the lang cookie or Accept-Language (no lang in its path, no domain, prefix not as-needed) gets no such header. A CDN hit does not reach the server: no before hook, rate limit, log, hook header or x-request-id. A CACHE_PUBLIC page behind a before gate (sign-in, paywall, geo) reaches everyone through a CDN. To keep the copy in the server and stop the CDN copy, set your own cache-control: no-cache (not private or no-store: then Wisp does not keep the page). revalidate_tag, stale_tag and uncache do not purge a CDN: it holds the old page until its s-maxage ends. A page that reads a header such as accept-language varies by it, so don't CACHE it. Dev keeps nothing. Limit: 8 MB per worker. A full store deletes the dead entries first, then the live entries nearest their end time (one eighth of the limit at a time). A flood of new URLs can push out pages that clients asked for. It costs renders, never memory.

Draft mode: cx.enter_draft() (from your own endpoint) sets the signed cookie wisp-draft; cx.exit_draft() ends it and cx.draft() reports it. Draft requests skip a CACHE_PUBLIC cache.

A page that reads nothing of the request needs no CACHE: with no load, statements or +page.js, and only literal holes, the build writes the response into the binary (Build).

Holes (Partial Prerendering)

On a page with CACHE, CACHE_PUBLIC or PRERENDER, an {#await} that does not name cx is waited for and kept. One that names cx is a hole: the page becomes a shell kept per worker (for good with PRERENDER), and each request runs the holes, which may read cookies or the user, and streams their answers in place of the pending markup. No script is needed.

---
const CACHE: u32 = 60;
---
<h1>Shop</h1>
{#await cart(cx.cookie_or("cart", String::new()))}<p>…</p>{:then c}<p>${c.len()} items</p>{/await}
  • cx in the shell (markup, statements, load, layouts) is a build error; cx.cache_tag is fine. Also refused: a hole naming a let, a hole inside {#if} or {#each}, {@flash}, <form once>, <form guard> and CACHE_STALE.
  • The shell is kept only from a GET that set no cookie, sent as cache-control: private, no-store. uncache, revalidate_path and revalidate_tag drop it.
  • In wisp build --static holes keep their pending markup.

Accessibility

wisp check, wisp dev and wisp build lint each template and warn ((a11y-img-alt)). Every lint has a code and a level: see Lint levels. <!-- wisp-ignore a11y-img-alt --> on the line before an element silences a lint. A value set by an expression counts as set.

Lints (wisp check --rules lists them all):

CodeFinds
a11y-img-alt<img> without alt
a11y-img-redundant-altalt that says image, picture or photo
a11y-anchor-href<a> without href, or href="#"
a11y-link-name, a11y-button-namea link or button with no text, aria-label or <img alt>
a11y-input-labela control with no label, id, aria-label, title or placeholder
a11y-label-control<label> that labels nothing
a11y-heading-ordera heading that skips a level
a11y-click-eventson:click on a non-interactive element without role and on:keydown
a11y-mouse-eventson:mouseover without on:focus, on:mouseout without on:blur
a11y-inline-handlera literal onclick="..." or other on*="...", which the page's CSP blocks: write on:click
a11y-autofocus, a11y-accesskeythe attribute
a11y-tabindextabindex above 0
a11y-tabindex-statictabindex="0" on an element with no role, no label and no handler
a11y-interactive-focusan interactive role and a click, but no tabindex
a11y-aria-attran aria-* name that is not an ARIA attribute
a11y-aria-rolea role that is not a WAI-ARIA 1.2 role
a11y-role-redundanta role that the element has (<button role="button">; <ul role="list"> is left)
a11y-role-propsa role without the ARIA attributes it requires (role="checkbox" needs aria-checked)
a11y-aria-hidden-focusablearia-hidden="true" on an element that takes focus
a11y-media-captions<video> without <track kind="captions"> (a muted video is skipped)
a11y-iframe-title<iframe> without a title
a11y-distracting<marquee> or <blink>

Lint levels

Set the level of a rule, or of a group (a11y, seo, css, js, onion), in Cargo.toml. A rule wins over its group.

[package.metadata.wisp.lint]
a11y = "error"          # every a11y-* rule fails the build
a11y-img-alt = "warn"   # except this one
js-console = "warn"     # off by default
css = "off"

off drops the warning, warn prints it and error fails the build. strict = true fails on every warning. An unknown rule is an error that names the nearest code. Wisp reads the levels only under the exact header [package.metadata.wisp.lint]. A key that starts with lint under [package.metadata.wisp] (lint.a11y = "off", lint = {...}), a header that only looks like it ([ package.metadata.wisp.lint ]) and a row without = in the table are errors. wisp check --rules lists each rule with its level.

CSS and JavaScript lints

These read the <style> and <script> blocks of templates and the .css, .js, .mjs and .ts files in src/. They use the tokenizer of the build, not a new parser. // wisp-ignore js-var, /* wisp-ignore css-empty-rule */ or <!-- wisp-ignore js-var --> on the line before a finding (or on it) silences it.

CodeLevelFinds
css-empty-rulewarna rule with no declaration
css-duplicate-propertywarna property twice in one rule (a fallback with another value right after is fine)
css-color-hexwarna hex color with a wrong length or a wrong digit
css-at-rulewarnan at-rule that CSS and Tailwind do not define
css-importantoff!important
js-debuggerwarna debugger statement
js-eqeqwarn== or != (except against null)
js-unused-importwarnan import that nothing in the file uses (a template's markup counts)
js-varoffvar
js-consoleoffconsole.log and console.debug

Onion lints

These run only for an app with scripts = false in [package.metadata.wisp]. They read the shell, the templates, the Markdown pages, src/fonts.txt and the CSS in src/ and static/. They find what the browser loads from another host (No Script at All).

CodeLevelFinds
onion-fetcherrora src, srcset, poster, <object data>, href or xlink:href of <use> and <image>, <link href>, imagesrcset, CSS url() or @import, or fonts.txt line that loads from another host
onion-formwarna <form action> or formaction that posts to another host

Fixes

wisp check --fix makes only the fixes that cannot change what the page means: a redundant role, a debugger statement, an empty CSS rule and a CSS declaration that repeats the one before it. It writes each file whole (a temporary file with a name of its own, then a rename: it deletes no file of yours), keeps the byte order mark and the line ends, skips a file with mixed line ends or a file that is not UTF-8 text, and never writes through a symbolic link. A duplicate CSS declaration is fixed only when nothing but white space stands between the two. After 8 rounds of fixes in a file, it says when fixes are left: run it again. If a write fails, it lists the files that it wrote before. A second run changes nothing, unless the output says that fixes are left. A rule at off is not fixed. wisp check --fix --dry-run writes nothing, names the files, and fails if one would change (for CI). It is an error with --rust, --types, --target or --explain-imports, because it stops after the fixes.

SEO lints

Same commands, for the pages that the sitemap lists. The lint reads a page and its layouts together. <!-- wisp-ignore seo-title --> silences a lint for the file. The lint skips noindex, (private) and guarded pages.

  • seo-title: missing, duplicate, empty, or literal text outside 10 to 60 characters.
  • seo-description: missing (a <title description="…"> counts), duplicate, or literal text outside 50 to 160 characters.
  • seo-canonical: a const PRERENDER page with no <link rel="canonical"> (or {@html wisp::alternates(cx)}) while SITE_URL or ORIGIN is set.
  • seo-h1: no <h1>, or more than one.
  • seo-link: <a href="/x"> to a path nothing answers (code spans and blocks of a .md page are not read); in wisp build --static, a link in dist/ to a missing file.
  • seo-anchor: in wisp build --static, href="/page#id" with no such id. The build crawl also fails on it (error /page links to /x#id, but no element has the id id), unless --allow-dead-links. An id that only JS makes fails the build: add the id in the server HTML, or build with --allow-dead-links.

Client router

The client API (beforeNavigate, afterNavigate, onNavigate, preloadData, preloadCode, invalidate(key), updated) and the link attributes data-wisp-noscroll, -keepfocus and -replacestate live in wisp.js and live.js. wisp:navigate is cancelable, wisp:leave collects what onNavigate waits for, wisp:preload reuses the hover prefetch. depends goes in the browser's +page.js load.

Navigation moves focus to the <h1> and announces the title in an aria-live region. Motion respects prefers-reduced-motion. Dialog and Menu use native <dialog> and popover, and Input, Textarea and Select set aria-invalid and aria-describedby. Phones: The router and forms.

Template syntax, components, snippets and scoped styles: Template syntax and styles.

Is This Page Useful?

View This Page's Source

Type to search every docs page and heading.