DocsServer

Functions and “use server”

Functions written in a page that run on the server, and endpoints in a folder.

Server code is JavaScript or TypeScript that runs as the calling user, so every rule still applies. To run a function on the server, mark it with "use server" and call it from the browser like any other function:

islands/add-note.tsx
export async function addNote(title: string, at: Date) {
  "use server";

  // who may call it (by default, anyone)
  "allow: @request.auth.staff = true";
  const made = await server.collection("notes").create({ title });
  return { made, next: new Date(at.getTime() + 86_400_000), tags: new Set(["new"]) };
}

// in the browser
// Date and Set arrive as a real Date and Set
const { next, tags } = await addNote("Milk", new Date());

In the code sent to the browser, the function’s body is replaced with a call to /api/rpc.

Features include:

  • Arguments and results that keep their types: dates, maps, sets, big integers and more
  • Arguments checked against the parameters’ TypeScript types, with no schema to write
  • An address of its own for each function, listed in the API’s description
  • Results that stay current, and calls made during rendering sent with the page
  • Endpoints in functions/, hooks before writes, and scheduled jobs

“use server”

  • Arguments and results keep their types on the way: dates, maps, sets, big integers, typed arrays, errors, undefined, and repeated or circular objects arrive intact.
  • Without "allow: …", anyone can call the function. It runs as the caller, so collection rules still apply.
  • Called from a server component while rendering, it runs directly, with no HTTP request.
  • Sluurp takes the body out and runs it on its own, so the page’s top-level imports aren’t available inside it.

Arguments checked by their types

Before the body runs, Sluurp checks the arguments against the parameters’ types. It reads the types from the file itself, so you don’t write a schema or a validator.

islands/order.tsx
type Size = "s" | "m" | "l";
interface Order { item: string; size: Size; count: number; note?: string }

export async function order(o: Order, when?: Date) {
  "use server";
  return server.collection("orders").create({ ...o, when });
}

A call with { item: "Tea", size: "xl", count: 1 } doesn’t run the body. It gets a 400 that says what is wrong: order: o.size should be "s" or "m" or "l", not text.

  • The checker understands string, number, boolean, null, literal types, unions, arrays, tuples, object types and interfaces (with extends), Record, Partial and Date, and the types and interfaces declared in the same file.
  • A type it can’t read, such as one imported from another file, a generic or any, accepts anything.
  • A date may arrive as an ISO string; the function receives a real Date.
  • A plain JSON call or a form sends text. There, "3" is accepted for a number and "on" for a boolean.

Call a function at its address

Each server function also has an address of its own, taking its arguments by name. This is the address the API’s description lists for it:

curl -X POST http://localhost:8090/api/rpc/islands/order.tsx/order \
  -H 'Content-Type: application/json' \
  -d '{ "o": { "item": "Tea", "size": "m", "count": 2 } }'

A JSON array of the arguments, in order, works too.

Give functions to an AI model

Server functions can be the tools of an AI assistant: the model calls them, and the server runs each call as the person asking.

Return rows that stay current

To return rows that stay current, use server.live(collection, options). It takes the same filter, sort and expand as a list, and limit for a window:

islands/orders.tsx
export async function ordersOf(customer: string) {
  "use server";
  return server.live("orders", { filter: `customer = "${customer}"`, sort: "-created_at" });
}

// in the browser: a function that reads the rows, kept current
const rows = await ordersOf(id);
rows(); // the orders, now and as they change

The function runs once. The rows are kept current over the page’s sync connection, read from the database as the caller, under the collection’s rules. Nothing on the server keeps running for it. Promises anywhere in a result are settled before it is sent. Rendered on the server, rows() gives the rows as they are at that moment.

Calls made while a page renders

A call is known by what it calls: the file, the function and its arguments.

  • When a server page renders, the results of the calls it made travel with the page. The browser uses them for the first render instead of calling again. After the first click or key, or once the page has settled, calls ask the server again.
  • The same call made twice at the same moment is sent once.

Endpoints

Each file in functions/ becomes an endpoint at /api/fn/<name>, versioned and rolled back with the app:

functions/order-summary.ts
// the app's own modules
import { average } from "../lib/totals.ts";
import seasons from "../data/seasons.json" with { type: "json" };

export const rule = "@request.auth.id != null";
export const method = "GET";

export default async function (ctx) {
  const page = await ctx.collection("orders").list({ filter: `customer = "${ctx.auth.id}"` });
  return { average: average(page.items.map((o) => o.total)), season: seasons.autumn };
}

To keep one record per something, such as when each person last looked at each feed, use upsert. It updates the record that matches, or makes one from both. With a unique index on the matched fields, two requests at once still make a single record: the second updates it.

functions/seen.ts
ctx.collection("seen").upsert({ person: ctx.auth.id, feed }, { at: ctx.now() });

Run as the system

export const runAs = "system" sets the caller’s rules aside, for example for totals everyone may see although the rows are private. The function then is the policy, so return totals, never rows.

Hooks and jobs

A file in hooks/ runs before every write to its collection, whatever made the write. Its reads set rules aside, since it is policy rather than user code, so it can enforce what rules can’t, such as counts or checks across rows:

hooks/projects.ts
export async function beforeCreate({ record, db, reject }) {
  const led = await db.count("projects", `lead = "${record.lead}"`);
  if (led >= 2) reject(`already leading ${led} projects`);

  // the record to write
  return { ...record, name: record.name.trim() };
}

A file in jobs/ runs on a schedule:

jobs/nightly.ts
export const schedule = "0 2 * * *";
export default async function (ctx) { /* … */ }

See Hooks and events and Scheduled jobs.

Where it runs

Server code runs on Bun, in workers beside the server. It has:

  • ctx, through which it reaches its data, as the caller, so every rule applies;
  • the web’s standard globals: fetch, URL, TextEncoder, crypto, timers, AbortController, structuredClone;
  • npm packages installed with bun add.

fetch can reach any address, because your server code is trusted like the rest of your app. To keep functions away from this machine and your private network, turn on Public addresses only in Settings. Once Settings has Only these on, each function reaches only the hosts it was seen reaching or was allowed. For an address somebody else gave you, such as a link a user posted, pass publicOnly: true. See Security.

The event loop

Server code runs on an event loop, as in Node. fetch starts a request and returns straight away, so requests made together run side by side:

functions/prices.ts
export default async function () {
  const [eur, usd] = await Promise.all([
    fetch("https://example.com/rates/eur").then((r) => r.json()),
    fetch("https://example.com/rates/usd").then((r) => r.json()),
  ]);
  return { eur, usd };
}

A response’s body is a stream, read as it arrives. That suits large downloads, server-sent events and long polls:

functions/follow.ts
export default async function () {
  const response = await fetch("https://example.com/events");
  let lines = 0;
  for await (const chunk of response.body) {
    lines += new TextDecoder().decode(chunk).split("\n").length - 1;
    if (lines > 100) break;
  }
  return { lines };
}

Time limits

  • 5 seconds of computing in a row. A function that runs JavaScript for longer without pausing, such as a loop that never ends, is stopped. Time spent waiting on a request or a timer doesn’t count towards it.
  • 60 seconds in all. A call is stopped after a minute, waiting included, so a slow service can hold a function for up to a minute, not longer.
  • Waiting holds no thread. Server code runs in Bun workers, apart from the threads that answer requests, so a function that waits or computes never slows the rest of the app.
  • AbortController cancels a request. When the client that called a function goes away, Sluurp stops waiting for its answer.
  • Hooks and views run the same way, with the same limits. Keep them quick: a hook holds up the write it runs before.

View as Markdown