API Reference
SvelteForge Admin exposes server-side utilities for authentication, 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 — Session management with SHA-256 hashed tokens, automatic
session extension, and secure cookie handling. This is the core authentication layer for your SvelteKit application.
generateSessionToken(): string
Generates a cryptographically random session token. Uses 20 bytes of randomness encoded as base32 (lowercase, no padding).
import { generateSessionToken } from "#lib/server/auth.js";
const token = generateSessionToken();
// => "4bv7h2xk9qm3np6wr8yta5cj2dfs7g" Token hashing is an internal implementation detail: sessions use Node’s SHA-256 implementation.
Call createSession() and validateSession() rather than importing the private
hash helper.
createSession(token, userId, metadata): Promise<Session>
Creates a new session in the database. The token is hashed before storage. Metadata (user agent and IP address) is recorded for security auditing.
import { generateSessionToken, createSession } from "#lib/server/auth.js";
const token = generateSessionToken();
const session = await createSession(token, user.id, {
userAgent: event.request.headers.get("user-agent") || "",
ipAddress: event.getClientAddress(),
});
// session.id = SHA-256 hash of token
// session.expiresAt = Date.now() + 30 days validateSession(token): { session, user } | { session: null, user: null }
Validates a session token by hashing it and looking up the session in the database. If the session
is valid but less than 15 days from expiry, it is automatically extended for another 30 days.
Returns the session and user objects, or null for both if invalid or expired.
import { validateSession } from "#lib/server/auth.js";
const result = await validateSession(token);
if (result.session) {
// Authenticated — result.user has the SessionUser data
console.log(result.user.email, result.user.role);
} else {
// Invalid or expired token
} invalidateSession(sessionId: string): Promise<void>
Deletes a single session from the database. Used during logout.
import { invalidateSession } from "#lib/server/auth.js";
await invalidateSession(session.id); To revoke every session for a user, delete their rows with Drizzle. There is no exported invalidateAllSessions() helper.
import { db } from "#lib/server/db/index.js";
import { sessions } from "#lib/server/db/schema.js";
import { eq } from "drizzle-orm";
await db.delete(sessions).where(eq(sessions.userId, user.id)); setSessionCookie(cookies, token, expiresAt): void
Sets the session cookie on the response. The cookie is httpOnly, sameSite=lax, path=/, and secure in production (outside development
mode).
import { setSessionCookie } from "#lib/server/auth.js";
setSessionCookie(event.cookies, token, session.expiresAt); deleteSessionCookie(cookies): void
Clears the session cookie by setting it to an empty value with an immediate expiry.
import { deleteSessionCookie } from "#lib/server/auth.js";
deleteSessionCookie(event.cookies); Type: SessionUser
The user object returned by validateSession() and available in event.locals.user throughout your SvelteKit application:
type SessionUser = {
id: string;
email: string;
username: string;
name: string;
role: "admin" | "editor" | "viewer";
avatarUrl: string | null;
}; OAuth Module
#lib/server/oauth.ts — Arctic OAuth providers for Google and GitHub. Providers are
conditionally initialized based on environment variables, making OAuth entirely optional in your SvelteKit deployment.
google: Google | null
Arctic Google OAuth provider instance. Returns null when GOOGLE_CLIENT_ID and GOOGLE_CLIENT_SECRET environment variables are not set.
import { google } from "#lib/server/oauth.js";
if (google) {
const url = google.createAuthorizationURL(state, codeVerifier, {
scopes: ["openid", "profile", "email"],
});
} github: GitHub | null
Arctic GitHub OAuth provider instance. Returns null when GITHUB_CLIENT_ID and GITHUB_CLIENT_SECRET environment variables are not set.
import { github } from "#lib/server/oauth.js";
if (github) {
const url = github.createAuthorizationURL(state, ["user:email", "read:user"]);
} getEnabledProviders(): string[]
Returns an array of provider names that are currently configured. Used by the login page to conditionally render social login buttons.
import { getEnabledProviders } from "#lib/server/oauth.js";
const providers = getEnabledProviders();
// => ["google", "github"] or ["google"] or [] 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:
| Table | Description |
|---|---|
users | User accounts with role-based access control (admin, editor, viewer) |
sessions | Active sessions with hashed tokens, expiry, and metadata |
pages | CMS content with templates (default, landing, blog) and status workflow |
notifications | User and global notifications with read/unread tracking |
oauthAccounts | Linked OAuth provider accounts (Google, GitHub) |
appSettings | Key-value application configuration |
passwordResetTokens | Time-limited password reset tokens with hashed values |
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,
OAuthAccount,
AppSetting,
PasswordResetToken,
} 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 crypto.getRandomValues(), 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 all entity IDs: users, sessions, pages, notifications, OAuth accounts, password reset tokens, and app settings.
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" } | Field | Detected Values |
|---|---|
| browser | Edge, Opera, Chrome, Firefox, Safari, or "Unknown" |
| os | Windows, macOS, Android, iOS, iPadOS, Linux, ChromeOS, or "Unknown" |
| device | Mobile, 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 two API endpoints accessible via standard HTTP requests.
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.