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.
| Feature | How |
|---|---|
| Base path | base = "/app" or WISP_BASE=/app |
| Asset base | assets = "https://cdn.example.com" or WISP_ASSET_BASE=https://cdn.example.com |
| Hooks | before (+ 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 options | CACHE, CACHE_PUBLIC, SSR, PRERENDER, TRAILING_SLASH, EARLY_HINTS, EARLY_HINTS_H1, PRECACHE, CSR, SIGNED_IN in a layout or page |
| Endpoint CSRF | automatic; const CSRF: bool = false; opts out; with const CORS, a form-typed request passes only from a listed origin |
| Browser env | env.PUBLIC_X |
| Typed routes | generated pub mod routes |
| Script strategies | type="wisp/idle", wisp/interaction |
| Web vitals | <meta name="wisp-vitals" content="/path"> |
| Browser errors | <meta name="wisp-errors" content="/path"> |
| Bundle analyzer | wisp build --analyze |
| Fonts | src/fonts.txt |
| Layers | extends = ["../base"] |
| Middleware | const 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, statichref,src,action,poster,formaction,dataandsrcsetvalues, redirects,Locationof a created row, the sitemap androutes::. A dynamichref=${x}is not covered: useroutes::orwisp::based. - A cookie's default
Pathis 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-namewithPath=<base>, andsigned_cookiereads it by that name. The session, flash and OAuth cookies are__Secure-session,__Secure-wisp-flashand__Secure-wisp_oauth_<name>withPath=<base>. So two apps on one host do not share a sign-in. wisp build --staticwrites 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.
beforecan returnResponse::rewrite("/new"). The router uses that path's route with no redirect, the address andcx.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/*. UnderNever(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 beforeafter, 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 towisp::spawn. The 5xx reply then does not wait for it.wisp::Request::new(method, url)makes the request.wisp::fetch(req).awaitsends 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) -> &strreturns the path to route by.wisp::on_fetch(|req, hop| ..)(once, ininit) runs before eachwisp::fetchrequest goes out, and before each redirectfetch_followfollows.wisp::Hopsays 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)isfetch_followfor a URL a visitor named: every call only to public addresses. The edge build'sfetchskips it.wisp::fetch_streamis the same call read as it arrives (anUpstream, 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@.wisphas no layouts above it.+page@group.wisphas those down to thegroup(or(group)) folder's+layout.wisp. A folder has one page, so a+page.wispbeside a+page@x.wispis a build error. - Layout options.
CACHE,CACHE_PUBLIC,SSR,PRERENDER,TRAILING_SLASH,EARLY_HINTS,EARLY_HINTS_H1,PRECACHE,CSRandSIGNED_INin 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_LIMITandRUNTIMEin a layout are errors: set them in the page. - Endpoint CSRF. A
+server.rshandler for post, put, patch or delete checks the origin, as actions do.const CSRF: bool = false;turns it off. Withconst CORS, a request a browser sends without a preflight (a form's content type) passes only from an originCORSlists, 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 (/ishome,/blog/[slug]isblog_slug). Parameters areimpl Display(optional onesOption<..>) and percent-encoded. - Named middleware.
const MIDDLEWARE: &[&str] = &["auth"];in a page,+server.rsor+layoutruns thosepub fn name(cx: &mut Cx) -> Resultfunctions ofsrc/middleware.rsfirst. The build checks the names.beforeinsrc/hooks.rsis the global one, andMIDDLEWAREthere is an error. A knob of a page or a layout insrc/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 aconstwith the same type text that a page uses for it (boolforCSR, spaces ignored).SIGNED_INis an error with any type, as aconstor astatic. A constant of another type (const TIMEOUT: Duration) is yours. To gate all routes, check inbefore(cx.signed_in()?).CSRFbelongs in the+server.rs(ormod server) whose requests it lets through.
Client Features
- Script strategies.
<script src type="wisp/idle">andwisp/interactiondo 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 onesendBeaconwhen the page is hidden. - Browser errors.
<meta name="wisp-errors" content="/path">insrc/app.htmlmakes each page load errors.js. It sends each uncaught error and unhandled rejection withsendBeacon, at most 5 per page load. - Loading views.
+loading.wispis shown 100 ms into a client navigation that has not arrived, with the#wisp-progressbar. 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 sendswisp:stale(theupdatedstore).
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/rroute, 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.wispin a slot, a+default.wispoutside 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, andCACHEmay not keep it. - A
+error.wispin the slot folder handles that slot's 4xx and 5xx alone. A slot's+loading.wispis 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 --analyzebuilds 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.wasmfiles 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=jsonprints the same as one JSON document.--analyze=htmlwrites a treemap page, with no script and no outside file. - Component libraries. A crate with
links,[package.metadata.wisp] prefixand abuild.rsthat callswisp_build::package(): Component libraries. The app's build copies each library'ssrc/componentsto.wisp/libs/<prefix>/, and its components areprefix: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], orwisp_build::run_with(&[Plugin { .. }])inbuild.rs, make files from files before the app compiles: Build plugins. - Layers.
extends = ["../base"]besideusein[package.metadata.wisp]names a path or a dependency with an app's layout.- Its
src/routesandsrc/componentsare 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, andsrc/app.cssgoes first inapp.css.$lib/xis the app's file, else the first layer's inextendsorder. A relative import in a layer's file looks in the layer first. The app's version wins a package version clash, andnpm::conflictswarns.src/fonts.txtandsrc/localescome from the first layer that has one when the app has none.wisp devwatches each layer. A layer's root+layout.wispwraps only the layer's own pages.
- Its
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 toscript-src, as origins. - Stylesheets:
<link rel="stylesheet" href="https://…">in a page orapp.html, or@import url(https://…)at the top ofsrc/app.css(a scoped<style>cannot hold an@import). - Fonts:
cdnor anhttps://URL insrc/fonts.txt, below. - Images and media:
<img src="https://…">(not resized, not made lazy by the build),<video src>,<audio src>,<source src>.img-srcis'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[].srcofsrc/manifest.jsonas anhttps://URL stays as written. - Open Graph image:
<title image="https://…">andwisp::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; thefonts.txtones are written for you.integrityandcrossoriginpass through untouched. - The service worker and
wisp build --staticleave 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
-
cdnloads 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 like100-900;italicfor the line) andpreconnectlinks tofonts.googleapis.comandfonts.gstatic.com. -
A URL in place of a file is one face (one weight, or one range). The
@font-facenames that URL, nothing is downloaded, the head gets apreconnectto its origin and, for a line markedpreload, apreloadlink. Onlyhttps://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>.ttfexists (agoogleline 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/fontsfor metrics. A failure only warns. -
The build puts these first in
app.css: an@font-faceper file withfont-display: swap, a fallback face per family (size-adjustand the*-overridemetrics, over Arial, Times New Roman or Courier New), and--font-<name>. -
A
preloadlink goes in the head for lines markedpreload. 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 areoptional: 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
.woff2gets the swap and the preload, and its fallback face when.wisp/fonts/<name>.ttfexists.
Is This Page Useful?