Guide
Sites
One HTML page per file in src/routes/. Built as static files or as a server with form actions and middleware, on Node, Bun, Deno or Workers. Only pages with islands ship JavaScript.
One line in vite.config.ts
import ascua from "vite-plugin-ascua";
export default { plugins: [ascua({ site: true })] };With that, each file in src/routes/ is a page: vite serves it in
development and vite build writes one HTML file per route to dist/. There
is no server to write and no client and server entries: what you get is a
folder of files for any static host or CDN.
src/routes/index.ts → dist/index.html
src/routes/about.ts → dist/about/index.html
src/routes/orders/index.ts → dist/orders/index.html
src/routes/orders/[id].ts → dist/orders/7/index.html, one per id
src/routes/docs/[...rest].ts → dist/docs/guide/start/index.html, slashes included
src/routes/api/[[v]].ts → /api and /api/2: the segment is optional
src/routes/(marketing)/pricing.ts → dist/pricing/index.html: the group is not in the URL
src/routes/404.ts → dist/404.html
src/routes/500.ts → dist/500.html: the error page
src/routes/_layout.ts wraps every page
src/routes/orders/_layout.ts wraps the ones in orders/, inside the root one
src/routes/admin/_middleware.ts runs before the ones in admin/ (with a server)A file that starts with _ is not a page. [...rest] goes last and catches
the rest of the URL: /docs/guide/start gives rest = "guide/start". You
choose the name in brackets: it is the name of the param the page receives.
With double brackets, [[v]], the segment is optional: the same page serves
/api —with v undefined— and /api/2. On a static site, /api is always
generated and paths() says which values of v to generate.
A folder in parentheses, like (marketing)/, groups routes without showing up
in the URL: it gives them their own _layout.ts or _middleware.ts without
changing their addresses. If two files end up with the same URL —two groups
with a pricing.ts, or [[v]].ts next to an index.ts— it is an error,
instead of silently keeping one.
A page
// src/routes/about.ts
export const title = "About";
export default function About() {
return view`<section><h1>About</h1></section>`;
}The default export is the page component and title goes to <title>. The
code of the pages runs at build time and does not reach the browser: it
ends up as HTML.
With params
// src/routes/orders/[id].ts
export const title = ({ id }: { id: string }) => `Order ${id}`;
export function paths() {
return ORDERS.map((o) => ({ id: o.id }));
}
export default function Order({ id }: { id: string }) {
return view`<article><h1>Order ${id}</h1></article>`;
}[id] is a variable segment, and the page gets it as a prop. paths() says
which pages to generate —one per object— and can be async. On a static site it
is required: without it the build would not know which ids exist.
Data: load()
// src/routes/orders/[id].ts
import { notFound } from "vite-plugin-ascua/site";
export async function load({ id }: { id: string }) {
const order = await readOrder(id);
if (!order) throw notFound();
return order;
}
type Props = { id: string; data: Awaited<ReturnType<typeof load>> };
export const title = ({ data }: Props) => `Order ${data.number}`;
export const description = ({ data }: Props) => `${data.lines.length} lines`;
export default function Order({ data }: Props) {
return view`<article><h1>Order ${data.number}</h1></article>`;
}load() runs at build time —in development and with a server, on every
request— and what it returns reaches the page, the title and the description
as data. It is the place to read files, a database or an API: none of that
reaches the browser. description goes to <meta name="description">.
throw notFound() answers with the 404 page in development and with a server.
Routes that are not pages
A file whose name, without the .ts, still has an extension is that file:
// src/routes/sitemap.xml.ts → dist/sitemap.xml
export default function Sitemap() {
return `<?xml version="1.0"?><urlset>…</urlset>`;
}The default export returns the content, and can be async; with params and
load(), same as a page. Good for a sitemap.xml, a feed.xml, a search
index in .js or a .json.
The interactive part: islands
A page is HTML. Whatever has to respond to the user goes in an island, which the page uses like any component:
// src/islands/counter.ts
export const CounterIsland = defineIsland("counter", { start: p.number }, Counter);
// src/routes/index.ts
view`<section><CounterIsland start=${3}/></section>`;Islands in src/islands/ register themselves. A page that uses one gets the
script that hydrates them and only the modules of the islands it uses,
with their chunks and stylesheets preloaded; a page that uses none ships no
JavaScript. That is why it is better to have one island per file: if two
islands are defined in the same module, a page that uses one downloads both.
The layout
// src/routes/_layout.ts
import type { LayoutProps } from "vite-plugin-ascua/site";
export default function Layout(props: LayoutProps) {
const frame = view`<div><header>…</header><main></main></div>`;
props.children(frame.querySelector("main")!);
return frame;
}It is a component with children: it gets the path (path), its params
(params), what the middleware left (locals) and where to put the page
(children). There can be one per folder, and they nest: the root one wraps
the one in orders/, which wraps its pages.
More in the <head>
export const head = ({ data }: Props) => `
<meta property="og:title" content="${data.title}">
<link rel="canonical" href="https://example.com/orders/${data.id}/">`;head —a string or a function of the props— goes into <head> as is,
unescaped: it is HTML written by the route, not text from a user.
The shell
If there is an index.html at the root, it is the shell of every page. It goes
through Vite as usual, so its <link> tags to global stylesheets come out
with their hash. The page goes where <!--ascua--> is, or at the start of
<body>. Without an index.html, a minimal one is used. The shell option
picks another file.
Each page gets its <title>, a <style> with the styles of the components
that appear in it —and only those—, its Content-Security-Policy in a <meta>,
and, if it has islands, its script. export const lang = "en" sets the
page's <html lang>, so a site in two languages can share one shell.
With a server
If pages have to render on each request —data that keeps changing, a page per user—, the same site comes out as a server:
ascua({ site: { mode: "server" } });npm run build
node dist/server/index.mjs # PORT=3000 by defaultvite build leaves the client in dist/client/ and the server in
dist/server/index.mjs, with everything inside: it does not need
node_modules to start. It serves the client files —with a long cache for the
hashed ones— and renders each page on request. Variable routes no longer need
paths(): any value reaches load(), which decides with notFound().
With a server, routes receive forms with actions —validated with validate
and field, answered with fail or redirect, and sent without reloading
from an island with enhance()—, and every page goes out with security on:
CSP, secure headers, HttpOnly cookies signed with ASCUA_SECRET, and
same-origin forms only.
Middleware
A _middleware.ts runs before the routes of its folder and the ones inside:
before actions and load(). It is for what would otherwise repeat in each one,
like requiring a session:
// src/routes/admin/_middleware.ts
import { redirect, type MiddlewareContext } from "vite-plugin-ascua/site";
export default async function ({ cookies, locals }: MiddlewareContext) {
const id = await cookies.getSigned("session");
if (!id) throw redirect("/login");
locals.user = await findUser(id);
}// src/routes/admin/orders.ts
export async function load(_: object, { locals }: LoadContext) {
return listOrders(locals.user!.id);
}It gets { url, request, params, cookies, locals, setHeaders, next }:
Stop.
throw redirect(…)sends to another page andthrow notFound()gives the 404; neither the action norload()runs. If the form came fromenhance(), it gets the redirect too.locals. What it leaves there reachesload(), the actions and the layouts. To type it, extendLocals:tsdeclare module "vite-plugin-ascua/site" { interface Locals { user?: { id: string; name: string }; } }setHeaders. Adds headers to the response, whether it is the page, a redirect or an error. They win over the kit's.Wrap with
next(). Runs what is inside —inner middlewares, the action,load(), the page— and returns itsResponse, which can be changed or replaced. An error from inside arrives as an exception:ts// src/routes/_middleware.ts export default async function ({ next }: MiddlewareContext) { const start = performance.now(); try { const response = await next(); response.headers.set("server-timing", `page;dur=${performance.now() - start}`); return response; } catch (error) { reportError(error); return new Response("Something went wrong", { status: 500 }); } }Returning a
Responsewithout callingnext()stops there. A middleware that neither callsnext()nor returns anything lets the request through, as before.
If there is one at the root and another in admin/, both run, the root one
first; with next(), the root one wraps the one in admin/. A URL that does
not exist gets the root 404 and only the root middlewares; a route in
admin/ that throws notFound() goes through the ones in admin/. Since it needs a request, a static
site with middleware does not build.
API routes: GET, PUT, DELETE…
A route can export one function per HTTP method, like Fresh. Each receives the
params, the request, the cookies and locals, and returns a Response:
// src/routes/api/posts/[id].ts
import { notFound, type RequestHandler } from "vite-plugin-ascua/site";
export const GET: RequestHandler<{ id: string }> = async ({ params }) => {
const post = await db.posts.find(params.id);
if (!post) throw notFound();
return Response.json(post);
};
export const PUT: RequestHandler<{ id: string }> = async ({ params, request }) =>
Response.json(await db.posts.update(params.id, await request.json()));
export const DELETE: RequestHandler<{ id: string }> = async ({ params }) => {
await db.posts.delete(params.id);
return new Response(null, { status: 204 });
};GET,POST,PUT,PATCH,DELETEandOPTIONScan be exported.HEADusesGET. A method the route does not handle is a 405, withallowsaying which ones it does.- They live alongside the page and the actions. If the method's function
exists, it answers; if not, as usual: the page for
GET, the actions forPOST. - Methods that write, same origin only. Like forms: a request whose
Originis another site gets a 403. WithoutOrigin—another server,curl— it goes through;security.originsadds trusted origins. - They go through middleware, can throw
redirect()ornotFound(), and need a server: a static site with them does not build.
The error page: 500.ts
An error nobody catches —in load(), in an action, while rendering— answers a
500. With src/routes/500.ts, that 500 is a page of the site, with its layout,
and it receives what was thrown in error:
// src/routes/500.ts
import { view } from "ascua";
import type { ErrorPageProps } from "vite-plugin-ascua/site";
export const title = "Something went wrong";
export default function Error500(props: ErrorPageProps) {
console.log(props.error); // already written to the server log
return view`<h1>Something went wrong</h1><p>We are looking into it.</p>`;
}The error is written to the server console, and the page decides what to show:
in production, better little. An API route, a file route or enhance()
expect something other than HTML, so there the 500 stays the usual one. If
500.ts itself fails, too. On a static site it comes out as
dist/500.html, for whatever serves the site.
Navigating without a reload: partials
With partials, an internal link does not reload the page: the new page is
fetched and only the regions marked with data-partial are replaced. What is
outside —the header, an island playing audio, a half-typed search— stays as it
was.
// vite.config.ts
export default { plugins: [ascua({ site: { partials: true } })] };// src/routes/_layout.ts
export default function Layout(props: LayoutProps) {
const page = view`
<div>
<header><Search/></header>
<main data-partial="main"></main>
</div>`;
props.children(page.querySelector("main")!);
return page;
}- What changes. The regions, the
<title>, the description and the language; stylesheets and modules the new page brings are added. Islands in the region that leaves are released and those in the one that enters are hydrated. - With no marked region, the whole
<body>is replaced: still no reload. - History. Back and forward work, with their scroll. A link with a hash scrolls to it.
- What it does not intercept. Links to another origin, with
target,downloadorrel="external", with a modifier key, and those insidedata-partials="false". - If something does not fit —the new page lacks the same regions, it is not HTML, the network fails—, it navigates the usual way.
It fetches the whole page, the same one the browser would get, so it works the
same on a static site. In exchange, every page carries a small script, also
those without islands. When done, document gets the ascua:navigate event.
The request carries an x-ascua-partial: 1 header, in case a middleware wants
to tell it apart. The server still answers with the whole page: trimming it
would save little more than 1 kB compressed per navigation, and the same URL
with two different responses means minding every cache along the way.
With Deno, from start to finish
No Node needed: Deno installs the npm packages, runs Vite and serves the built site.
deno run -A npm:create-ascua my-site --template server
cd my-site
deno install
deno task dev # or: deno task build
deno run -A dist/server/index.mjsLike stil, Deno does not install versions published less than a day ago; in
that case, deno install --minimum-dependency-age 0.
On Bun, Deno and Workers
dist/server/index.mjs starts the same way on Node, Bun and Deno:
node dist/server/index.mjs
bun dist/server/index.mjs
deno run -A dist/server/index.mjsNext to it is dist/server/worker.mjs, the same site with nothing from
Node: a fetch(request, env) that takes a Request and returns a Response,
which is the shape of Cloudflare Workers and of
workerd, the Workers runtime you can
host on your own servers. It asks env.ASSETS for the files in
dist/client/, and reads ASCUA_SECRET from env:
// wrangler.jsonc
{
"name": "my-site",
"main": "dist/server/worker.mjs",
"compatibility_date": "2026-09-01",
"assets": { "directory": "dist/client", "binding": "ASSETS" }
}On your own workerd, ASSETS is a disk service:
using Workerd = import "/workerd/workerd.capnp";
const config :Workerd.Config = (
services = [
(name = "main", worker = .site),
(name = "assets", disk = (path = "/srv/my-site/dist/client", writable = false)),
],
sockets = [ (name = "http", address = "*:8080", http = (), service = "main") ],
);
const site :Workerd.Worker = (
modules = [ (name = "worker.mjs", esModule = embed "dist/server/worker.mjs") ],
compatibilityDate = "2026-09-01",
bindings = [
(name = "ASSETS", service = "assets"),
(name = "ASCUA_SECRET", fromEnvironment = "ASCUA_SECRET"),
],
);No nodejs_compat needed. The kit's tests run the same site —forms, signed
cookies and the body limit— on Node, Bun, Deno and workerd.
Options
| Default | ||
|---|---|---|
routes |
src/routes |
Where the pages are |
islands |
src/islands |
What hydrates; no islands, no script |
shell |
index.html |
The base of every page |
mode |
static |
Or server |
lang |
es |
The language of what visitors see: the field messages and the kit's responses (403, 404, 405, 413). Build errors follow LANG; the runtime's console warnings are in English |
security |
on | CSP, headers, cookies and origin check |
And what a route can export:
default |
The page: a component of the props. In a file route, the content |
title |
The <title>: a string or a function of the props |
description |
<meta name="description">, same |
head |
HTML for the <head>, same |
lang |
The page's <html lang>, over the shell's |
paths() |
Which pages to generate for a variable route |
load() |
The data: arrives as data. Gets the params and { url, request, cookies, locals } |
actions |
With a server, what receives its forms |