API Reference

SvelteForge Admin exposes server-side utilities for authentication (Better Auth), database access, data export, and ID generation — all fully typed with TypeScript. These modules power the Svelte 5 and SvelteKit application and are available for use in your own server routes, form actions, and hooks.

All server-side modules live in #lib/server/, which SvelteKit guarantees will never be included in client-side bundles. Client-safe utilities are in #lib/utils/ and #lib/utils.ts.

Auth Module

#lib/server/auth.ts — The configured Better Auth instance, plus the validation constants and helpers the auth routes share. Better Auth owns sessions, cookies, password verification, OAuth, and password resets; see the Authentication guide for the full configuration.

auth

The Better Auth instance (username and admin plugins, sveltekitCookies). Server code calls its auth.api.* methods and passes the request's headers so Better Auth can read the session cookie. A failed call throws an APIError.

import { auth } from "#lib/server/auth.js";
import { authFailure } from "#lib/server/auth-errors.js";

// In a form action:
try {
  await auth.api.changePassword({
    body: { currentPassword, newPassword },
    headers: request.headers,
  });
} catch (err) {
  return authFailure(err);
}

authFailure(err, fallback?): ActionFailure

From #lib/server/auth-errors.ts. Converts a Better Auth APIError into a SvelteKit fail() with the error's status and message. Anything that is not an APIError (including SvelteKit redirects) is rethrown.

Validation constants

import {
  USERNAME_PATTERN, // /^[a-z0-9_-]+$/
  USERNAME_MIN,     // 3
  USERNAME_MAX,     // 31
  PASSWORD_MIN,     // 8
  PASSWORD_MAX,     // 255
} from "#lib/server/auth.js";

getSession and session cookies

You rarely call these yourself: hooks.server.ts runs auth.api.getSession() on every request and fills event.locals. The cookie is named better-auth.session_token and is signed with BETTER_AUTH_SECRET. Sign out with auth.api.signOut({ headers }), which deletes the session row and clears the cookie.

To revoke every other session for the current user, call auth.api.revokeOtherSessions({ headers: request.headers }). To revoke one session, call auth.api.revokeSession({ body: { token }, headers }) with the row's token.

Type: SessionUser

The user object available in event.locals.user throughout your SvelteKit application. It is Better Auth's session user with username and role narrowed to the types the users table guarantees:

type SessionUser = Omit<BetterAuthSessionUser, "username" | "role"> & {
  username: string;
  role: "admin" | "editor" | "viewer";
};
// Includes id, name, email, emailVerified, image (avatar), createdAt, updatedAt, ...

getEnabledProviders(): ("google" | "github")[]

Returns the OAuth providers that are currently configured (both client ID and secret set). Used by the login page to conditionally render social login buttons.

import { getEnabledProviders } from "#lib/server/auth.js";

const providers = getEnabledProviders();
// => ["google", "github"] or ["google"] or []

Password and Email Helpers

hashPassword(password) / verifyPassword({ hash, password })

#lib/server/password.ts — Argon2id hashing (19 MiB, 2 iterations) kept from v1 and registered with Better Auth, so existing hashes keep working. This module has no SvelteKit imports, so scripts such as the seeder and the v2 migration can use it.

sendAuthEmail({ to, subject, text, url })

#lib/server/email.ts — Every auth email (password reset, email-change confirmation, verification) goes through this one function. The default implementation logs the message and link to the server console and, when AUTH_EMAIL_OUTBOX is set, appends it as a JSON line to that file. Replace the body with your email provider.

Permissions

#lib/permissions.ts exports ac (access control statements) and roles (admin, editor, viewer) for the admin plugin. Only admins can list, create, update, delete, ban, or change the role of users and list or revoke sessions. No role can impersonate users in the free edition.

Database

#lib/server/db/index.ts — Drizzle ORM instance configured with SQLite (better-sqlite3) in WAL mode. Provides full type inference from the schema for use in SvelteKit server routes and form actions.

db

The Drizzle ORM instance with the full schema loaded. Supports both the SQL-like query builder and the relational query API.

import { db } from "#lib/server/db/index.js";
import { users } from "#lib/server/db/schema.js";
import { eq } from "drizzle-orm";

// SQL-like query builder
const allUsers = await db.select().from(users);

// Relational query API
const user = await db.query.users.findFirst({
  where: eq(users.email, "[email protected]"),
});

Schema Tables

All tables are exported from #lib/server/db/schema.ts and available through the db instance:

TableDescription
usersUser accounts with role-based access control (admin, editor, viewer)
sessionsActive Better Auth sessions with token, expiry, and metadata
pagesCMS content with templates (default, landing, blog) and status workflow
notificationsUser and global notifications with read/unread tracking
accountsLogin methods per user: credential (Argon2id password) and OAuth links (Google, GitHub)
appSettingsKey-value application configuration
verificationsShort-lived hashed tokens for password resets, email-change confirmations, and OAuth state

Type Exports

Inferred TypeScript types for all database entities, available for use in your Svelte 5 components and SvelteKit server routes:

import type {
  User,
  Session,
  Page,
  Notification,
  Account,
  Verification,
  AppSetting,
} from "#lib/server/db/schema.js";

ID Generator

#lib/server/id.ts — Cryptographic random ID generation used for all entity identifiers throughout the SvelteKit application.

generateId(length?: number): string

Generates a cryptographically random ID using node:crypto's randomBytes(), encoded as base32 lowercase without padding. Default length is 15 bytes, producing a 24-character string with 120 bits of entropy.

import { generateId } from "#lib/server/id.js";

const userId = generateId();       // 24 chars, 120 bits of entropy
const shortId = generateId(10);    // 16 chars, 80 bits of entropy

