Authentication
SvelteForge Admin uses Better Auth for authentication, wired into SvelteKit through server hooks, form actions, and server-only modules. Better Auth handles sessions, cookies, OAuth, password reset tokens, and the user-management API; SvelteForge adds username sign-in, three roles, Argon2id password hashing, and a few safety guards on top.
- better-auth with the
usernameandadminplugins and thesveltekitCookiesplugin - @node-rs/argon2 — Argon2id password hashing (memory-hard, GPU-resistant), kept from v1 so existing hashes keep working
- Drizzle ORM — Better Auth's tables are ordinary Drizzle tables in
schema.ts
Coming from v1.x? The hand-rolled session code and Arctic are gone; see Upgrading for the migration steps.
Architecture
Four pieces work together:
src/lib/server/auth.ts— Creates theauthinstance with all configuration, hooks, and plugins.src/hooks.server.ts— On every request, resolves the session intoevent.localsand lets Better Auth serve/api/auth/*.- Form actions — Login, register, settings, and user management call
auth.api.*methods directly on the server, passingrequest.headers. - Drizzle tables —
users,sessions,accounts, andverificationsstore everything.
Server Hooks
SvelteKit server hooks run on every request. SvelteForge's hook does two things:
// src/hooks.server.ts
export const handle: Handle = async ({ event, resolve }) => {
event.locals.user = null;
event.locals.session = null;
if (!building) {
try {
const result = await auth.api.getSession({ headers: event.request.headers });
if (result) {
event.locals.user = result.user as SessionUser;
event.locals.session = result.session;
}
} catch (err) {
// DB error or corrupt cookie: continue as unauthenticated.
console.error("Session lookup failed:", err);
}
}
// Serves /api/auth/* (OAuth callbacks, reset links, ...) and passes
// every other request on to SvelteKit.
return svelteKitHandler({ event, resolve, auth, building });
}; - Populates
event.locals.userandevent.locals.sessionso every load function and form action can read the signed-in user. Any failure results in an unauthenticated request rather than an error page. - Serves Better Auth's HTTP endpoints under
/api/auth/*throughsvelteKitHandler. This is where OAuth providers redirect back to and where password reset links land.
The App.Locals interface in src/app.d.ts types both values:
interface Locals {
user: SessionUser | null;
session: Session | null;
} SessionUser and Session are derived from the Better Auth instance (auth.$Infer.Session). SessionUser narrows username and role to string and the admin | editor | viewer union,
because the users table guarantees both.
Better Auth Configuration
Everything lives in src/lib/server/auth.ts, a server-only module that SvelteKit will never include in the client bundle. A condensed walkthrough:
Secret and base URL
export const auth = betterAuth({
appName: "SvelteForge Admin",
baseURL: ORIGIN || "http://localhost:5173",
secret: BETTER_AUTH_SECRET || undefined,
database: drizzleAdapter(db, { provider: "sqlite", schema, usePlural: true }),
// ...
}); BETTER_AUTH_SECRET signs the session cookie and is required in production: the module
throws at startup if it is missing (outside development, the build step, and tests). Generate one
with openssl rand -base64 32. ORIGIN doubles as Better Auth's base URL, so
it controls OAuth callback URLs and the links in emails.
Sessions
session: {
// 30-day sessions that slide forward once less than 15 days remain.
expiresIn: 30 * DAY_SECONDS,
updateAge: 15 * DAY_SECONDS,
}, - Lifetime: 30 days. Once a session has less than 15 days left, the next request extends it (sliding expiration).
- Cookie:
better-auth.session_token, httpOnly and SameSite=Lax, and secure over HTTPS. The value is the session token signed with HMAC usingBETTER_AUTH_SECRET. - Storage: The
sessionstable holds the raw token, expiry, user agent, and IP address (recorded when the session is created). A leaked database alone cannot be turned into a valid cookie, because forging one requires the secret. - Every request looks the session up in the database; there is no cookie cache, so revoking a session takes effect immediately.
Passwords: Argon2id
Better Auth defaults to scrypt. SvelteForge replaces it with the Argon2id functions in src/lib/server/password.ts, which are plain functions with no SvelteKit imports so
the seed script and the v2 migration can use them too:
// src/lib/server/password.ts
const ARGON2_OPTIONS = {
memoryCost: 19456, // ~19 MB memory
timeCost: 2, // 2 iterations
outputLen: 32, // 256-bit output
parallelism: 1, // Single-threaded
} as const;
export const hashPassword = (password: string) => hash(password, ARGON2_OPTIONS);
export async function verifyPassword({ hash, password }) {
try { return await verify(hash, password, ARGON2_OPTIONS); }
catch { return false; } // malformed hash = mismatch
}
// auth.ts
emailAndPassword: {
enabled: true,
minPasswordLength: PASSWORD_MIN, // 8
maxPasswordLength: PASSWORD_MAX, // 255
password: { hash: hashPassword, verify: verifyPassword },
resetPasswordTokenExpiresIn: 60 * 60,
revokeSessionsOnPasswordReset: true,
sendResetPassword: async ({ user, url }) => { /* sendAuthEmail(...) */ },
}, Hashes are stored in accounts.password for the credential account of
each user. The minimum length is 8 characters (v1 allowed 6). Usernames are 3-31
characters of lowercase letters, numbers, hyphens, and underscores. These limits are exported as USERNAME_MIN, USERNAME_MAX, USERNAME_PATTERN, PASSWORD_MIN, and PASSWORD_MAX so forms and tests share one source of truth.
Plugins
plugins: [
username({
minUsernameLength: USERNAME_MIN,
maxUsernameLength: USERNAME_MAX,
usernameValidator: (value) => USERNAME_PATTERN.test(value),
validationOrder: { username: "post-normalization" },
}),
admin({ ac, roles, defaultRole: "viewer", adminRoles: ["admin"] }),
// Must stay last: forwards Set-Cookie from auth.api calls to SvelteKit.
sveltekitCookies(getRequestEvent),
], username— AddsusernameanddisplayUsernamecolumns and thesignInUsernameAPI. Login uses username, not email.admin— Adds therolecolumn, ban fields, and admin APIs (createUser,setRole,removeUser, ...). New users default toviewer.sveltekitCookies— When you callauth.api.signInUsername()inside a form action, Better Auth needs to set a cookie on SvelteKit's response. This plugin does that throughgetRequestEvent(). It must be the last plugin.
Other options
user.fields: { image: "avatarUrl" }— Better Auth'simagefield is stored in the existingavatar_urlcolumn.verification.storeIdentifier: "hashed"— Password-reset and confirmation tokens are stored as SHA-256 hashes, so a leaked database cannot be used to reset anyone's password (Better Auth's default is plain text).user.changeEmail— Enabled. Accounts with an unverified email switch immediately (updateEmailWithoutVerification); verified accounts, such as OAuth sign-ups, get a confirmation link.
Calling Better Auth from Form Actions
SvelteForge's forms are ordinary SvelteKit form actions with progressive
enhancement. They validate input, then call a server-side auth.api.* method. Always
pass request.headers so Better Auth can identify the caller from the session cookie.
// src/routes/(auth)/login/+page.server.ts
export const actions: Actions = {
default: async ({ request }) => {
const formData = await request.formData();
const username = formData.get("username");
const password = formData.get("password");
// ... validate types and lengths ...
try {
// Sets the session cookie through the sveltekitCookies plugin.
await auth.api.signInUsername({
body: { username, password },
headers: request.headers,
});
} catch (err) {
if (isAPIError(err) && (err.statusCode === 401 || err.statusCode === 400)) {
return fail(400, { message: "Incorrect username or password" });
}
if (isAPIError(err)) {
return fail(err.statusCode, { message: err.body?.message ?? "Sign-in failed" });
}
throw err;
}
redirect(302, "/");
},
}; Login deliberately returns the same message for unknown users and wrong passwords, which prevents username enumeration. Banned accounts and similar cases keep Better Auth's own message.
authFailure()
Better Auth throws an APIError when something is wrong. Most actions turn that into a
form failure with one helper from src/lib/server/auth-errors.ts:
export function authFailure(err: unknown, fallback = "Something went wrong. Please try again.") {
if (isAPIError(err)) {
const status = typeof err.statusCode === "number" && err.statusCode >= 400 ? err.statusCode : 400;
return fail(status, { message: err.body?.message || err.message || fallback });
}
throw err; // redirects and unexpected errors pass through
}
// Usage
try {
await auth.api.changePassword({ body: { currentPassword, newPassword }, headers: request.headers });
} catch (err) {
return authFailure(err);
} Which routes call what
| Route | Better Auth call |
|---|---|
/login | auth.api.signInUsername() |
/register | auth.api.signUpEmail() (signs the user in) |
/logout | auth.api.signOut() (deletes the session row, clears the cookie) |
/forgot-password | auth.api.requestPasswordReset() |
/reset-password | auth.api.resetPassword() |
/lock | auth.api.verifyPassword() |
/login/google, /login/github | auth.api.signInSocial() |
| Settings | updateUser, changeEmail, changePassword, revokeSession, revokeOtherSessions |
| Users and Roles | createUser, adminUpdateUser, setRole, removeUser |
Registration and the First Admin
The register action validates name, email, username, and password, then calls auth.api.signUpEmail(). Better Auth creates the user and a credential account and signs the user in.
First user privilege: The first registered user automatically becomes admin. This is done in a Better Auth databaseHooks.user.create.after hook with a single atomic UPDATE that promotes the user only if they are the oldest row
and no admin exists yet, so two people registering at the same moment cannot both become admin.
databaseHooks: {
user: {
create: {
before: async (user) => {
// validates name; derives a unique username for OAuth sign-ups
},
after: async (user) => {
db.run(sql`
UPDATE users SET role = 'admin'
WHERE id = ${user.id}
AND id = (SELECT id FROM users ORDER BY rowid LIMIT 1)
AND NOT EXISTS (SELECT 1 FROM users WHERE role = 'admin')
`);
},
},
},
}, Later registrations get the viewer role. OAuth sign-ups arrive without a username, so
the before hook derives a unique one from the email address.
OAuth (Google + GitHub)
Social login is built into Better Auth and is entirely optional. A provider is enabled only when both its client ID and secret are set:
const socialProviders = {
...(GOOGLE_CLIENT_ID && GOOGLE_CLIENT_SECRET
? { google: { clientId: GOOGLE_CLIENT_ID, clientSecret: GOOGLE_CLIENT_SECRET } }
: {}),
...(GITHUB_CLIENT_ID && GITHUB_CLIENT_SECRET
? { github: { clientId: GITHUB_CLIENT_ID, clientSecret: GITHUB_CLIENT_SECRET } }
: {}),
};
export function getEnabledProviders(): ("google" | "github")[] {
return Object.keys(socialProviders) as ("google" | "github")[];
} The login page loads getEnabledProviders() and only renders buttons for configured providers.
Setting up a provider
- Create the OAuth app in the Google Cloud Console or GitHub Developer Settings.
- Register the redirect (callback) URL, replacing the origin with your own:
{ORIGIN}/api/auth/callback/google{ORIGIN}/api/auth/callback/github
- Add
GOOGLE_CLIENT_ID/GOOGLE_CLIENT_SECRETand/orGITHUB_CLIENT_ID/GITHUB_CLIENT_SECRETto your environment, then restart.
For local development with the default origin, the Google URI is http://localhost:5173/api/auth/callback/google. In v1 the callbacks were /login/google/callback and /login/github/callback; update them when
upgrading.
The flow
- Start —
/login/google(or/login/github) callsauth.api.signInSocial()and redirects the browser to the provider. Better Auth stores the OAuth state and PKCE verifier. - Callback — The provider redirects to
/api/auth/callback/{provider}, handled bysvelteKitHandlerin the hook. Better Auth validates state, exchanges the code, and creates or links the user and anaccountsrow. - Finish — The user lands on
/. On failure they return to/login?error=oauthand see a "Social sign-in failed" message.
// src/routes/(auth)/login/google/+server.ts
export const GET: RequestHandler = async ({ request }) => {
if (!getEnabledProviders().includes("google")) redirect(302, "/login");
const { url } = await auth.api.signInSocial({
body: { provider: "google", callbackURL: "/", errorCallbackURL: "/login?error=oauth" },
headers: request.headers,
});
if (!url) redirect(302, "/login?error=oauth");
redirect(302, url, { external: [new URL(url).origin] });
}; OAuth users have no password. They get the viewer role unless they are the very first account
on a fresh install, and a unique username derived from their email. Their email is already verified
by the provider, so changing it later uses a confirmation link.
Password Reset and Email
Reset and confirmation emails all go through one function:
// src/lib/server/email.ts
export async function sendAuthEmail(email: { to: string; subject: string; text: string; url: string }) {
console.log(`[Auth email] To: ${email.to}`);
console.log(`[Auth email] Subject: ${email.subject}`);
console.log(`[Auth email] Link: ${email.url}`);
// Optional: AUTH_EMAIL_OUTBOX=/path/to/outbox.jsonl also appends each message as a JSON line.
} SvelteForge ships without an email provider. The default implementation logs the
message and link to the server console, which is enough for development. Before production,
replace the body of sendAuthEmail() with your provider (Resend, Postmark, SES,
Nodemailer, ...). Setting AUTH_EMAIL_OUTBOX additionally appends every message to a JSONL
file; the E2E tests use it to read reset links.
Step 1: Request a reset (/forgot-password)
- The user enters their email address.
- The action calls
auth.api.requestPasswordReset({ body: { email, redirectTo: "/reset-password" } }). - Better Auth stores a hashed, one-hour token in
verificationsand callssendResetPassword, which callssendAuthEmail(). - The response is always success, so it never reveals whether the email exists.
Step 2: Choose a new password (/reset-password)
- Better Auth validates the token and redirects to
/reset-password?token=..., or with?error=INVALID_TOKENfor a bad or expired link. - The action validates the new password and calls
auth.api.resetPassword({ body: { newPassword, token } }). revokeSessionsOnPasswordResetsigns the user out everywhere, then the action redirects to/login.
Screen Lock
The screen lock feature (/lock) lets an authenticated user lock the screen and
re-enter their password to continue. The page requires an active session (otherwise it redirects
to /login) and checks the password with auth.api.verifyPassword(); no new
session is created.
Roles and Permissions
Roles are a SQLite text enum: admin, editor, viewer. Access
control for Better Auth's admin APIs is defined in src/lib/permissions.ts and shared by
the server and the UI:
export const statements = {
user: ["create", "list", "set-role", "ban", "impersonate", "impersonate-admins",
"delete", "set-password", "set-email", "get", "update"],
session: ["list", "revoke", "delete"],
} as const;
export const ac = createAccessControl(statements);
export const roles = {
admin: ac.newRole({ user: ["create", "list", "set-role", "ban", "delete",
"set-password", "set-email", "get", "update"],
session: ["list", "revoke", "delete"] }),
editor: ac.newRole({ user: [], session: [] }),
viewer: ac.newRole({ user: [], session: [] }),
}; | Role | Admin API (users, sessions) | App behavior |
|---|---|---|
admin | Full access except impersonation | Manages users, roles, and settings; bypasses maintenance mode |
editor | None | Creates and edits content, deletes their own content |
viewer | None | Read-only access to the dashboard |
Impersonation is granted to no role in the free edition. The statements exist so
the admin plugin's types line up, but neither admin nor any other role holds them. Two-factor
auth, passkeys, organizations, and impersonation are possible through Better Auth plugins in SvelteForge
Premium.
Safety Guards
A hooks.before middleware in auth.ts runs before Better Auth executes
any endpoint. Because it lives in Better Auth rather than in the form actions, the rules apply
equally to SvelteForge's forms and to raw requests against /api/auth/*:
- Demo account protection — When
DEMO_MODE=true, the shareddemouser cannot call/update-user,/change-email,/change-password, or/delete-user. - Last-admin protection —
/admin/set-role,/admin/update-user, and/admin/remove-userare refused if they would demote or delete the only remaining admin. - Authored content —
/admin/remove-useris refused for users who authored pages. Reassign or delete their content first.
hooks: {
before: createAuthMiddleware(async (ctx) => {
if (isDemoMode() && DEMO_PROTECTED_PATHS.has(ctx.path)) {
const session = await getSessionFromCtx(ctx);
if (session?.user.username === "demo") {
throw new APIError("FORBIDDEN", { message: "The shared demo account cannot be modified" });
}
}
// ... last-admin and authored-content checks ...
}),
}, Protecting Routes
Because the hook fills event.locals on every request, guarding a route is a check on locals.user. Protected pages live in the (app) route group, whose layout server
load function guards all of them at once:
// src/routes/(app)/+layout.server.ts
export const load: LayoutServerLoad = async ({ locals }) => {
if (!locals.user) {
redirect(302, "/login");
}
// Maintenance mode: admins bypass it, everyone else gets a 503
const maintenanceSetting = await db.query.appSettings.findFirst({
where: eq(appSettings.key, "maintenanceMode"),
});
if (maintenanceSetting?.value === "true" && locals.user.role !== "admin") {
error(503, "The application is currently under maintenance.");
}
return { user: locals.user, ... };
}; Because this is a layout load function, it runs before every page inside (app). For role-specific actions, check locals.user.role as well. Never rely
on hiding a button: every action must enforce its own rule on the server.
// In any +page.server.ts action
if (locals.user?.role !== "admin") {
return fail(403, { message: "Admin access required" });
} Public routes: the docs/ directory and anything else outside a (group)/ is not covered by the (app) guard and is reachable without signing
in.
Maintenance Mode
The auth guard also enforces maintenance mode. When the maintenanceMode app setting
is "true", all non-admin users receive a 503 Service Unavailable error. Admins
can still use the application to turn it back off from the Settings page, with no code changes or redeployment.
Session Management UI
Settings > Sessions lists the signed-in user's active sessions with browser, operating system,
IP address, and how long ago each began (parsed with src/lib/utils/user-agent.ts).
Users can revoke one session (auth.api.revokeSession) or all others (auth.api.revokeOtherSessions). The session token column is never sent to the browser; revocation looks it up on the
server by session id, scoped to the current user.
Database Schema
Four tables, defined with Drizzle ORM in src/lib/server/db/schema.ts, belong to Better Auth:
| Table | Purpose | Key Columns |
|---|---|---|
users | User accounts | id, name, email, emailVerified, username, role, banned, avatarUrl |
sessions | Active sessions | token, userId, expiresAt, userAgent, ipAddress |
accounts | Login methods | userId, providerId (credential, google, github), accountId, password (Argon2id hash) |
verifications | Reset and confirmation tokens, OAuth state | identifier (hashed), value, expiresAt |
See the Database guide for the full definitions. If you add Better
Auth plugins that need new columns, regenerate the schema with npx @better-auth/cli generate and update SCHEMA_SQL in test-utils.ts.
Security Summary
| Measure | Implementation |
|---|---|
| Password storage | Argon2id with 19 MB memory cost, 2 iterations; minimum 8 characters |
| Session cookie | better-auth.session_token, httpOnly, SameSite=Lax, secure over HTTPS, signed
with BETTER_AUTH_SECRET |
| Session lifetime | 30 days with sliding expiration (extends when less than 15 days remain) |
| Reset and verification tokens | Stored as SHA-256 hashes, one-hour expiry; resetting signs the user out everywhere |
| Username enumeration | Generic error on login; identical response on password-reset requests |
| OAuth | State and PKCE handled by Better Auth; redirect URIs fixed to /api/auth/callback/* |
| Privileged operations | Admin plugin permission checks plus last-admin and demo-account guards in hooks.before |
| Server boundary | All auth code in #lib/server/ — SvelteKit prevents client-side
import |
| Startup check | The app refuses to start in production without BETTER_AUTH_SECRET |
Need More?
Go Premium with DashboardPack
SvelteForge Admin gives you a solid Svelte 5 + SvelteKit authentication foundation on Better Auth. When you need enterprise-grade features — multi-tenant auth, 2FA, passkeys, impersonation, API key management, audit logs, and advanced RBAC — check out the premium templates at DashboardPack.
- Apex (Svelte) — SvelteKit admin with 6 dashboards, 39 pages, and a authentication screens for backend integration
- Zenith — Modern analytics dashboard with advanced data visualization
- Signal — Real-time monitoring dashboard with live data feeds
- Ember — Sleek SaaS dashboard with subscription management
- Flux — Minimalist admin with focus on speed and simplicity