@kiln-js/server#
@kiln-js/server turns a route table into a request handler. The handler renders pages to HTML, streams .server pages, runs loaders and actions, dispatches API routes, and applies CSRF protection and CORS. It uses standard Request and Response objects, so the same handler runs on Bun, Node, and edge runtimes.
bun add @kiln-js/serverMost projects do not call this package directly. The generated server entry calls createAppHandler, and the Kiln Vite plugin injects the route table. You call it yourself when you need to customize the handler, for example to add security options or a custom template.
Exports at a glance#
| Export | Purpose |
|---|---|
createAppHandler(options) | Build the full handler: pages, API routes, special pages, and security. |
createHandler(context) | The lower-level rendering pipeline that createAppHandler wraps. |
defaultTemplate | The HTML document used when you do not supply a template. |
withSecurity(handler, options) | Wrap any handler with CSRF and CORS. |
csrfToken(request) | Return the CSRF token for a request. |
CsrfField | A hidden form input that carries the CSRF token. |
parseForm(request, schema) | Read a form or JSON body and validate it. |
readBody(request) | Read a form or JSON body into a plain object. |
HttpError, notFound, forbidden, redirect, island, defer, Await | Re-exported from @kiln-js/core. |
Types: AppOptions, SecurityOptions, CorsOptions, CsrfOptions, KilnAssets, RouteEntry, PageModule, LayoutModule, ApiRoute, Specials, and the rest of the types in types.ts.
createAppHandler(options)#
Creates the request handler for your app.
import { createAppHandler, type KilnAssets } from "@kiln-js/server";
export function createHandler(assets: KilnAssets) {
return createAppHandler({
assets,
defaultTitle: "My app",
notFound: "<h1>Page not found</h1>",
});
}Options#
| Option | Type | Default | Meaning |
|---|---|---|---|
assets | KilnAssets | required | The stylesheet links and the entry script for the page. |
routes | RouteEntry[] | injected | The page route table. Injected by the Vite plugin when omitted. |
api | ApiRoute[] | injected | The API route table. Injected when omitted. |
specials | Specials | injected | The _error and _not-found tables. Injected when omitted. |
template | string | defaultTemplate | The HTML document. Must contain the placeholder comments. |
notFound | string | <h1>404: Not found</h1> | HTML sent when no route matches and no _not-found file applies. |
defaultTitle | string | Kiln App | The <title> used when a page sets none. |
security | SecurityOptions | {} | CSRF and CORS. Off by default. |
When routes is not passed, the handler reads the __KILN_ROUTES__ global set by the Vite plugin. If neither exists, it throws No routes found.
Assets#
export interface KilnAssets {
head: string; // HTML for <link rel="stylesheet"> tags
entry: string; // URL of the hashed client script
}The CLI builds these from the Vite manifest. In development, the dev server supplies them.
Template#
The template is a complete HTML document with four placeholders:
| Placeholder | Replaced with |
|---|---|
<!--kiln-head--> | assets.head |
<!--kiln-app--> | The rendered page HTML |
<!--kiln-data--> | The boot script and the entry <script> tag |
<title>…</title> | The page title. Added before </head> when missing. |
The default template is exported as defaultTemplate. Copy it and change the parts you need.
What the handler does, in order#
For every request, the handler works through these steps:
/__kiln/data. A client navigation asks for loader data for a path. The handler runs the target page's loader and returns JSON. A loader redirect comes back as{ "redirect": "..." }.- API routes. If the path matches an API route, the handler calls the method's function and returns the result. Returning
undefinedgives204. Returning a plain value gives JSON. Returning aResponsesends it unchanged. - Page match. The path is matched against the page routes. If nothing matches, the handler renders
_not-foundor thenotFoundstring with status 404. - Method. A
POSTruns the page's action.GETandHEADrender the page. Other methods return405. - Loader. The page's loader runs with
paramsandrequest. - Render. For
universalandserverpages, React renders the page to HTML.clientpages send an empty root element and boot data only. - Response. The HTML is assembled into the template and sent with
text/html.
If a page throws, the handler renders the nearest _error file with status 500 and a request ID. In development the error goes to the overlay instead.
Actions#
A POST to a page with an action export runs the action:
export async function action({ request }: { request: Request }) {
const form = await request.formData();
await save(form.get("title"));
return redirect("/posts");
}Rules:
- A same-origin check runs first. A request whose
Originheader differs from the page's origin gets403 Forbidden. - The result decides the response. A returned
Responseis sent unchanged. When the request asks for JSON withaccept: application/json, a plain result is sent as JSON, or{ "ok": true }when the action returns nothing. Otherwise the browser gets303 See Otherback to the same path.
Caching#
A page that exports revalidate (a number of seconds) is cacheable by a CDN:
export const revalidate = 60;The response gets public, s-maxage=60, stale-while-revalidate=600 and vary: Cookie. A request that carries a Cookie header gets private, no-store instead, so signed-in pages are never shared. Pages without revalidate send no cache header.
createHandler(context)#
The rendering pipeline without the security wrapper and without the injection shortcuts. Use it when you need full control of the context.
import { createHandler } from "@kiln-js/server";
const handle = createHandler({
manifest: async () => routes,
api: async () => apiRoutes,
specials: async () => specials,
template: async () => template,
assets: async () => assets,
notFound: async () => "<h1>Nope</h1>",
defaultTitle: "My app",
});The context interface is KilnContext. template, assets, notFound, and manifest are required. api, specials, and defaultTitle are optional.
Security#
withSecurity(handler, options)#
Wraps a handler with CSRF protection and CORS. createAppHandler calls it with options.security. You can call it yourself on any handler.
import { withSecurity } from "@kiln-js/server";
export default withSecurity(handler, {
csrf: { exempt: ["/api/webhooks/"] },
cors: { origins: ["https://app.example.com"], credentials: true },
});SecurityOptions#
interface SecurityOptions {
cors?: CorsOptions | false | any;
csrf?: CsrfOptions | boolean;
}Both are off by default. csrf: true turns on CSRF with no exempt paths.
CSRF#
CSRF uses the double-submit pattern:
- When a page renders a token, the first response that carries it also sets an HttpOnly cookie named
kiln_csrf. The cookie hasSameSite=Lax, andSecureon HTTPS. - A page reads the token with
csrfToken(request)and renders it into a form. - Each
POST,PUT,PATCH, orDELETEmust send the same token, either as the_csrfform field or as thex-csrf-tokenheader. - A request with an
Originthat differs from the request URL is refused. A request without a matching token is refused with403.
import { csrfToken, CsrfField } from "@kiln-js/server";
export async function loader({ request }: { request: Request }) {
return { csrf: csrfToken(request) };
}
export default function Contact({ data }: { data: { csrf: string } }) {
return (
<form method="post">
<CsrfField token={data.csrf} />
<input name="message" />
<button>Send</button>
</form>
);
}exempt takes path prefixes that skip the check, for webhooks that other services send.
CORS#
CORS applies to /api/ by default. Set paths to change that.
| Option | Default | Meaning |
|---|---|---|
origins | "*" | "*", an array of allowed origins, or a function that returns true for an allowed origin. |
methods | GET, POST, PUT, PATCH, DELETE, OPTIONS | Methods sent in preflight responses. |
headers | the request's access-control-request-headers, else content-type | Headers allowed in preflight responses. |
credentials | false | When true, the origin is echoed back instead of *. |
maxAge | 600 | Seconds a preflight result may be cached. |
paths | ["/api/"] | Path prefixes that CORS applies to. |
A preflight from an origin that is not allowed gets 403. A simple request from an allowed origin gets the access-control-allow-origin header. Requests with no Origin header get no CORS headers.
Forms#
readBody(request)#
Reads a JSON body or a form body into a plain object. Non-string form fields are dropped. A body of any other type returns {}.
const body = await readBody(request);parseForm(request, schema)#
Reads the body and validates it with a schema from @kiln-js/core:
import { parseForm, v } from "@kiln-js/server";
const PostForm = {
title: v.string().min(3),
published: v.boolean(),
};
export async function action({ request }: { request: Request }) {
const result = await parseForm(request, PostForm);
if (!result.ok) {
return Response.json({ errors: result.errors }, { status: 422 });
}
await save(result.data);
return redirect("/posts");
}See Forms and validation.
Re-exports#
These are re-exported from @kiln-js/core so server code can import everything from one place:
HttpError,notFound,forbidden,redirectislanddefer,Await, and theDeferredtype
Types#
export interface AppOptions {
routes?: RouteEntry[];
api?: ApiRoute[];
specials?: Specials;
assets: KilnAssets;
template?: string;
notFound?: string;
defaultTitle?: string;
security?: SecurityOptions;
}
export interface LoaderContext {
params: Record<string, string>;
request: Request;
}
export type ActionContext = LoaderContext;
export interface PageModule {
default: ComponentType<any>;
loader?: (ctx: LoaderContext) => unknown;
action?: (ctx: ActionContext) => unknown;
revalidate?: number;
}
export interface RouteEntry {
pattern: string;
mode: "universal" | "server" | "client";
load: (() => Promise<PageModule>) | null;
layouts: (() => Promise<LayoutModule>)[];
}
export interface ApiContext {
params: Record<string, string>;
request: Request;
}
