Data and SSR

Data comes from load() in the page .server.js. Writes go through server actions. By default the prebuilt page shows a skeleton while a fetch, started in <head>, completes; with ssr = true the server renders the data into the first HTML instead.

load() with a skeleton

load() runs on the server, and its return value is data: {data.loadedAt} in HTML, data.products in a script. Switch categories to watch the skeleton.

routes/examples/data/demo/catalog.html

<title>Catalog demo · pragma examples</title><meta name="robots" content="noindex"><script>  import { query } from 'pragma'  const current = () => query.fail ? 'broken' : query.category ?? 'all'  const filterLink = () => ({    all: current() === 'all' && 'true',    hardware: current() === 'hardware' && 'true',    books: current() === 'books' && 'true',    broken: current() === 'broken' && 'true',  })</script><c-demo-page>  <nav class="flex flex-wrap gap-x-5 gap-y-2 font-mono text-xs" aria-label="Category">    <a href="/examples/data/demo/catalog" class="nav-link" :aria-current="$filterLink.all">All</a>    <a href="?category=hardware" class="nav-link" :aria-current="$filterLink.hardware">Hardware</a>    <a href="?category=books" class="nav-link" :aria-current="$filterLink.books">Books</a>    <a href="?fail=1" class="nav-link" :aria-current="$filterLink.broken">Make load throw</a>  </nav>  <if page.loading>    <ul class="grid gap-2" aria-busy="true" aria-label="Loading products">      <li class="skeleton h-12"></li>      <li class="skeleton h-12"></li>      <li class="skeleton h-12"></li>    </ul>  </if>  <else-if page.error>    <div class="grid gap-1 border border-danger-500/50 bg-danger-950/40 p-4" role="alert">      <p class="font-mono text-sm text-danger-300">{page.error.message}</p>      <p class="text-sm text-muted">HTTP 500 from /_data. The rest of the page still works: pick a category.</p>    </div>  </else-if>  <else>    <div class="grid gap-2">      <ul class="grid gap-2">        <for product in data.products key=product.id>          <li class="flex items-center justify-between gap-4 border border-line px-4 py-3">            <span class="text-sm">{product.name}</span>            <span class="font-mono text-xs tabular-nums text-muted">{product.priceLabel}</span>          </li>        </for>      </ul>      <p class="font-mono text-xs text-faint">loaded at <span class="tabular-nums">{data.loadedAt}</span> UTC</p>    </div>  </else></c-demo-page>

routes/examples/data/demo/catalog.server.js

import { listProducts } from './_catalog.server.js'export async function load({ query, log }) {  if (query.fail) throw new Error('Inventory service timed out after 700 ms')  const products = await listProducts(query.category)  log.info('catalog loaded', { 'product.total': products.length })  return { products, loadedAt: new Date().toISOString().slice(11, 23) }}

routes/examples/data/demo/_catalog.server.js

import products from './_products.json' with { type: 'json' }const latencyMs = 700export const categories = ['hardware', 'books']export async function listProducts(category) {  await new Promise(resolve => setTimeout(resolve, latencyMs))  const visible = categories.includes(category) ? products.filter(product => product.category === category) : products  return visible.map(product => ({ ...product, priceLabel: product.price ? `$${product.price}` : 'free' }))}

routes/examples/data/demo/_products.json

[  { "id": "kbd-60", "name": "60% keyboard", "category": "hardware", "price": 89 },  { "id": "usb-hub", "name": "USB-C hub, 7 ports", "category": "hardware", "price": 42 },  { "id": "desk-mat", "name": "Felt desk mat", "category": "hardware", "price": 24 },  { "id": "sicp", "name": "Structure and Interpretation", "category": "books", "price": 55 },  { "id": "tao", "name": "The Art of Unix Programming", "category": "books", "price": 38 },  { "id": "ostep", "name": "Operating Systems: Three Easy Pieces", "category": "books", "price": 0 }]

Live result

/examples/data/demo/catalog

A real route rendered in a frame: 700 ms of simulated latency in the private helper, so the skeleton stays visible.

load receives { params, query, request, env, log }. The build adds a script to <head> that starts GET /_data/<path>?<query> before any module loads, and the page shows the <if page.loading> branch until it resolves. Every navigation, including a query change, runs load again. The page's own <script> only derives which category link is current from query.

