@kiln-js/core#
@kiln-js/core contains the code shared by the server and the browser: route matching, the head and title system, environment validation, HTTP errors, islands, deferred data, client-only rendering, and form validation. It also ships a build-time scanner under @kiln-js/core/scan.
bun add @kiln-js/corePeer dependency: react 18 or later.
Most applications import from @kiln-js/core only indirectly, through @kiln-js/server and @kiln-js/client. Import it directly when you need defineEnv, v, validate, the error helpers, or the scanner.
Exports at a glance#
| Export | Kind | Environment | Purpose |
|---|---|---|---|
matchRoute | function | both | Find the route that matches a pathname. |
compose | function | both | Wrap a page element in its layouts. |
RouteProvider | component | both | Make the current pathname and params available. |
usePathname | hook | both | Read the current pathname. |
useParams | hook | both | Read the current route params. |
HeadProvider | component | both | Collect the document title during rendering. |
Title | component | both | Set the document title. |
defineEnv | function | both | Validate and type environment variables. |
HttpError | class | both | An error that carries an HTTP status. |
notFound, forbidden | functions | both | Throw a 404 or 403 response. |
redirect | function | both | Build a redirect response. |
ClientOnly | component | both | Render children only in the browser. |
useIsClient | hook | both | false on the server and during hydration, true afterward. |
island, IslandContext | function, context | both | Mark a component as an island. |
defer, Await | function, component | both | Start slow data on the server and stream it later. |
v, validate | object, function | both | Build and run form schemas. |
scanRoutes, scanApi, scanSpecials | functions | build time only | Read the file tree into route records. |
Types exported: RouteState, HeadSink, EnvField, EnvType, EnvOf, Deferred, Field, Schema, Infer, Validated.
Routing#
matchRoute(routes, pathname)#
Finds the first route whose pattern matches the pathname. Routes are tried in order, so the order matters. The scanner already sorts them so that static segments come before dynamic ones, and dynamic before catch-all.
import { matchRoute } from "@kiln-js/core";
const routes = [
{ pattern: "/blog/:slug" },
{ pattern: "/docs/*path" },
{ pattern: "/" },
];
matchRoute(routes, "/blog/hello");
// { route: { pattern: "/blog/:slug" }, params: { slug: "hello" } }
matchRoute(routes, "/docs/a/b/c");
// { route: { pattern: "/docs/*path" }, params: { path: "a/b/c" } }
matchRoute(routes, "/nothing-here");
// nullRules:
- Segments match exactly, unless they begin with
:. - A segment beginning with
:captures one URL segment. The captured value is URL-decoded. - A segment beginning with
*captures the rest of the path, joined with/, and must be the last segment. - A static route matches only when every URL segment is consumed.
/blogdoes not match/blog/hello. - Empty segments are ignored, so
/blog/and/blogmatch the same route.
The function returns null when nothing matches. It accepts any array of objects with a pattern string, so you can use it for your own route tables.
compose(page, layouts)#
Wraps a page element in a list of layout components. The first layout in the list is the outermost.
import { compose } from "@kiln-js/core";
const tree = compose(<Page />, [RootLayout, DocsLayout]);
// same as <RootLayout><DocsLayout><Page /></DocsLayout></RootLayout>RouteProvider, usePathname, useParams#
The server and the client both wrap rendered pages in RouteProvider. Inside a component you read the route with the hooks:
import { usePathname, useParams } from "@kiln-js/core";
export function Breadcrumb() {
const pathname = usePathname(); // "/blog/hello"
const { slug } = useParams(); // { slug: "hello" }
return <nav>{pathname} / {slug}</nav>;
}Outside a route, usePathname() returns "/" and useParams() returns {}.
Titles and head#
Title#
Sets the page title. The Kiln Vite plugin rewrites <kiln:title> to <Title>, so both forms work:
import { Title } from "@kiln-js/core";
export default function Home() {
return (
<>
<Title>Home · My app</Title>
<h1>Welcome</h1>
</>
);
}On the server, Title records the text in a HeadSink so the handler can write it into <title>. In the browser, it keeps document.title in sync as you navigate. The text is taken from the children as a string. Elements inside the title are ignored, and only strings and numbers are kept.
HeadProvider#
Supplies the HeadSink that Title writes to. The server render wraps each page in it. You rarely use it directly.
export interface HeadSink {
title?: string;
}Environment variables#
defineEnv(schema, source?)#
Validates environment variables against a schema and returns typed values. It throws one error that lists every problem.
import { defineEnv } from "@kiln-js/core";
export const env = defineEnv({
PORT: { type: "number", default: 3000 },
API_KEY: "string",
DEBUG: { type: "boolean", default: false },
});
env.PORT; // number
env.API_KEY; // string
env.DEBUG; // booleanField forms:
- A bare type name, such as
"string", makes the variable required. - An object
{ type, default }makes the variable optional when a default is given.
Parsing rules:
- An empty string counts as missing.
numberusesNumber(raw)and fails when the result isNaN.booleanistruefor1,true,yes, andon, in any letter case. Any other value isfalse.stringis taken as-is.
The second argument defaults to process.env. Pass a plain object to test the function:
defineEnv({ PORT: "number" }, { PORT: "abc" });
// throws: Invalid environment:
// - PORT must be a number, got "abc"The types EnvType, EnvField, and EnvOf describe the schema and the result. EnvOf<S> gives the type of the parsed object for a schema S.
Errors and redirects#
HttpError#
An error that stops rendering and returns a response with that status.
import { HttpError } from "@kiln-js/core";
throw new HttpError(429, "Slow down");The status is stored in status. When you omit the message, Kiln uses Not found for 404, Forbidden for 403, Unauthorized for 401, and Error otherwise.
notFound(message?) and forbidden(message?)#
Shortcuts that throw an HttpError with status 404 or 403. They return never, so TypeScript knows the code after them is unreachable.
export async function loader({ params }: { params: Record<string, string> }) {
const post = await getPost(params.slug);
if (!post) notFound();
return post;
}redirect(location, status?, headers?)#
Returns a Response with a location header. The default status is 303, which asks the browser to follow the redirect with a GET. The allowed statuses are 301, 302, 303, 307, and 308.
export async function action() {
await saveSettings();
return redirect("/settings?saved=1");
}Return a redirect, do not throw it. A loader or action that returns a Response ends the request with that response.
Client-only rendering#
ClientOnly#
Renders children only in the browser. The server and the first browser render both show fallback, so hydration never sees a mismatch.
import { ClientOnly } from "@kiln-js/core";
<ClientOnly fallback={<p>Loading the map…</p>}>
<Map />
</ClientOnly>useIsClient()#
Returns false during server rendering and during the first browser render, and true after the component mounts.
const isClient = useIsClient();Use it when a value differs between server and browser and you need to branch on it.
Islands#
island(id, Component) and IslandContext#
Wraps a component so that the server renders it inside a container, and the browser hydrates only that container. The Kiln Vite plugin creates these wrappers for files that start with "use island", so you rarely call island yourself. See Islands.
When a page renders an island, the island adds its id to the IslandContext set. The server reads that set to decide whether the page needs the client script.
Streaming data#
defer(promise) and Await#
defer starts a promise and returns an object with a read() method that suspends React until the promise settles. Await calls read() and passes the value to a child function.
import { defer, Await } from "@kiln-js/core";
export function loader() {
return { slow: defer(fetchSlowReport()) };
}
export default function Report({ data }: { data: { slow: ReturnType<typeof defer<string>> } }) {
return (
<section>
<h1>Report</h1>
<Await resource={data.slow}>
{(text) => <p>{text}</p>}
</Await>
</section>
);
}On a .server page the shell is sent first, and the deferred content follows when the promise settles. See Streaming.
If the promise rejects, read() throws the error, which reaches the nearest error boundary on the server.
Forms and validation#
v#
A set of field builders. Each builder returns a field that can be chained with checks.
| Builder | Coerces | Chainable checks |
|---|---|---|
v.string() | String(raw).trim() | min(n, msg?), max(n, msg?), email(msg?), matches(regex, msg?) |
v.number() | Number from a number or numeric string, rejects non-finite values | min(n, msg?), max(n, msg?), int(msg?) |
v.boolean() | true for true, on, or 1, and false for anything else | none |
v.enum(values) | A string that must be one of values | none |
Every field also has .optional(). An optional field accepts a missing or empty value and returns undefined.
A missing or empty value fails with This field is required. unless the field is optional. A boolean is different: a missing checkbox means false, so it never fails for being missing.
validate(schema, input)#
Runs every field of a schema against an input object and collects the errors.
import { v, validate } from "@kiln-js/core";
const PostForm = {
title: v.string().min(3).max(120),
email: v.string().email(),
age: v.number().int().min(13).optional(),
published: v.boolean(),
status: v.enum(["draft", "live"] as const),
};
const result = validate(PostForm, { title: "Hi", email: "x", status: "draft" });
if (result.ok) {
result.data; // typed values
} else {
result.errors; // { title: "Use at least 3 characters.", email: "Enter a valid email address." }
result.values; // the raw input
}The return value is a discriminated union. When ok is true, data holds the typed values. When it is false, errors maps each failing field to its first message, and values returns the raw input so a form can redisplay it. Only the first failing check on a field is reported.
Types: Field<T>, Schema, Infer<F>, and Validated<S>.
Build-time scanner#
@kiln-js/core/scan reads the file system. Use it only in build tools and tests. Never import it from browser code. The Kiln Vite plugin is its main user.
scanRoutes(pagesDir)#
Returns an array of RouteRecord objects, sorted so static segments come before dynamic ones:
interface RouteRecord {
file: string; // absolute path of the page file
pattern: string; // "/blog/:slug"
mode: "universal" | "server" | "client";
segments: Segment[];
layouts: string[]; // absolute paths of the layouts that apply, outermost first
}Rules applied by the scanner:
indexmaps to its folder:blog/index.tsxis/blog.- Folders in parentheses are skipped in the URL but still count for layouts.
- Files whose names begin with
_are skipped, except the special files handled byscanSpecials. - A
.serveror.clientsuffix sets the render mode and is removed from the URL. - Two files that map to the same pattern throw
Route conflict.
scanApi(apiDir)#
Returns the API route records. app/api/users/[id].ts becomes /api/users/:id. Two files that map to the same pattern throw API route conflict.
scanSpecials(pagesDir, name)#
Returns records for _error or _not-found files. Each record covers its folder and everything below it, through a catch-all pattern. Records are sorted so the most specific folder wins.
Types#
export type RenderMode = "universal" | "server" | "client";
export interface RouteState {
pathname: string;
params: Record<string, string>;
}
export interface HeadSink {
title?: string;
}
export interface Deferred<T> {
read(): T;
}
