Server actions

Pages run in the browser and can't call other services or hold secret keys. An action is a small piece of your own TypeScript in server/ that runs on the platform when a page calls it: fetch a forecast, start a payment with your key, wake a waiting workflow. The page imports it and calls it like a function; the input is checked before your code runs, and the page gets back what you return.

When to use it

  • A third-party API, especially one that needs a secret key.
  • Several writes that belong together, or a check the browser can't be trusted with.
  • Something signed-out visitors may do beyond reading (a contact form): roles: ["guest"].

Code

// server/bookings.ts
import { defineAction, v } from "@appbricx/server";

export const confirmBooking = defineAction({
  input: v.object({ booking: v.uuid(), note: v.string({ max: 200 }).optional() }),
  roles: ["ops"],                     // required; "guest" lets signed-out visitors call it too
  handler: async (ctx, input) => {
    const row = await ctx.db.update("booking", input.booking, { status: "confirmed", notes: input.note ?? null });
    if (!row) throw new Error("No such booking.");
    return { ref: String(row.ref), status: String(row.status) };
  },
});
// in a route or component: a typed call, no server code in the browser
import { confirmBooking } from "../server/bookings";

try {
  const r = await confirmBooking({ booking: id, note: "confirmed from the list" });   // POST /__appbricx/actions/confirmBooking
  setMsg(r.ref + " " + r.status);
} catch (e) {
  setMsg(e instanceof Error ? e.message : String(e));    // your thrown message, or the input error
}

Input schemas

SchemaAccepts
v.string({ min?, max? })Text, trimmed (at most 10,000 characters unless max)
v.uuid(), v.email()An id; an email address
v.number({ min?, max? }), v.integer(…)A number (a decimal string is read as one); a whole number
v.boolean(), v.enum(["a", "b"])true or false; one of the values
v.array(schema, { max? }), v.object({ … })A list (1,000 items unless max); an object with exactly these fields
.optional(), .nullable()May be left out; may be null
v.any()Anything, unchecked (what a converted JSON app starts with: describe it)

A refused input rejects the call with INVALID_INPUT and a message naming the field (people: must be at most 40); a field the schema doesn't list is refused too.

A secret, by reference

// app.config.ts (names and rules only: values are set per environment)
config: { PAYMENTS_URL: { type: "string", required: ["prod"] } },
secrets: { PAYMENTS_KEY: { hosts: ["api.razorpay.com"], required: ["prod"] } },
http: { allow: ["api.razorpay.com"] },

// server/payments.ts
const res = await ctx.http.fetch(String(ctx.config.PAYMENTS_URL ?? "") + "/v1/orders", {
  method: "POST",
  auth: { basic: ["teamday", ctx.secrets.ref("PAYMENTS_KEY")] },
  json: { amount: input.amount, receipt: input.booking },
});
if (!res.ok) throw new Error("The payment provider answered " + res.status + ".");
const order = res.json<{ id: string }>();

ctx.secrets.ref is a placeholder: the platform puts the value into the request only when it goes to one of the secret's hosts, so your code never holds it, and values are scrubbed from logs, errors and answers. ctx.secrets.get(name) reads a value only for a secret declared expose: true. With http.allow, ctx.http.fetch reaches only those hosts. The values themselves are set per environment with the secrets tool, never in code. See secrets.

What the code gets

NameValue
inputThe checked input, typed from the schema
user (third argument){ id, name, email, role } of the caller, or null when signed out
ctx.dbget, list, create, update, remove, as the caller: their policies apply
ctx.me(role)The caller's profile row id
ctx.http.fetch(url, { method, headers, body | json, auth }){ status, ok, headers, text, json() }
ctx.config, ctx.secretsThe app's config values for this environment; secrets by reference
ctx.signal(name, key, payload)Wakes the workflow runs waiting in step.waitFor(name, { key })
ctx.email, ctx.sms, ctx.pdf(html, { name }), ctx.log, ctx.now()Send a plain message; print a PDF kept as an app file; log lines in the run

Packages that run in a V8 isolate (date-fns, Zod, fetch-based SDKs) work in server/; a Node built-in or a native addon is a check error naming the package. Message templates are sent from workflows(step.send); an action that should send one can create a row a workflow reacts to, or signal one.

Check it

call_app { "project_id": "…", "kind": "action", "name": "confirmBooking",
           "input": { "booking": "…" }, "as": { "kind": "user", "role": "ops" } }
// the status, the body ({ "result": … } or the error) and how long it took

call_app { "project_id": "…", "kind": "action", "name": "confirmBooking", "input": { "booking": "…" } }
// as a signed-out visitor: refused, ops only

workflows { "project_id": "…", "action": "dry_run", "id": "confirmbooking",
            "input": { "booking": "…" }, "as": { "role": "ops" } }   // writes listed, not made

run { "action": "workflow", "id": "confirmBooking", "input": {…}, "as": { "role": "ops" } } runs it for real and waits for the result. Every call is a run in logs, with your ctx.log lines.

Gotchas

  • Never return or throw a secret. Thrown messages are shown to the caller.
  • An action runs as its caller, so it can do only what they could. Work that needs more belongs in a security definer function in db/, with its -- @definer reason (see access).
  • A signed-in caller needs one of the roles, even when "guest" is in the list.
  • Each call carries an idempotency key: a retried call (a double click, a flaky network) answers the first result instead of running twice.
  • Third-party services fail. Handle a rejected call in the page; Open-Meteo answering 503 should read as "try again later", not a blank screen.
  • No React in server/, and no @appbricx/server outside it. The check says which file and line.
  • ctx.ai isn't in an action's types yet. Ask the AI from the page (useAppHandle().ai) or in a workflow (step.prompt); see AI.

Related