The prebuilt HTML carries the loading chain as an inert template: the skeleton appears once the boot script runs, while content outside the chain, like the category links, is visible immediately. request is the Fetch Request (headers, cookies); env holds the Workers bindings, and on Node it is process.env. Using data.* on a page without a load fails check.

Helpers whose name starts with _ and ends in .server.js are private to the folder and never reach the browser; JSON is imported with with { type: 'json' }. A client module that imports a .server.js file fails pragma check with js/import, and node:* imports are allowed only in server files.

A form backed by a server action

Writes go through call('sign', input), imported from 'pragma', which runs actions.sign in the page's .server.js.

routes/examples/data/_components/guestbook/guestbook.html

<script>  import { data, call } from 'pragma'  let name = ''  let message = ''  let sending = false  let error = ''  async function sign(event) {    const fields = new FormData(event.target)    const signing = call('sign', { name: fields.get('name'), message: fields.get('message') })    if (event.agentInvoked) event.respondWith(signing)    sending = true    error = ''    try {      data.guestbook = (await signing).guestbook      message = ''    } catch (failure) {      error = failure.message    } finally {      sending = false    }  }</script><div class="grid w-full gap-5">  <form class="grid gap-3" toolname="sign_guestbook" tooldescription="Sign the demo guestbook with a name and a short message" @submit="sign">    <label class="guestbook-field">      <span class="label">Name</span>      <input class="guestbook-input" name="name" autocomplete="nickname" toolparamdescription="Name shown on the entry, 2 to 40 characters" :model="$name">    </label>    <label class="guestbook-field">      <span class="label">Message</span>      <input class="guestbook-input" name="message" toolparamdescription="Message of the entry, 3 to 140 characters" :model="$message">    </label>    <div class="flex items-center gap-3">      <button class="btn btn-primary btn-small" :disabled="$sending">Sign</button>      <p class="guestbook-error" role="status">{$error}</p>    </div>  </form>  <if page.loading>    <ul class="grid gap-2" aria-busy="true" aria-label="Loading entries">      <li class="skeleton h-10"></li>    </ul>  </if>  <else-if page.error>    <p class="guestbook-error" role="alert">{page.error.message}</p>  </else-if>  <else>    <ol class="grid gap-2" aria-label="Guestbook entries">      <for entry in data.guestbook key=entry.id>        <li class="guestbook-entry">          <p class="guestbook-meta">{entry.name} <span class="text-faint">{entry.at}</span></p>          <p class="text-sm">{entry.message}</p>        </li>      </for>    </ol>  </else></div><style>  .guestbook-field {    display: grid;    gap: 0.375rem;  }  .guestbook-input {    height: 2.5rem;    padding: 0 0.75rem;    border: 1px solid var(--color-line-strong);    background: var(--color-sunken);    color: var(--color-ink);    font-size: 0.9375rem;    caret-color: var(--color-accent);  }  .guestbook-input:focus-visible { outline-offset: 0; border-color: var(--color-accent); }  .guestbook-error {    color: var(--color-danger-300);    font-family: var(--font-mono);    font-size: 0.75rem;  }  .guestbook-entry {    display: grid;    gap: 0.25rem;    padding: 0.625rem 0.75rem;    border: 1px solid var(--color-line);    background: var(--color-ground);  }  .guestbook-meta {    font-family: var(--font-mono);    font-size: 0.6875rem;    color: var(--color-accent);  }</style>

routes/examples/data/index.server.js

