Reference › APIs
On this page
Server
Server code: a server route's load(), and the handler vite build writes. For when a route renders on each request, see Rendering modes.
LoadContext #
type LoadContext = { params: Record<string, string>; request: Request; cookies: Cookies; locals: Locals }What a page's load() gets: the route's params, the request, the request's cookies, and the locals that handle() filled.
// src/pages/account.load.ts (a server route)
import type { LoadContext } from 'clarusjs/server'
export function load({ params, cookies, locals }: LoadContext) {
return { id: params.id, user: locals.user, theme: cookies.get('theme') ?? 'light' }
}cookies #
cookies.get(name: string): string | undefined
cookies.getAll(): Record<string, string>
cookies.set(name: string, value: string, options?: CookieOptions): void
cookies.delete(name: string, options?: { path?: string; domain?: string }): voidThe request's cookies, read from its Cookie header. What set() and delete() change is sent on the answer as Set-Cookie, whatever the answer is: the page, its data or fragment, or a redirect(). get() sees this request's own changes.
Options #
CookieOptions: path, domain, maxAge (seconds), expires, httpOnly, secure, sameSite ('lax', 'strict' or 'none').
Caveats #
- Secure by default:
path: '/',httpOnly: true(scripts can't read it),sameSite: 'lax', andsecure: true, so the cookie is only sent over HTTPS. The exception is the Vite dev server, so development over plain http works; browsers also accept secure cookies fromhttp://localhost, sovite previewworks. It's never guessed from the request's address: behind a proxy, production can seehttp://localhosttoo. Pass an option to change one. - Only on the server: a static page's
load()runs once at build, for everyone, so it has no visitor's cookies or headers to read. Usingcookiesorrequest.headersthere fails the build:"/account reads cookies, but static routes are built once for everyone: make it 'server'". The same goes for a client route's data.handle()still runs for static pages, with no cookies.clarusjs explainshows which server routes read cookies. - Names must be cookie tokens: no spaces or separators. Values are URL-encoded on the way out and decoded on the way in.
locals #
interface Locals {}Data one request carries from handle() to every load(), such as the signed-in user. Declare what it holds once, and every loader is checked against it:
// src/server.ts
declare module 'clarusjs/server' {
interface Locals { user?: { id: string; name: string } }
}handle() #
type Handle = (context: { request: Request; cookies: Cookies; locals: Locals }) => void | Response | Promise<void | Response>An optional handle export in src/server.ts runs once per request, before any page loads. It turns the request (usually a session cookie) into locals, so pages never parse cookies themselves. Returning a Response, such as redirect('/login'), answers the request instead of the page.
// src/server.ts
import type { Handle } from 'clarusjs/server'
export const handle: Handle = async ({ cookies, locals }) => {
const session = cookies.get('session')
if (session) locals.user = await sessions.find(session)
}If handle() throws, the request gets a 500, and the error goes to the server's log.
Endpoints #
type RequestHandler = (context: LoadContext) => Response | Promise<Response>A .ts file under src/pages (not a .load.ts) that exports GET, POST, PUT, PATCH, DELETE or OPTIONS is an endpoint, at its file's route: src/pages/api/items.ts answers /api/items, and src/pages/api/items/[id].ts answers /api/items/42 with params.id. Each handler gets the same context as a load() (the request, params, cookies and locals) and returns a Response.
// src/pages/api/items.ts
import type { RequestHandler } from 'clarusjs/server'
export const GET: RequestHandler = ({ locals }) => Response.json(listFor(locals.user))
export const POST: RequestHandler = async ({ request, locals }) => {
const item = await save(locals.user, await request.json())
return Response.json(item, { status: 201 })
}An island calls it with fetch('/api/items'), and the visitor's cookies go along, so handle() has resolved the session. A token for a third-party API stays in the endpoint and never reaches the browser.
Caveats #
- Endpoints are server routes: they need a server deploy (an adapter, or
dist/server/index.mjsin your own server). They are never prerendered. - Writes from other sites are refused: a
POST,PUT,PATCHorDELETEwhoseOriginis neither the request's own nor yoursite.urlgets a 403, as does one the browser marks cross-site (Sec-Fetch-Site). This blocks cross-site request forgery. A request without anOrigin, from a server or a script, isn't a browser acting for a visitor, so it's allowed. - Methods:
HEADusesGET's handler without the body. Any other method a file doesn't export gets 405, with anAllowheader listing those it does. - A page wins a shared path, and a
.tsfile that exports no method isn't an endpoint (it's a 404).
redirect() #
redirect(to: string, status?: 301 | 302 | 303 | 307 | 308): ResponseA redirect for a server page's load() to return.
Parameters #
to: where to send the visitor: a path or a full URL.status(default302):301or308: the page moved for good;303: after a form is posted, so the next request is a GET;307: a temporary move that keeps the method.
Returns #
A Response with that status and a location header. load() can return any Response: the handler sends it as it is.
Caveats #
- Only server routes run
load()on each request. A static page'sload()runs at build time, where a redirect would end the build. - Fragment navigation and the client router follow it: the target page loads normally, and the address bar shows where it landed.
Usage #
// src/pages/account.load.ts (a server route)
import { redirect } from 'clarusjs/server'
export async function load({ request }) {
const user = await userFrom(request)
if (!user) return redirect('/login')
return { user }
}render() #
render(name: string, props: object): Promise<string>From clarusjs/views. Renders a view (any .tscl under src/) to an HTML string, in server code: a load(), an endpoint, or a script importing the built server.
Parameters #
name: the view's path undersrc/, without the extension:'components/pill'.props: its inputs.
Returns #
A promise of the HTML.
Caveats #
- Server code only, after the server entry has loaded: that's where the views are registered.
- Typed once
clarusjs checkhas run: it writes.clarusjs/views.d.ts, and an unknown name or a wrong prop becomes a type error. Add that file to yourtsconfig.json'sincludeto get the same types in your editor. - The built server,
dist/server/index.mjs, exportsrendertoo.
Usage #
import { render } from 'clarusjs/views'
const html = await render('components/pill', { text: 'new' })h() #
h(name: string, props?: object, children?: Children | Record<string, Children>): Promise<Html>From clarusjs/views, in server code. Builds HTML from elements and views: for components picked at runtime, wrappers, generated layouts and tests. Put the result in a page through load(). A template's {{ }} inserts it as HTML.
Parameters #
name: an element's tag ('p','section'), or a view's name, which has a/('components/card').props: a view's inputs, or an element's attributes. They're escaped and URL-checked, as in templates.children: what goes inside. Text is escaped;h()results nest; numbers are text;null,undefinedand booleans are nothing; lists are flattened. For a view, an object fills its slots by name ({ default: …, title: … }).
Returns #
A promise of Html: HTML that h() built from escaped parts.
Caveats #
- Only
h()makesHtml. A template inserts it as HTML and escapes every other value as before. Data can't pass for it: JSON has no way to carry its mark. - For server-rendered pages and components. An island's props and a client route's data are sent to the browser as data;
h()output there is an error naming it. - Take view and tag names from your own list, never from request data or a database: a name picks what renders.
- In an attribute (
title="{{ x }}"),Htmlis text like anything else. - Refused from code:
on*attributes,srcdoc, tags that load or run things (script,style,iframe,object,embed,base,link,meta,template) and clarusjs's owncl-*tags. Write those in a.tsclview, where the compiler checks them. Children of a void element (img), and named slots on an element, are errors too. - Server only: island scripts keep their templates.
Usage #
Components picked at runtime:
// src/pages/dashboard.load.ts
import { h } from 'clarusjs/views'
export async function load() {
const widgets = await getWidgets() // [{ view: 'components/chart', props: { … } }, …]
return { grid: await h('div', { class: 'grid' }, widgets.map((w) => h(w.view, w.props))) }
}{{-- src/pages/dashboard.tscl --}}
@input grid: any
<main>{{ grid }}</main>A view with named slots:
await h('components/card', { title: 'Hi' }, { default: [h('p', {}, ['Body'])], footer: 'Read more' })readManifest() #
readManifest(): Manifest | nullFrom clarusjs/manifest. The built site's route manifest: for each route, its mode, its islands, and the JavaScript and CSS it ships.
Returns #
The manifest during vite build. null in development, and on the first prerender pass.
Caveats #
- Node only, while prerendering. A page that calls it during
vite buildis rendered again once the manifest is written, so it can show what the built site ships. - The same data is in
dist/clarusjs-manifest.jsonafter the build.
Usage #
// src/pages/size.load.ts
import { readManifest } from 'clarusjs/manifest'
export function load() {
const home = readManifest()?.routes['/']
return { js: home?.js.gzip ?? 0 }
}The built handler #
vite build writes dist/server/index.mjs. Its default export is the handler: fetch(request) returns a Response, for any server built on the Fetch API (Node with an adapter, Deno, Bun, a Netlify or Cloudflare function).
import handler from './dist/server/index.mjs'
export default { fetch: (request: Request) => handler.fetch(request) }With adapter: 'netlify', the build writes that function for you (see Vite plugin).