Skip to content

Authentication

This guide sets up accounts for a Kiln app with @kiln-js/auth: sign-up and sign-in with email and password, GitHub or Google sign-in, sign-out, and checks that protect pages and API routes.

The package provides the storage-independent logic. You provide a storage adapter, a few pages, and a route file.

1. Install

bash
bun add @kiln-js/auth

2. Create the auth object

Create one module that builds the auth object and exports it. Use the SQLite adapter for a persistent development database:

ts
// app/lib/auth.ts
import { createAuth, sqliteAdapter, github, google } from "@kiln-js/auth";

const adapter = await sqliteAdapter("data/auth.db");

export const auth = createAuth({
  adapter,
  oauth: [
    github({ clientId: process.env.GITHUB_CLIENT_ID!, clientSecret: process.env.GITHUB_CLIENT_SECRET! }),
    google({ clientId: process.env.GOOGLE_CLIENT_ID!, clientSecret: process.env.GOOGLE_CLIENT_SECRET! }),
  ],
  redirects: {
    signedIn: "/account",
    signIn: "/login",
    register: "/register",
  },
});

For a throwaway prototype, memoryAdapter() works without a file. Its data is lost on restart.

The SQLite adapter needs Node 22 or later, or Bun. It does not run on Vercel's Edge runtime. See @kiln-js/adapter-vercel.

3. Mount the routes

Create one catch-all API file. It forwards every /api/auth/… request to the auth object:

ts
// app/api/auth/[...action].ts
import { auth } from "../../lib/auth";

export function GET({ request, params }: { request: Request; params: { action: string } }) {
  return auth.route(request, params.action);
}

export function POST({ request, params }: { request: Request; params: { action: string } }) {
  return auth.route(request, params.action);
}

The routes now exist:

MethodURLPurpose
POST/api/auth/signupCreate an account
POST/api/auth/signinSign in
POST/api/auth/signoutSign out
GET/api/auth/sessionRead the current user as JSON
GET/api/auth/oauth/githubStart GitHub sign-in
GET/api/auth/oauth/github/callbackGitHub's return URL

For OAuth, register the callback URL https://your-domain/api/auth/oauth/github/callback (and the equivalent for Google) in the provider's developer settings. For local development, use http://localhost:3000/....

4. Build the sign-up and sign-in pages

Forms post straight to the auth routes. Read any error from the query string, because a failed form redirects back with ?error=…:

tsx
// app/pages/login.tsx
import { Link } from "@kiln-js/client";

export function loader({ request }: { request: Request }) {
  return { error: new URL(request.url).searchParams.get("error") };
}

export default function Login({ data }: { data: { error: string | null } }) {
  return (
    <main>
      <kiln:title>Sign in</kiln:title>
      <h1>Sign in</h1>
      {data.error && <p role="alert">{data.error}</p>}
      <form method="post" action="/api/auth/signin">
        <label>Email <input name="email" type="email" required /></label>
        <label>Password <input name="password" type="password" required /></label>
        <button>Sign in</button>
      </form>
      <p><a href="/api/auth/oauth/github">Continue with GitHub</a></p>
      <p>No account? <Link href="/register">Create one</Link></p>
    </main>
  );
}
tsx
// app/pages/register.tsx
export function loader({ request }: { request: Request }) {
  return { error: new URL(request.url).searchParams.get("error") };
}

export default function Register({ data }: { data: { error: string | null } }) {
  return (
    <main>
      <kiln:title>Create an account</kiln:title>
      <h1>Create an account</h1>
      {data.error && <p role="alert">{data.error}</p>}
      <form method="post" action="/api/auth/signup">
        <label>Name <input name="name" required /></label>
        <label>Email <input name="email" type="email" required /></label>
        <label>Password <input name="password" type="password" minLength={8} required /></label>
        <button>Create account</button>
      </form>
    </main>
  );
}

Sign-out is a form too:

tsx
<form method="post" action="/api/auth/signout">
  <button>Sign out</button>
</form>

5. Protect a page

Call auth.session in the loader to find the user, and redirect when there is none:

tsx
// app/pages/account.tsx
import { redirect } from "@kiln-js/core";
import { auth } from "../lib/auth";

export async function loader({ request }: { request: Request }) {
  const current = await auth.session(request);
  if (!current) return redirect("/login");
  return { user: current.user };
}

export default function Account({ data }: { data: { user: { name: string; email: string } } }) {
  return (
    <main>
      <kiln:title>Your account</kiln:title>
      <h1>Hello, {data.user.name}</h1>
      <p>{data.user.email}</p>
    </main>
  );
}

auth.requireUser(request) is the same check in one call. It throws a 401 when no one is signed in. Use it in API routes:

ts
// app/api/notes.ts
import { auth } from "../lib/auth";

export async function GET({ request }: { request: Request }) {
  const user = await auth.requireUser(request);
  return Response.json({ owner: user.id });
}

6. Authorize actions

A signed-in user is not always allowed to do everything. Add an authorize hook, and call auth.can:

ts
// in createAuth
hooks: {
  authorize(user, action, resource) {
    if (action === "post.edit") {
      return user !== null && user.id === (resource as { authorId: string }).authorId;
    }
    return user !== null;
  },
},
ts
// in an action
const allowed = await auth.can(request, "post.edit", post);
if (!allowed) return forbidden();

Without an authorize hook, can returns true for any signed-in user.

7. Sign users out everywhere

After a password change, end every session for that user:

ts
await auth.revokeSessions(user.id);

Then clear the current cookie by calling sign-out in the same request, or redirect the user to sign in again.

8. React to events

Hooks run at each step, so you can record sign-ups or block some addresses:

ts
createAuth({
  adapter,
  hooks: {
    async beforeSignUp({ email }) {
      if (email.endsWith("@blocked.example")) {
        throw new AuthError(403, "This email domain cannot register.");
      }
    },
    onSignUp(user, method) {
      console.log(`new user ${user.id} via ${method}`);
    },
  },
});

See @kiln-js/auth for every hook.

How sign-in works

  • A successful sign-up or sign-in sets the kiln_session cookie. It is HttpOnly, SameSite=Lax, and Secure on HTTPS.
  • The cookie holds a random token. The server stores its SHA-256 hash.
  • The session lasts 30 days. When it has less than half its life left, it is extended on the next check.
  • A password is hashed with PBKDF2 and 100,000 iterations.
  • Sign-in failures give the same message for an unknown email and a wrong password.

OAuth accounts

A GitHub or Google sign-in creates an account with no password. If an account with the same email already exists as a password account, the OAuth sign-in is refused with a message asking the user to sign in with their password. This prevents someone who controls an email address at a provider from taking over an existing account.

Checklist

  • Set GITHUB_CLIENT_ID, GITHUB_CLIENT_SECRET, and the Google pair in .env.local, not in committed files.
  • If you turn on CSRF for the whole app, add a CsrfField to the sign-in, sign-up, and sign-out forms as well. Those forms post to /api/auth/…, and the app-wide check applies to them too. See Security.
  • Use a persistent adapter in production, and a database that works from your deployment target.
  • Decide what each authorize action means before you ship.