import { readExamples } from '../_source.server.js'export const ssr = trueconst maxEntries = 5const entries = [{ id: 'seed', name: 'pragma', message: 'Signed from the server at boot.', at: '00:00' }]function rejected(message) {  return new Response(JSON.stringify({ error: { message } }), { status: 422, headers: { 'content-type': 'application/json' } })}export async function load() {  const examples = await readExamples('routes/examples/data', {    catalog: [      'demo/catalog.html',      'demo/catalog.server.js',      'demo/_catalog.server.js',      'demo/_products.json',    ],    guestbook: [      '_components/guestbook/guestbook.html',      'index.server.js',    ],    ssr: ['demo/ssr.html', 'demo/ssr.server.js'],    failure: ['demo/catalog.server.js', 'demo/catalog.html'],  })  return { examples, guestbook: entries }}export const actions = {  async sign({ input, request, log }) {    const name = String(input?.name ?? '').trim()    const message = String(input?.message ?? '').trim()    if (name.length < 2 || name.length > 40) return rejected('Name must be 2 to 40 characters.')    if (message.length < 3 || message.length > 140) return rejected('Message must be 3 to 140 characters.')    entries.unshift({ id: crypto.randomUUID(), name, message, at: new Date().toISOString().slice(11, 16) })    entries.length = Math.min(entries.length, maxEntries)    log.info('guestbook signed', { 'user_agent.original': request.headers.get('user-agent') ?? '' })    return { guestbook: entries }  },}

Live result

  1. pragma 00:00

    Signed from the server at boot.

Entries live in server memory and are shared by every visitor until the server restarts. Try a one-letter name to see the 422.

@submit calls preventDefault() for you, then sign() sends a POST /_action/<current path>/sign with a JSON body. data is live: assigning data.guestbook re-renders the list. A non-2xx response makes call throw with the server message, which the component keeps in its let error.

call works from a component too and always targets the current page's .server.js: this guestbook calls routes/examples/data/index.server.js. A server action may return a raw Response to pick the status, here a 422 for invalid input. Actions also receive query and request.

The endpoint answers 404 for an unknown action, 400 for a body that is not JSON and 405 for anything but POST. Actions are the only write path: there are no /api routes and no GET endpoints, so nothing can serve RSS, a sitemap or raw JSON dynamically.

ssr = true: data in the first HTML

With export const ssr = true in the .server.js, the server renders the page with its data, so the skeleton never appears. Reload the frame and the counts arrive already in the HTML.

routes/examples/data/demo/ssr.html

<title>{data.votes} votes · SSR demo</title><meta property="og:title" content="{data.votes} votes · SSR demo"><meta name="robots" content="noindex"><script>  import { data, call, log } from 'pragma'  let hydratedAt = ''  let error = ''  async function vote(option) {    error = ''    try {      const result = await call('vote', { id: option.id })      data.options = result.options      data.votes = result.votes    } catch (failure) {      log.error('ssr demo vote failed', { 'exception.message': failure.message })      error = failure.message    }  }  function mount() {    hydratedAt = new Date().toISOString().slice(11, 23)  }</script><c-demo-page>  <dl class="grid grid-cols-2 gap-px border border-line bg-line font-mono text-xs">    <div class="grid gap-1 bg-ground p-3">      <dt class="text-faint">server rendered at</dt>      <dd class="tabular-nums">{data.renderedAt}</dd>    </div>    <div class="grid gap-1 bg-ground p-3">      <dt class="text-faint">client bound at</dt>      <dd class="tabular-nums text-accent">{$hydratedAt}</dd>    </div>  </dl>  <ul class="grid gap-2" aria-label="Rendering strategies">    <for option in data.options key=option.id>      <li class="flex items-center justify-between gap-4 border border-line px-4 py-3">        <span class="text-sm">{option.label}</span>        <button type="button" class="btn btn-small tabular-nums" aria-label="Vote for {option.label}" @click="vote(option)">{option.total}</button>      </li>    </for>  </ul>  <p class="font-mono text-xs text-danger-300" role="status">{$error}</p>  <p class="font-mono text-xs text-faint">first request by {data.agent}</p></c-demo-page>

routes/examples/data/demo/ssr.server.js

export const ssr = trueconst votes = new Map([['prebuilt', 12], ['ssr', 7], ['islands', 3]])const labels = { prebuilt: 'Prebuilt HTML + /_data fetch', ssr: 'ssr = true', islands: 'Client-only rendering' }function tally() {  return [...votes].map(([id, total]) => ({ id, label: labels[id], total }))}function sumOf(options) {  return options.reduce((sum, option) => sum + option.total, 0)}export async function load({ request }) {  const options = tally()  return {    options,    votes: sumOf(options),    renderedAt: new Date().toISOString().slice(11, 23),    agent: (request.headers.get('user-agent') ?? 'unknown').split(' ')[0],  }}export const actions = {  async vote({ input, log }) {    if (!votes.has(input?.id)) return new Response(JSON.stringify({ error: { message: 'Unknown option' } }), { status: 422 })    votes.set(input.id, votes.get(input.id) + 1)    log.info('ssr demo vote', { 'vote.option': input.id })    const options = tally()    return { options, votes: sumOf(options) }  },}

