Skip to content

Loaders and actions

A page often needs data before it renders, and it often needs to handle a form submission. Kiln gives you two exports for this: loader runs before a page renders and supplies its data, and action handles a POST to the page.

Both run on the server only. In the browser build, the Kiln plugin removes them and any imports that are used only by them.

Loaders

A loader is an exported function that runs on the server before the page renders. Its return value becomes the page's data prop.

tsx
// app/pages/blog/[slug].tsx
import { notFound } from "@kiln-js/core";

export async function loader({ params, request }: { params: Record<string, string>; request: Request }) {
  const post = await getPost(params.slug);
  if (!post) notFound();
  return { post, url: request.url };
}

export default function Post({ data }: { data: { post: { title: string; body: string } } }) {
  return (
    <article>
      <kiln:title>{data.post.title}</kiln:title>
      <h1>{data.post.title}</h1>
      <p>{data.post.body}</p>
    </article>
  );
}

What a loader receives

ts
interface LoaderContext {
  params: Record<string, string>; // from the route pattern
  request: Request;               // the incoming request
}

The request gives you headers, cookies, and the query string. Read the query with new URL(request.url).searchParams.

What a loader returns

  • Any JSON-serializable value becomes data.
  • When a page is requested directly, a loader that returns undefined leaves data undefined. When the same data is requested by a client navigation, undefined is sent as null. Return null yourself when you want the same result in both cases.
  • A Response ends the request with that response. Use redirect(...) for a redirect and notFound() or forbidden() to throw an error page.

Do not return functions, class instances with methods, Date objects, or other values that do not survive JSON. A universal page sends data to the browser inside the page, so the value must serialize. A Date becomes a string after a round trip, so convert it yourself.

Loader data on client navigation

When a visitor clicks a Link to a universal page, the client does not load the HTML. It asks the server for the loader's data at /__kiln/data?path=… and renders the page in the browser. Hovering or focusing the link prefetches that data.

This means a loader runs on the server for every navigation, and the page's component runs in the browser. Keep loaders free of browser-only code, and keep secrets out of the returned value.

Caching a page

Export revalidate as a number of seconds to let a CDN cache the rendered page:

ts
export const revalidate = 60;

Requests with a Cookie header are never cached, so signed-in pages stay private. See @kiln-js/server.

Actions

An action handles a POST to a page. Use it for form submissions.

tsx
// app/pages/posts/new.tsx
import { redirect } from "@kiln-js/core";

export async function action({ request }: { request: Request }) {
  const form = await request.formData();
  const title = String(form.get("title") ?? "");
  await createPost({ title });
  return redirect("/posts");
}

export default function NewPost() {
  return (
    <form method="post">
      <input name="title" />
      <button>Publish</button>
    </form>
  );
}

The form posts to the same URL, so the browser sends the request to the action. Forms need no JavaScript.

What happens after an action

The return value of the action decides the response:

  • A Response, such as a redirect, is sent unchanged.
  • When the request asks for JSON with accept: application/json, a plain value is sent as JSON. If the action returns nothing, the response is { "ok": true }.
  • Otherwise the browser receives 303 See Other back to the same path, which reloads the page with a GET.

Returning a plain value from a form action therefore re-renders the page with a fresh GET. To show a message after a failed submission, use redirect with a query string, or return JSON to a JavaScript caller.

Security for actions

  • A POST whose Origin header is different from the page's origin receives 403 Forbidden.
  • The CSRF checks in Security apply to every POST when you turn them on.
  • A page with no action export returns 405 Method Not Allowed for POST.

Validating input

Validate every action's input before you use it. See Forms and validation.

Loaders and actions together

A page can export both. A common pattern is a loader that reads the current data and an action that changes it. After the action redirects, the browser loads the page again, and the loader gives it fresh data.

Errors

Throwing an ordinary error in a loader reaches the nearest _error page with status 500, or the development overlay during kiln dev. An unexpected error in an action is not sent to _error. It is logged and the visitor gets a plain server error. Throwing HttpError (or notFound or forbidden) in either returns that status to the visitor. See Errors.