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

Wisp

Parity Features

All of this is build-time, a const or a cold path. A request that uses none of it runs no code for it.

FeatureHow
Base pathbase = "/app" or WISP_BASE=/app
Asset baseassets = "https://cdn.example.com" or WISP_ASSET_BASE=https://cdn.example.com
Hooksbefore (+ Response::rewrite(path)), after, html, report, reroute, wisp::on_fetch (wisp::Hop), wisp::csp_nonce, wisp::csp_report_only, wisp::csp_report, cx.nonce()
Layout reset+page@.wisp, +page@group.wisp
Layout optionsCACHE, CACHE_PUBLIC, SSR, PRERENDER, TRAILING_SLASH, EARLY_HINTS, EARLY_HINTS_H1, PRECACHE, CSR, SIGNED_IN in a layout or page
Endpoint CSRFautomatic; const CSRF: bool = false; opts out; with const CORS, a form-typed request passes only from a listed origin
Browser envenv.PUBLIC_X
Typed routesgenerated pub mod routes
Script strategiestype="wisp/idle", wisp/interaction
Web vitals<meta name="wisp-vitals" content="/path">
Browser errors<meta name="wisp-errors" content="/path">
Bundle analyzerwisp build --analyze
Fontssrc/fonts.txt
Layersextends = ["../base"]
Middlewareconst MIDDLEWARE: &[&str] = &["auth"];
Loading views+loading.wisp
Slots@name folders
Intercepting routes(.), (..), (...) in a slot
Version skew<meta name="wisp-build">, wisp:stale

Base Path