Live result

/examples/data/demo/ssr

Votes are a server action on an SSR page. Reload the frame and both the list and the page title arrive with the new total.

The line must be literally export const ssr = true. The server runs load, renders the page into <main data-page>, every {data.x} included, and appends the data as <script type="application/json" id="pragma-data">. The client binds to that HTML without re-rendering and without a second fetch. The response is text/html with cache-control: private, no-cache, HEAD works, and a client-side navigation to an SSR route fetches the rendered HTML from the server instead of the prebuilt file.

The page's script and its components' scripts also run on the server, once per request, so their initial lets, props and derived values are in the first HTML too. mount() runs only in the browser: $hydratedAt is empty in the HTML and gets the time when the page boots. A script that reads window, document, localStorage or a store while it runs is left to the browser, and the rest of the page still renders. Head tags take {} too, but only with SSR: this route writes <title>{data.votes} votes · SSR demo</title> and the same in og:title, so link previews see the live count (SEO and head).

When load throws

An error thrown in load reaches the page as page.error.

routes/examples/data/demo/catalog.server.js

import { listProducts } from './_catalog.server.js'export async function load({ query, log }) {  if (query.fail) throw new Error('Inventory service timed out after 700 ms')  const products = await listProducts(query.category)  log.info('catalog loaded', { 'product.total': products.length })  return { products, loadedAt: new Date().toISOString().slice(11, 23) }}

routes/examples/data/demo/catalog.html

<title>Catalog demo · pragma examples</title><meta name="robots" content="noindex"><script>  import { query } from 'pragma'  const current = () => query.fail ? 'broken' : query.category ?? 'all'  const filterLink = () => ({    all: current() === 'all' && 'true',    hardware: current() === 'hardware' && 'true',    books: current() === 'books' && 'true',    broken: current() === 'broken' && 'true',  })</script><c-demo-page>  <nav class="flex flex-wrap gap-x-5 gap-y-2 font-mono text-xs" aria-label="Category">    <a href="/examples/data/demo/catalog" class="nav-link" :aria-current="$filterLink.all">All</a>    <a href="?category=hardware" class="nav-link" :aria-current="$filterLink.hardware">Hardware</a>    <a href="?category=books" class="nav-link" :aria-current="$filterLink.books">Books</a>    <a href="?fail=1" class="nav-link" :aria-current="$filterLink.broken">Make load throw</a>  </nav>  <if page.loading>    <ul class="grid gap-2" aria-busy="true" aria-label="Loading products">      <li class="skeleton h-12"></li>      <li class="skeleton h-12"></li>      <li class="skeleton h-12"></li>    </ul>  </if>  <else-if page.error>    <div class="grid gap-1 border border-danger-500/50 bg-danger-950/40 p-4" role="alert">      <p class="font-mono text-sm text-danger-300">{page.error.message}</p>      <p class="text-sm text-muted">HTTP 500 from /_data. The rest of the page still works: pick a category.</p>    </div>  </else-if>  <else>    <div class="grid gap-2">      <ul class="grid gap-2">        <for product in data.products key=product.id>          <li class="flex items-center justify-between gap-4 border border-line px-4 py-3">            <span class="text-sm">{product.name}</span>            <span class="font-mono text-xs tabular-nums text-muted">{product.priceLabel}</span>          </li>        </for>      </ul>      <p class="font-mono text-xs text-faint">loaded at <span class="tabular-nums">{data.loadedAt}</span> UTC</p>    </div>  </else></c-demo-page>

Live result

/examples/data/demo/catalog?fail=1

The same catalog route with ?fail=1. On an SSR route the status is also 500 and the shell arrives without a rendered body.

The response is HTTP 500 with {"error":{"message"}}, an ERROR log on the server, and {page.error.message} on the client, rendered by the <else-if page.error> branch. Content outside the loading chain, like the filter links, keeps working. "Not found" is not an error: return { product: null } and render it.