@kaarel/auth

Simple auth for any TypeScript server.

Sessions, passwords, Google and GitHub in one config file. You keep your own pages.

Framework-agnostic · Type-safe results · Zero dependencies

$ bun add @kaarel/auth
Read the docs

Using a coding agent? Install with AI

Install with AI

Pick your setup and copy the prompt into Claude Code, Cursor or any coding agent.

Open on its own page
Framework
Database driver
Sign-in methods
Who can sign up
Modules
Extras

install.md

# Add login to this app with @kaarel/auth

Read https://auth.kaarel.dev/llms-full.txt first. It has the whole API. After install, also read node_modules/@kaarel/auth/AGENTS.md.

Framework: TanStack Start. Database: PostgreSQL, Bun built-in (DATABASE_URL).

## Steps

1. Install `@kaarel/auth`.
2. Create the auth config in a server-only module that fits this app's layout (for example `src/auth.ts` or `lib/auth.ts`). Call `createAuth({ ... })` with:
   - `url: process.env.BASE_URL`, `secret: process.env.AUTH_SECRET`
   - `db: process.env.DATABASE_URL` (this works on the Bun runtime only).
   - `methods: [password(), google(process.env.GOOGLE_CLIENT_ID, process.env.GOOGLE_CLIENT_SECRET)]`
   - `email: { from: "<App> <no-reply@<domain>>", send: resend(process.env.RESEND_API_KEY) }`
   - `pages` with the real paths of the pages below
   - Set `framework: tanstackStart()` (import from "@kaarel/auth/tanstack").
3. Mount `auth.routes` on a catch-all server route for `/auth/$`: `createFileRoute("/auth/$")({ server: { handlers: auth.routes } })`. On TanStack Start 1.131 use `createServerFileRoute("/auth/$").methods(auth.routes)`.
4. Call the package from server functions. Every server function that changes something uses `createServerFn({ method: "POST" })`. Do not name any file `src/server.ts`; TanStack Start uses that name for its server entry.
5. Build these pages in this app's own style and language: login (e-mail and password form, handles `?error=`, `?verified=1` and `?next=`); sign-up (shows "check your inbox" when `next` is `verify_email`); forgot password (`auth.password.requestReset`); new password at `pages.resetPassword` (`auth.password.reset` with `?token=`).
6. Protect signed-in routes with `beforeLoad` that calls a server function returning `auth.user()`, and redirects to the login page with `next` when it is null.
7. Add a settings page with: change password (`auth.account.changePassword`); active sessions with "sign out other devices" (`auth.sessions.list`, `revokeOthers`); connected accounts (links to `/auth/<provider>?link=1&next=<settings path>`, `auth.account.unlink`).
8. Add `AUTH_SECRET`, `BASE_URL`, `DATABASE_URL`, `RESEND_API_KEY`, `GOOGLE_CLIENT_ID`, `GOOGLE_CLIENT_SECRET` to the env example file.
9. Run `bunx --bun kaarel-auth doctor` and fix what it reports. Tell me the redirect URIs it prints.

## Rules

- Show every `AuthError` a call can return, in the app's own words. Pages import `AuthError` and `messages` from `@kaarel/auth/errors`; never import `@kaarel/auth` into browser code.
- Handle `reauth_required`: ask for the password and call `auth.account.reauthenticate({ password })`, then retry.
- Use `result.redirectTo` after sign-in and after the two-factor step.
- Do not add a client SDK or any other auth package. Do not write session or cookie code by hand. Do not render pages from the auth package.

Every docs page also has a Markdown version: add .md to its URL. The whole API is in /llms-full.txt, the index in /llms.txt.

Three steps. No client code.

