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 #

ts
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.

ts
// 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 #

ts
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 }): void

The 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 #

locals #

ts
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:

ts
// src/server.ts
declare module 'clarusjs/server' {
  interface Locals { user?: { id: string; name: string } }
}

handle() #

ts
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.

ts
// 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 #

ts
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.

ts
// 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 #

redirect() #

ts
redirect(to: string, status?: 301 | 302 | 303 | 307 | 308): Response

A redirect for a server page's load() to return.

Parameters #

Returns #

A Response with that status and a location header. load() can return any Response: the handler sends it as it is.

Caveats #

Usage #

ts
// 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() #

ts
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 #

Returns #

A promise of the HTML.

Caveats #

Usage #

ts
import { render } from 'clarusjs/views'

const html = await render('components/pill', { text: 'new' })

h() #

ts
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 #

Returns #

A promise of Html: HTML that h() built from escaped parts.

Caveats #

Usage #

Components picked at runtime:

ts
// 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))) }
}
tscl
{{-- src/pages/dashboard.tscl --}}
@input grid: any
<main>{{ grid }}</main>

A view with named slots:

ts
await h('components/card', { title: 'Hi' }, { default: [h('p', {}, ['Body'])], footer: 'Read more' })

readManifest() #

ts
readManifest(): Manifest | null

From 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 #

Usage #

ts
// 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).

ts
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).