Skip to content

Security

Kiln's defaults are chosen so that a simple site works without setup. Two protections are available and off by default: CSRF checks for state-changing requests, and CORS for cross-origin API calls. This guide explains what each one does, when to turn it on, and what Kiln already protects without configuration.

What Kiln protects by default

  • Server code stays on the server. Importing a .server file into client code fails the build. Server exports (loader, action, revalidate) are removed from client bundles.
  • Cross-origin form posts to pages are refused. A POST to a page action with an Origin header that does not match the page's origin receives 403 Forbidden.
  • Secrets stay out of the browser bundle. Environment variables are read only on the server.
  • Session tokens are stored hashed. The auth package stores a SHA-256 hash of each session token, not the token. See Authentication.
  • Passwords are hashed with PBKDF2 at 100,000 iterations.
  • Cookies are HttpOnly and SameSite=Lax. They are marked Secure on HTTPS.
  • Error details are hidden from visitors in production. The page shows a generic message and a request id.

CSRF

Cross-site request forgery is an attack where another website makes your visitor's browser submit a form to your app. The defense is a token that only pages from your app can read.

Kiln uses the double-submit pattern:

  1. When a page renders a CSRF token, the first response sets an HttpOnly cookie named kiln_csrf with the same value.
  2. The form carries that value as a hidden field called _csrf, or the client sends it in an x-csrf-token header.
  3. On every POST, PUT, PATCH, and DELETE, Kiln checks that the submitted token matches the cookie. A request without a matching token gets 403.

Turn it on for the whole app:

ts
import { createAppHandler, type KilnAssets } from "@kiln-js/server";

export function createHandler(assets: KilnAssets) {
  return createAppHandler({
    assets,
    security: { csrf: true },
  });
}

Render the token in each form:

tsx
import { csrfToken, CsrfField } from "@kiln-js/server";

export async function loader({ request }: { request: Request }) {
  return { csrf: csrfToken(request) };
}

export default function Settings({ data }: { data: { csrf: string } }) {
  return (
    <form method="post">
      <CsrfField token={data.csrf} />
      <input name="displayName" />
      <button>Save</button>
    </form>
  );
}

For JavaScript clients, send the token in a header instead:

ts
await fetch("/api/notes", {
  method: "POST",
  headers: { "content-type": "application/json", "x-csrf-token": token },
  body: JSON.stringify({ text: "hello" }),
});

Exempting paths

Webhooks from other services cannot send your token. Exempt their paths:

ts
security: { csrf: { exempt: ["/api/webhooks/"] } }

Exempt paths skip the check. Keep the list short, and make sure those endpoints verify the request another way, such as a signature.

Behavior notes

  • A request with an Origin header that does not match its URL is refused, even with a valid token.
  • Requests are checked against the cookie, not against your session. The token protects the form, not the user's identity.
  • The first response that carries a token sets the cookie. Visitors who have never loaded a form have no cookie, and their first submission fails. Render a page with a form before expecting a submission to succeed.

CORS

Cross-origin resource sharing controls which other websites can call your API from a browser. It is off by default. Turn it on for /api/ routes that other sites need:

ts
createAppHandler({
  assets,
  security: {
    cors: {
      origins: ["https://app.example.com"],
      credentials: true,
    },
  },
});
OptionDefaultMeaning
origins"*""*", an array of allowed origins, or a function (origin) => boolean.
methodsGET, POST, PUT, PATCH, DELETE, OPTIONSMethods listed in preflight responses.
headersthe requested headers, or content-typeHeaders listed in preflight responses.
credentialsfalseAllow cookies on cross-origin requests. The origin is echoed back, not *.
maxAge600Seconds a browser may cache a preflight answer.
paths["/api/"]Path prefixes CORS applies to.

Rules:

  • With origins: "*" and no credentials, the response says *.
  • With credentials: true, the origin is echoed back, so a wildcard is not used. Set origins to a specific list.
  • A preflight from a disallowed origin gets 403.
  • A request with no Origin header gets no CORS headers. Same-origin requests do not need them.

Do not combine credentials: true with origins: "*". With credentials on, Kiln echoes back whichever origin asks, so every site could make credentialed calls. List your origins instead. If you use a function, compare the full origin, including the scheme and port, so a lookalike domain cannot pass.

Authentication and authorization

CSRF and CORS are about where requests come from. Who may do what is a separate question. Use @kiln-js/auth's requireUser and can in your loaders and actions. See Authentication.

Headers

Kiln does not set Content-Security-Policy, Strict-Transport-Security, or other response headers beyond the cookies and cache headers described above. Add them through a platform configuration, such as vercel.json headers, or in your own handler wrapper. See @kiln-js/adapter-vercel.

Checklist

  • Turn on security.csrf for any app with forms or a POST API.
  • Render csrfToken in every form that posts to a page.
  • Turn on CORS only for origins you trust, and list them.
  • Keep secrets in defineEnv schemas, and read them only on the server.
  • Validate every action's input. See Forms and validation.
  • Add security headers at the platform level.