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/authUsing a coding agent? Install with AI
Install with AI
Pick your setup and copy the prompt into Claude Code, Cursor or any coding agent.
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.
1Configure it once
Sign-in methods, e-mails and pages go in one
createAuth()call. The tables go into a Postgres schema calledauth, 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 });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 }; },// in createAuth: framework: nextjs() (import from "@kaarel/auth/next") // app/auth/[...auth]/route.ts — the /auth/* routes export const GET = auth.handler; export const POST = auth.handler; // app/actions.ts — server actions for every change "use server"; export async function signIn(email: string, password: string, next?: string) { return auth.password.signIn({ email, password, next }); } // guard: in a server component of a signed-in page const user = await auth.requireUser({ next: "/app" });// no framework option: Hono gives a web Request app.all("/auth/*", (c) => auth.handler(c.req.raw)); app.post("/api/sign-in", async (c) => { const api = auth.withRequest(c.req.raw); const result = await api.password.signIn(await c.req.json()); return c.json(result, { headers: api.headers }); // headers carry the session cookie }); // guard app.use("/app/*", async (c, next) => { if (!(await auth.withRequest(c.req.raw).user())) return c.redirect(`/login?next=${encodeURIComponent(c.req.path)}`); await next(); });// Bun.serve, SvelteKit, React Router, Astro, Elysia: anything with a web Request // 1. send every request under /auth/* to the package if (url.pathname.startsWith("/auth/")) return auth.handler(request); // 2. in a POST handler: call the API, then copy the Set-Cookie lines const api = auth.withRequest(request); const result = await api.password.signIn(await request.json()); return Response.json(result, { headers: api.headers }); // 3. guard signed-in pages const user = await auth.withRequest(request).user(); if (!user) return Response.redirect(new URL(`/login?next=${url.pathname}`, url));3Show errors in your own words
erroris 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.");
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
invalid_inputinvalid_emailweak_passwordpassword_too_longinvalid_credentialsemail_not_verifiedemail_takensignup_closedaccess_deniedrate_limitedforbidden_originnot_signed_inreauth_requiredinvalid_tokenlink_expiredoauth_failedoauth_deniedoauth_email_unverifiedaccount_linked_elsewherelast_sign_in_methodmethod_disabledinvalid_codetwo_factor_not_enabledtwo_factor_already_enabledchallenge_expirednot_foundforbiddenalready_memberinvite_email_mismatchowner_cannot_leavetransfer_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.
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_…