@kaarel/auth
Docs: Getting started
View .md

Getting started

The package works with any framework that gives you a web Request. Steps 1–3 are the same everywhere. Step 4 connects your framework.

1. Install

bun add @kaarel/auth

2. Add the env vars

AUTH_SECRET=        # bunx kaarel-auth secret
BASE_URL=http://localhost:3000
DATABASE_URL=postgres://localhost/myapp
GOOGLE_CLIENT_ID=
GOOGLE_CLIENT_SECRET=
RESEND_API_KEY=

3. Create the config

Put it in a server-only module. The name and folder are up to you: src/auth.ts, lib/auth.ts, server/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 step 4
});

The tables go into a Postgres schema called auth. The package creates them on first use. Every path in pages and the /auth mount path (basePath) is yours to choose.

4. Connect your framework

Each framework needs three things: the /auth/* routes, a place to call the API (a POST handler), and a guard for signed-in pages.

TanStack Start

// in createAuth: framework: tanstackStart()   (import from "@kaarel/auth/tanstack")

// routes/auth.$.ts — the /auth/* routes
export const Route = createFileRoute("/auth/$")({ server: { handlers: auth.routes } });
// TanStack Start 1.131: export const ServerRoute = createServerFileRoute("/auth/$").methods(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 };
},

Never name a file src/server.ts: TanStack Start uses that name for its server entry.

Next.js (App Router)

// 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" });

Server components only read (auth.user(), auth.session(), requireUser). Sign-in, sign-up and settings go in server actions, because only actions and route handlers can set cookies.

Hono

// 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();
});

Any other framework

Bun.serve, SvelteKit, React Router, Astro, Elysia and others all give a web Request:

  1. Send every request under /auth/* to auth.handler(request) and return its Response.
  2. In a POST handler, call auth.withRequest(request), use its API, and copy api.headers (the Set-Cookie lines) onto your response.
  3. Guard pages with await auth.withRequest(request).user().

See Frameworks for more, and how to write an adapter.

5. Build the login page

The page is yours. It posts e-mail and password to your POST handler from step 4 and shows the result:

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.",
  oauth_denied: "Google sign-in was cancelled.",
};

// after the call:
if (result.ok) location.assign(result.redirectTo); // "/app", or the two-factor page
else showError(text[result.error] ?? "Something went wrong.");
  • The Google button is a plain link: <a href="/auth/google?next=/app">Continue with Google</a>.
  • Redirect flows send errors back as ?error=<code>, so read error from the query string too.
  • A verification link opened in another browser lands on /login?verified=1: show "E-mail confirmed, sign in".
  • Sign-out is a form: <form method="post" action="/auth/sign-out"><button>Sign out</button></form>.
  • Pages import from @kaarel/auth/errors only. @kaarel/auth is server code.

6. Check the setup

bunx --bun kaarel-auth doctor

It finds the config file, checks the secret, the URL and the database, and prints the exact Google redirect URI to paste into the Google Cloud console: https://<your host>/auth/google/callback.