Nothing from the package runs in the browser.

  1. 1Configure it once

    Sign-in methods, e-mails and pages go in one createAuth() call. The tables go into a Postgres schema called auth, created on first use.

    src/auth.ts
    import { createAuth, google, password, resend } from "@kaarel/auth";
    
    export const auth = createAuth({
      url: process.env.BASE_URL!,
      secret: process.env.AUTH_SECRET!,
      db: process.env.DATABASE_URL!, // Bun. On Node: db: pg(pool)
      appName: "Leads",
      methods: [
        password(),
        google(process.env.GOOGLE_CLIENT_ID, process.env.GOOGLE_CLIENT_SECRET),
      ],
      email: { from: "Leads <no-reply@leads.example>", send: resend(process.env.RESEND_API_KEY) },
      pages: { signIn: "/login", afterSignIn: "/app" },
      // framework: tanstackStart() or nextjs(), see the next step
    });
  2. 2Connect your framework

    Mount the /auth/* routes, call the API from POST handlers, and guard signed-in pages.

    // in createAuth: framework: tanstackStart()   (import from "@kaarel/auth/tanstack")
    
    // routes/auth.$.ts — the /auth/* routes
    export const Route = createFileRoute("/auth/$")({ server: { handlers: auth.routes } });
    
    // a server function — POST for every change
    export const signIn = createServerFn({ method: "POST" })
      .validator((data: { email: string; password: string; next?: string }) => data)
      .handler(({ data }) => auth.password.signIn(data));
    
    export const currentUser = createServerFn().handler(() => auth.user());
    
    // guard: in the layout route of signed-in pages
    beforeLoad: async ({ location }) => {
      const user = await currentUser();
      if (!user) throw redirect({ to: "/login", search: { next: location.href } });
      return { user };
    },
  3. 3Show errors in your own words

    error is a typed union, so your editor lists every case.

    login page
    import type { AuthError } from "@kaarel/auth/errors";
    
    const text: Partial<Record<AuthError, string>> = {
      invalid_credentials: "Wrong e-mail or password.",
      email_not_verified: "Confirm your e-mail. We sent a new link.",
      rate_limited: "Too many attempts. Try again later.",
    };
    
    // after the call to your POST handler:
    if (result.ok) location.assign(result.redirectTo); // "/app", or the two-factor page
    else showError(text[result.error] ?? "Something went wrong.");

Read the full guide

Every failure has a name.

Calls that change something return { ok: false, error }. Type your messages as Record<AuthError, string> and TypeScript lists each code you missed.

Codes that password.signIn can return

When each code happens

  • invalid_input
  • invalid_email
  • weak_password
  • password_too_long
  • invalid_credentials
  • email_not_verified
  • email_taken
  • signup_closed
  • access_denied
  • rate_limited
  • forbidden_origin
  • not_signed_in
  • reauth_required
  • invalid_token
  • link_expired
  • oauth_failed
  • oauth_denied
  • oauth_email_unverified
  • account_linked_elsewhere
  • last_sign_in_method
  • method_disabled
  • invalid_code
  • two_factor_not_enabled
  • two_factor_already_enabled
  • challenge_expired
  • not_found
  • forbidden
  • already_member
  • invite_email_mismatch
  • owner_cannot_leave
  • transfer_ownership_first

What is in the package

Sessions
Kept on the server. The cookie holds a random token and the database stores its SHA-256 hash, so sign-out works at once.
Sign-in methods
E-mail and password with argon2id, Google and GitHub. Verification and reset e-mails through Resend or your own sender.
twoFactor
TOTP codes from any authenticator app, and recovery codes.
workspaces
Members, roles and invites by e-mail.
tokens
API tokens for scripts, CLIs and MCP clients.
Runs on
Bun 1.2+ or Node 24.7+, and PostgreSQL 13+. Adapters for TanStack Start and Next.js. Other frameworks use the web Request.

Modules are off until you add them to createAuth(). Their functions exist only when the module is on, and TypeScript knows it.

src/auth.ts
twoFactor: true,                                     // or { issuer: "Acme" }
workspaces: { roles: ["owner", "admin", "member"] }, // highest first; the first is the owner
tokens: true,                                        // or { prefix: "acme" } → tokens look like acme_…