Used for application row IDs: pages, notifications, and seed data. The auth tables (users, sessions, accounts, verifications) use Better Auth's own ID generator.

Export Utilities

#lib/utils/export.ts — Client-side data export functions that trigger browser downloads. Used by the user management and content management pages in the Svelte 5 application.

exportToCSV(data, filename): void

Converts an array of objects to CSV format with proper escaping (handles commas, quotes, and newlines in values) and triggers a browser download.

import { exportToCSV } from "#lib/utils/export.js";

// Triggers download of "users.csv"
exportToCSV(users, "users.csv");

exportToJSON(data, filename): void

Converts an array of objects to pretty-printed JSON (2-space indentation) and triggers a browser download.

import { exportToJSON } from "#lib/utils/export.js";

// Triggers download of "users.json"
exportToJSON(users, "users.json");

Both functions work by creating a Blob, generating an object URL, programmatically clicking a hidden anchor element, and then revoking the URL to free memory.

User-Agent Parser

#lib/utils/user-agent.ts — Lightweight user-agent string parser used by the session management UI to display readable browser, OS, and device information.

parseUserAgent(ua: string): { browser, os, device }

Parses a user-agent string and returns structured information about the client.

import { parseUserAgent } from "#lib/utils/user-agent.js";

const info = parseUserAgent(
  "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0.0.0 Safari/537.36"
);
// => { browser: "Chrome", os: "macOS", device: "Desktop" }
FieldDetected Values
browserEdge, Opera, Chrome, Firefox, Safari, or "Unknown"
osWindows, macOS, Android, iOS, iPadOS, Linux, ChromeOS, or "Unknown"
deviceMobile, Tablet, Desktop

Utility Helpers

#lib/utils.ts — Shared utility functions used across the Svelte 5 application.

cn(...inputs: ClassValue[]): string

Combines clsx (conditional class merging) with tailwind-merge (Tailwind CSS class deduplication). The standard pattern for dynamic class names in shadcn-svelte components.

import { cn } from "#lib/utils.js";

// Conditional classes with Tailwind deduplication
const classes = cn(
  "px-4 py-2 rounded-md",
  isActive && "bg-primary text-primary-foreground",
  isDisabled && "opacity-50 cursor-not-allowed"
);
// Tailwind-merge prevents conflicts like "px-4 px-2" => "px-2"

Type Utilities

Helper types for shadcn-svelte component composition. These strip children/child snippet props to allow wrapping components without type conflicts:

import type { WithoutChild, WithoutChildren, WithElementRef } from "#lib/utils.js";

// WithoutChild<T> — removes the "child" snippet prop
// WithoutChildren<T> — removes the "children" snippet prop
// WithElementRef<T, E> — adds a typed element ref prop

API Endpoints

SvelteForge Admin includes a few API endpoints accessible via standard HTTP requests, plus Better Auth's own endpoints under /api/auth/*.

/api/auth/*

Handled by Better Auth through svelteKitHandler in hooks.server.ts. The important ones for setup are the OAuth callbacks (/api/auth/callback/google and /api/auth/callback/github) and the password reset link handler. The app's own forms call auth.api.* directly, but the HTTP endpoints are live too, which is why the demo-account and last-admin guards are implemented in Better Auth's hooks.before rather than in the form actions.

GET /api/search?q={query}

Full-text search across users, pages, and notifications. Returns categorized results with icons. Powers the command palette (Cmd+K / Ctrl+K) in the Svelte 5 application shell.

// Request
GET /api/search?q=admin

// Response
{
  "results": [
    {
      "title": "Admin User",
      "description": "[email protected]",
      "url": "/users",
      "category": "Users",
      "icon": "users"
    },
    {
      "title": "Admin Dashboard Settings",
      "description": "Configure dashboard preferences",
      "url": "/content/admin-dashboard-settings",
      "category": "Pages",
      "icon": "file-text"
    }
  ]
}

The search endpoint queries all three tables using SQL LIKE patterns and returns a unified result set. Results are limited to prevent large responses.

GET /sitemap.xml

Auto-generated XML sitemap for SEO. Returns all published page URLs in standard sitemap format. This SvelteKit server route dynamically queries the pages table for published content.

App.Locals Type

SvelteKit populates event.locals on every request via the hooks.server.ts hook. The type is defined in src/app.d.ts:

// src/app.d.ts
declare global {
  namespace App {
    interface Locals {
      user: SessionUser | null;
      session: Session | null;
    }
  }
}

event.locals.user and event.locals.session are available in all SvelteKit server-side code: +page.server.ts load functions, form actions, +server.ts API routes, and hooks.

// Example: +page.server.ts
export const load = async (event) => {
  const user = event.locals.user;
  if (!user) redirect(302, "/login");

  return {
    user,
    // ... load page data
  };
};

Next Steps

  • Authentication — Full auth flow walkthrough with OAuth setup
  • Database — Complete schema reference and query patterns
  • Deployment — Production deployment with Docker, Railway, Fly.io

Need More?

Full API with DashboardPack

Need a full REST API with OpenAPI docs, webhook support, and third-party integrations? DashboardPack premium templates include complete API layers with authentication, rate limiting, pagination, filtering, and auto-generated documentation — ready for your Svelte 5 and SvelteKit frontend.

  • Apex (Svelte) — SvelteKit admin with 6 dashboards, full CRUD modals, and reactive data tables system
  • Zenith — GraphQL API with subscriptions, real-time data streaming, and query optimization
  • Signal — API monitoring dashboard with request logging, error tracking, and performance metrics

Release Health

GET /api/health returns the status, package version, and build commit. It is public and uses Cache-Control: no-store; deployment checks its commit against GitHub.