Set base = "/app" under [package.metadata.wisp], or WISP_BASE=/app as a cargo env. It needs a / first and none last. wisp dev always serves at /.

  • A request outside the base is a 404 (/_wisp/*, the health probe and metrics answer at any base).
  • Wisp adds the base to what it writes: /_app/... URLs, static href, src, action, poster, formaction, data and srcset values, redirects, Location of a created row, the sitemap and routes::. A dynamic href=${x} is not covered: use routes:: or wisp::based.
  • A cookie's default Path is the base, except __Host- cookies, which stay /. A signed cookie under a base is not made __Host- (that would send it to every app on the host). Over HTTPS under a base, it is __Secure-name with Path=<base>, and signed_cookie reads it by that name. The session, flash and OAuth cookies are __Secure-session, __Secure-wisp-flash and __Secure-wisp_oauth_<name> with Path=<base>. So two apps on one host do not share a sign-in.
  • wisp build --static writes the folder a host serves at the base.

assets = "https://cdn.example.com" (or WISP_ASSET_BASE) links the built files (CSS, wisp.js, live.js, modules, lib images) from another host. The server still serves them at /_app/, so a CDN can pull from the app or hold a copy of dist/. It is https://host or /path with none last and no ?, #, ;, ,, quote or space, and wisp dev ignores it. A cross-origin host is added to script-src and style-src of the default CSP.

Hooks (src/hooks.rs)

Example: Hooks Around Every Request shows its code and downloads as a project.

  • before can return Response::rewrite("/new"). The router uses that path's route with no redirect, the address and cx.path() stay as sent, and the target route's guards and layouts run. A path no route matches is a 404, and so is a rewrite to /_wisp/* or /_app/*. Under Never (the default), a rewrite to a path that ends in / is a 404, because a rewrite never redirects. Returning a rewrite from any other hook is a 500.
fn before(cx: &mut Cx) -> Result<Option<Response>> {
    if cx.path() == "/old" {
        return Ok(Some(Response::rewrite("/new")));
    }
    Ok(None)
}
  • fn html(cx: &mut Cx, html: &mut String) is sync. It edits every text/html body whole before after, and skips streams and compressed bodies.
fn html(cx: &mut Cx, html: &mut String) { *html = html.replace("%year%", "2026"); }
  • report(cx, err) is sync and runs on every 5xx. To send the error to a service, give the call to wisp::spawn. The 5xx reply then does not wait for it. wisp::Request::new(method, url) makes the request. wisp::fetch(req).await sends it:
// src/hooks.rs
fn report(cx: &mut Cx, err: &Error) {
    let mut req = wisp::Request::new("POST", "https://sentry.example/api/store/");
    req.header("content-type", "application/json");
    req.body = format!(
        r#"{{"status":{},"path":{}}}"#,
        err.status(),
        wisp::to_json(cx.path())
    )
    .into_bytes();
    wisp::spawn(async move {
        let _ = wisp::fetch(req).await;
    });
}
  • reroute(path) -> &str returns the path to route by.
  • wisp::on_fetch(|req, hop| ..) (once, in init) runs before each wisp::fetch request goes out, and before each redirect fetch_follow follows. wisp::Hop says which hop (n) and whether the chain left the first origin (moved), so a secret header is added only when !hop.moved. wisp::fetch_public(req, hops) is fetch_follow for a URL a visitor named: every call only to public addresses. The edge build's fetch skips it. wisp::fetch_stream is the same call read as it arrives (an Upstream, a piece of at most 64 KB at a time, 30 s idle and 5 minutes in all). Dropping it closes the connection, and on the edge cancels the host's read.
  • A hook you do not write costs nothing.

Routing and Options

  • Layout reset. +page@.wisp has no layouts above it. +page@group.wisp has those down to the group (or (group)) folder's +layout.wisp. A folder has one page, so a +page.wisp beside a +page@x.wisp is a build error.
  • Layout options. CACHE, CACHE_PUBLIC, SSR, PRERENDER, TRAILING_SLASH, EARLY_HINTS, EARLY_HINTS_H1, PRECACHE, CSR and SIGNED_IN in a layout apply to its pages. The nearest layout wins, and a page's own const wins over all. RATE_LIMIT, CORS, TIMEOUT, COMPRESS, BODY_LIMIT and RUNTIME in a layout are errors: set them in the page.
  • Endpoint CSRF. A +server.rs handler for post, put, patch or delete checks the origin, as actions do. const CSRF: bool = false; turns it off. With const CORS, a request a browser sends without a preflight (a form's content type) passes only from an origin CORS lists, never for *.
  • Browser env. Browser code reads env.PUBLIC_X, inlined at build. Any other name is a build error, so a secret cannot reach the browser.
  • Typed routes. The build writes pub mod routes, a function per route named from its pattern (/ is home, /blog/[slug] is blog_slug). Parameters are impl Display (optional ones Option<..>) and percent-encoded.
  • Named middleware. const MIDDLEWARE: &[&str] = &["auth"]; in a page, +server.rs or +layout runs those pub fn name(cx: &mut Cx) -> Result functions of src/middleware.rs first. The build checks the names. before in src/hooks.rs is the global one, and MIDDLEWARE there is an error. A knob of a page or a layout in src/hooks.rs (SIGNED_IN, TIMEOUT, BODY_LIMIT, CACHE, CACHE_PUBLIC, CACHE_STALE, CACHE_TAGS, PRERENDER, COMPRESS, SSR, CSR, RUNTIME, CSRF, EARLY_HINTS, EARLY_HINTS_H1, PRECACHE, TRAILING_SLASH) is a build error, because nothing reads it there. This holds for a const with the same type text that a page uses for it (bool for CSR, spaces ignored). SIGNED_IN is an error with any type, as a const or a static. A constant of another type (const TIMEOUT: Duration) is yours. To gate all routes, check in before (cx.signed_in()?). CSRF belongs in the +server.rs (or mod server) whose requests it lets through.

Client Features

  • Script strategies. <script src type="wisp/idle"> and wisp/interaction do nothing until wisp.js swaps in a real <script> on idle or on the first pointer, key or scroll. on:load="init()" on that script runs when the script has loaded.
  • Web vitals. <meta name="wisp-vitals" content="/path"> makes wisp.js send LCP, layout shifts and event timing with one sendBeacon when the page is hidden.
  • Browser errors. <meta name="wisp-errors" content="/path"> in src/app.html makes each page load errors.js. It sends each uncaught error and unhandled rejection with sendBeacon, at most 5 per page load.
  • Loading views. +loading.wisp is shown 100 ms into a client navigation that has not arrived, with the #wisp-progress bar. The nearest folder's view wins. A streamed {#await} needs none of it.
  • Version skew. A release build puts <meta name="wisp-build" content=ID> in the shell. When a navigation fetches a page with another ID, wisp.js sends wisp:stale (the updated store).

Remote Functions

  • #[remote] functions are served at /_app/r/<hash>, a path no route has, so a routed request runs none of their code.
  • A command's POST carries x-wisp-refresh, a JSON array of up to 16 URLs of queries the page reads. After a 2xx, the server runs those GET queries and answers {"r": value, "q": [[status, value], …]}, so a command and the refresh of its queries take one round trip.
  • A #[remote] that a page form posts to (?/name) becomes an action of that page. It then has no /_app/r route, and a script that calls it is a build error.

Slots and Intercepting Routes

Slots (parallel routes). A @name folder beside a +layout.wisp is a sub-tree the layout draws (Routes). Its pages are never matched by the router on their own.

  • Each slot page is drawn at the URL pattern of its path without @name. The slot's page of the route's exact pattern wins, else +default.wisp, else the slot's own +page.wisp, else nothing.
  • The build refuses a slot page with no page of that pattern inside the slot's layout, a +layout.wisp in a slot, a +default.wisp outside one, and a slot drawn twice or in <p>, a table part or <select>.
  • A slot page cannot have statements. Its {#await} streams with the page, and CACHE may not keep it.
  • A +error.wisp in the slot folder handles that slot's 4xx and 5xx alone. A slot's +loading.wisp is one more loading view.
  • On a client navigation, wisp.js keeps a slot that is showing its default content.

Intercepting routes. (.), (..), (...) before a segment inside a slot name the route it intercepts. Intercepting pages are +page@.wisp, so they have no layouts. A click on a link to the target loads the intercepting page into the slot and pushes the target's URL. history.back() closes it, and a direct load of the URL is the route's own page.

Build Tools

  • Bundle analyzer. wisp build --analyze builds nothing. For each page route it sums the files that page loads as served (wisp.js, live.js, its modules and imports, app.css, the .wasm files its JavaScript names) in raw and gzipped bytes, largest first. It then lists each file once as a module: the heaviest modules, how many routes load each, and modules with equal bytes under two names. --analyze=json prints the same as one JSON document. --analyze=html writes a treemap page, with no script and no outside file.
  • Component libraries. A crate with links, [package.metadata.wisp] prefix and a build.rs that calls wisp_build::package(): Component libraries. The app's build copies each library's src/components to .wisp/libs/<prefix>/, and its components are prefix:Name. A bare name inside a library means the library's own component, so an app cannot hijack a library's <Button>. Nothing is added at run time.
  • Build plugins. build_plugins = ["name glob out -- program args"] in [package.metadata.wisp], or wisp_build::run_with(&[Plugin { .. }]) in build.rs, make files from files before the app compiles: Build plugins.
  • Layers. extends = ["../base"] beside use in [package.metadata.wisp] names a path or a dependency with an app's layout.
    • Its src/routes and src/components are copied like a plugin's ((layer_<dir>) group, git-ignored). The app's own route at the same URL, and its component of the same name, win. A component two layers ship is a name clash.
    • static/ is listed after the app's own, and src/app.css goes first in app.css.
    • $lib/x is the app's file, else the first layer's in extends order. A relative import in a layer's file looks in the layer first. The app's version wins a package version clash, and npm::conflicts warns.
    • src/fonts.txt and src/locales come from the first layer that has one when the app has none.
    • wisp dev watches each layer. A layer's root +layout.wisp wraps only the layer's own pages.

Assets from other sites

A URL goes where a path goes. No keyword, nothing is downloaded, and each is in the page policy by itself (a script by its exact URL, the rest by origin; Content-Security-Policy).

  • Scripts: <script src="https://…" integrity="sha384-…" crossorigin="anonymous">. Browser modules import them: import confetti from "https://esm.sh/canvas-confetti" stays as written. The https URLs in a <script type="importmap"> also go to script-src, as origins.
  • Stylesheets: <link rel="stylesheet" href="https://…"> in a page or app.html, or @import url(https://…) at the top of src/app.css (a scoped <style> cannot hold an @import).
  • Fonts: cdn or an https:// URL in src/fonts.txt, below.
  • Images and media: <img src="https://…"> (not resized, not made lazy by the build), <video src>, <audio src>, <source src>. img-src is 'self' data: https: by default ('self' data: on an onion site, WISP_ONION; wisp::csp("img-src …") replaces it).
  • Favicon and app icons: <link rel="icon" href="https://…">; icons[].src of src/manifest.json as an https:// URL stays as written.
  • Open Graph image: <title image="https://…"> and wisp::og(title, desc, "https://…").
  • Frames, plugins, form targets: <iframe src>, <embed src>, <object data>, <form action>.
  • A <link rel="preconnect" href="https://…"> for an origin you load early is yours to write; the fonts.txt ones are written for you. integrity and crossorigin pass through untouched.
  • The service worker and wisp build --static leave these URLs alone.

Fonts

src/fonts.txt has a line per font: a file in static/fonts, an https:// URL, google (download once) or cdn (Google's CDN), and weights. A weight is 1 to 1000, and a range goes from low to high. Two families must not share a file name: Open_Sans and Open-Sans stop the build.

DM_Sans google 400 700 preload
Roboto  cdn    400 700 italic
Fira    https://cdn.example.com/fira.woff2  400  mono
  • cdn loads the family straight from the Google Fonts CDN. Nothing is downloaded or stored. The head gets Google's stylesheet (display=swap; weights one by one or a range like 100-900; italic for the line) and preconnect links to fonts.googleapis.com and fonts.gstatic.com.

  • A URL in place of a file is one face (one weight, or one range). The @font-face names that URL, nothing is downloaded, the head gets a preconnect to its origin and, for a line marked preload, a preload link. Only https:// is accepted.

  • Each origin goes into the page policy (style-src, font-src) by itself: Content-Security-Policy.

  • A face from the web has a fallback face only when .wisp/fonts/<name>.ttf exists (a google line made it). Without it the fallback is left out and the build goes on, offline too.

  • The download (once) fetches the Latin subset as WOFF2, plus a TrueType copy in .wisp/fonts for metrics. A failure only warns.

  • The build puts these first in app.css: an @font-face per file with font-display: swap, a fallback face per family (size-adjust and the *-override metrics, over Arial, Times New Roman or Courier New), and --font-<name>.

  • A preload link goes in the head for lines marked preload. With none marked, it is the first line's first weight. Mark only what the first screen uses.

  • A preloaded face with no fallback face is font-display: block, so nothing shifts. The others are optional: the browser uses them if they arrive within about 100 ms, else from the next page on. On a slow connection a blocked face stays invisible for up to about 3 s.

  • Metrics come from TrueType and OpenType files only. A local .woff2 gets the swap and the preload, and its fallback face when .wisp/fonts/<name>.ttf exists.

Is This Page Useful?

View This Page's Source

Type to search every docs page and heading.