Mutations

Mutations

Handle form submissions and writes with route actions.

Updated: 2026-07-26

Route action

Export action(ctx) next to your loader. It runs on POST, PUT, PATCH, and DELETE, before the page re-renders. Loaders then run again, so the page shows fresh data.

Because the whole flow is server-side, a plain HTML form works with no client JavaScript at all.

src/pages/contact.tsx
import { redirect } from '@rigbyhost/karui/router';
import type { SiteActionContext, SiteRouteContext } from '@rigbyhost/karui/ssr';

export async function action(ctx: SiteActionContext) {
  const message = String(ctx.request.formData.message ?? '').trim();
  if (!message) return { error: 'Message cannot be empty' };

  await saveMessage(message);
  redirect('/contact?sent=1', 303);
}

export default function Contact(ctx: SiteRouteContext) {
  const result = ctx.actionData as { error?: string } | undefined;

  return (
    <form method="post">
      {result?.error ? <p>{result.error}</p> : null}
      <input name="message" />
      <button type="submit">Send</button>
    </form>
  );
}

Reading the request

ctx.request carries what an action needs, and nothing more. It is transport-agnostic, so a Bun, Deno, or worker handler can build one too.

  • method โ€” the uppercased HTTP method
  • headers โ€” a record with lowercased keys
  • body โ€” the raw request body
  • formData โ€” parsed fields; a repeated field becomes an array
  • json โ€” the parsed body when Content-Type is JSON

POST, redirect, GET

Redirect with status 303 after a successful mutation. A browser reload then re-requests the destination instead of resubmitting the form.

Return a value instead of redirecting when the submission failed validation: it arrives as ctx.actionData and the page renders with the error inline.

Limits

A POST to a route with no action answers 405. Bodies above 1 MB are rejected with 413. multipart/form-data is not parsed โ€” read ctx.request.body yourself for uploads.