Your backend already has auth: sign-up, sessions, passkeys and 2FA in one Bun process
Most side projects die at the auth step. Not because auth is hard to understand — sign-up, log in, keep a session — but because the pieces live in five different places: a user table somewhere, a password hasher, a session store, a token library, a 2FA package, and a pile of glue code that only you understand. By the time it all works, you've spent the weekend on plumbing instead of the thing you actually wanted to build.
Yatta JS takes the opposite approach. It's a backend-as-a-server for Bun: one process with the database, auth, mail, storage, realtime, jobs and observability baked in. When you scaffold a project, auth is already wired up. This is the part of that setup most people skip over, so here's what it actually gives you, and how to use it.
Start with the scaffold
bunx yatta new my-app cd my-app bun run dev That gives you a project with yatta/main.ts, a yatta/backend/ directory for routes and yatta/func/ for the wired-up subsystems — including yatta/func/auth.ts, which already connects auth to your database. The server listens on port 4000 by default.
The one call that sets it up
Auth is created with createAuth from yatta.js/auth:
import { createAuth, type AuthStore } from "yatta.js/auth"; import { db } from "./db"; import { mailer } from "./mail"; export const auth = createAuth({ secret: process.env.AUTH_SECRET || "change-me-32-chars-minimum", store: new SQLiteAuthStore(), // required in production email: { mailer, appUrl: process.env.APP_URL || "http://localhost:4000" }, passkeys: { rpName: "Yatta App", rpID: process.env.RP_ID || "localhost", origin: process.env.APP_URL || "http://localhost:4000", }, }); Two things worth knowing here. First, the secret belongs in AUTH_SECRET — the fallback string is a development convenience only. Second, a real store is required in production. The in-memory default is fine for a script or a test, but it does a linear scan per lookup and enforces nothing, so two concurrent sign-ups for the same address would both succeed. In production, createAuth throws without a store.
Passwords are hashed with Argon2id. Sessions are AES-256-GCM encrypted at rest. Those aren't options you turn on; they're how it works.
Sign-up and sign-in
const result = await auth.signUp({ email: "ada@example.com", password: "CorrectHorseBatteryStaple123!", req, // optional — used for rate limiting and audit }); if ("emailVerificationRequired" in result) { // No session yet; the user must confirm their address first. } else { const { user, session, tokens, cookies } = result; // result.toResponse(body?, status?) builds the whole reply, cookies included. } const login = await auth.signIn({ email: "ada@example.com", password: "CorrectHorseBatteryStaple123!", }); await auth.signOut(sessionToken); Sign-up returns one of two shapes, so check before you destructure: if email verification is on, there's no session yet. Sign-in returns a short-lived access token and a longer refresh token. Resolving the current session later is one call, from a request, a bearer token, or a raw string:
const resolved = await auth.getSession(req); const fromHeader = await auth.getSession(authorizationHeader); const maybe = await auth.getSession(req, { autoRefresh: true }); And a protected route is as boring as it should be:
import { API, createAPI } from "yatta.js/api"; import { auth } from "../func/auth"; const api = createAPI(); api.get(async (ctx) => { const token = ctx.req.headers.get("Authorization")?.replace("Bearer ", ""); const session = await auth.getSession(token); if (!session) return API.json({ error: "Unauthorized" }, { status: 401 }); return API.json({ user: session.user }); }); export default api; Refresh tokens that actually rotate
This is the part most hand-rolled auth gets wrong. Every refresh issues a new refresh token and invalidates the old one. Presenting a token that has already been superseded fails the session outright and emits a security.token_replay event — so a stolen token is usable at most once, and using it logs the legitimate client out. Which is the point.
There's a 30-second grace window for concurrent refreshes, because a client firing two at once would otherwise log itself out for its own timing. Inside that window the replay is only accepted from the same client — same address and user agent. That binding needs a client address, so it only holds when getClientIp is configured.
Refreshing is one call:
const { tokens } = await auth.refresh(refreshToken); // tokens.accessToken — new // tokens.refreshToken — rotated; the old one is now invalid Passkeys, 2FA, and API keys — same object, no extra services
Passkeys are FIDO2 / WebAuthn, two steps each way: send options to the browser, verify what comes back. Registration stores the challenge server-side for five minutes; authentication resolves to the same shape as sign-in.
const options = await auth.passkey.generateRegistrationOptions(userId); const verified = await auth.passkey.verifyRegistration(userId, response, options.challenge); const authn = await auth.passkey.generateAuthenticationOptions(user.email); const result = await auth.passkey.verifyAuthentication(response, authn.challenge); TOTP two-factor is the same pattern. Begin setup, get a base32 secret and an otpauth:// URL for a QR code, confirm with the first code — only then does 2FA count as enabled — and you get recovery codes to show once. Each one works once, in place of a TOTP code. With 2FA on, sign-in returns { mfaRequired, ticket, expiresInSec } instead of a session, and completeMfa({ ticket, code }) finishes it. The ticket is signed, short-lived (five minutes by default) and single-use — it's the proof the first factor passed, so the second step isn't standing on nothing.
API keys are for the machine-to-machine case:
const { apiKey, record } = await auth.apiKeys.create(user.id, { name: "Production CLI", scopes: ["read:data", "write:data"], }); // apiKey → shown once, e.g. "yk_live_..." const principal = await auth.apiKeys.verify(rawKey); principal?.requireScope("write:data"); // throws ForbiddenError if not held Scopes are enforced at verification, not just stored. A key minted with read:data can't write, * is a wildcard, and an empty scope list grants nothing — a forgotten list denies rather than allows. Keys can be revoked per user.
On top of that there's role-based permissions (define roles with accesscontrol, check them with auth.permissions.check), and failed sign-ins are throttled per IP and per account, throwing a RateLimitError — HTTP 429 — when the limit is hit.
One setup line matters more than it looks: per-IP rate limiting needs security.getClientIp configured. Bun keeps the peer address on the server, not on the Request, so without it every request reads as 127.0.0.1 and your per-IP limits collapse into one global limit — one attacker guessing passwords locks out every legitimate user at once. The framework warns at boot when it's missing, in production only.
Your app can also be the login server
The same user store can log people into other apps. Yatta ships an OAuth 2.0 server and OpenID Connect, so another app can send its users to your Yatta app to sign in. That's the other direction from signing in with Google and GitHub, where Yatta is the client.
Why this matters for a solo builder
None of this is new technology. Argon2id, WebAuthn, TOTP, rotating refresh tokens — they've all existed for years. What's new is not having to assemble them. The auth your side project needs — sign-up, sessions, passkeys, 2FA, API keys, rate limiting, roles — is the auth that ships with the runtime, backed by your own database instead of a vendor, in the same process as everything else your backend does.
That's the whole pitch, really. The weekend goes to the app, not the plumbing.
Yatta JS is open source under MIT, on npm as yatta.js (1.0.6). Docs: https://yatta.js.org — Code: https://github.com/psrockstar098/yatta.js
What part of auth has eaten the most of your time on a side project? The password reset flow is my personal nemesis — curious what yours is.
