Database

SvelteForge Admin uses SQLite as its database, accessed through Drizzle ORM with the better-sqlite3 driver. This gives your Svelte 5 and SvelteKit application a zero-configuration, high-performance database that lives as a single file in your project root.

Why SQLite

SQLite is the ideal database for SvelteKit admin dashboards and internal tools:

  • Zero configuration — No database server to install, configure, or maintain. Just a single file (svelteforge.db) in your project root.
  • Simple local setup — Embedded SQLite needs no separate database service. With WAL mode enabled, concurrent reads never block each other.
  • Perfect for deployment — Deploy your SvelteKit app with its database as a single unit. No connection strings to manage, no cold start latency.
  • Type-safe with Drizzle — Drizzle ORM provides full TypeScript inference from your schema, catching query errors at compile time in your Svelte 5 components and SvelteKit server routes.

Connection Setup

The database connection is established in src/lib/server/db/index.ts. Because this file lives inside SvelteKit's #lib/server/ directory, it is guaranteed to never leak to the client bundle — a key security feature of SvelteKit's module system.

// src/lib/server/db/index.ts
import Database from "better-sqlite3";
import { drizzle } from "drizzle-orm/better-sqlite3";
import * as schema from "./schema.js";

const dbPath = process.env.DATABASE_URL || "svelteforge.db";
const sqlite = new Database(dbPath);
sqlite.pragma("journal_mode = WAL");

export const db = drizzle(sqlite, { schema });

Key details:

  • WAL journal mode — Write-Ahead Logging allows concurrent reads while a write is in progress. This is critical for SvelteKit apps where multiple server-side load functions may query simultaneously.
  • DATABASE_URL env var — Defaults to svelteforge.db in the project root. Override it in production to point to a persistent volume.
  • Full schema import — Passing the entire schema to drizzle() enables Drizzle's relational query API (db.query.users.findFirst(), etc.).

Schema Deep Dive

The complete database schema is defined in src/lib/server/db/schema.ts using Drizzle ORM's SQLite table builder. Every table, column, type, constraint, and default is defined in TypeScript — giving your Svelte 5 components and SvelteKit server routes full type inference.

Auth Tables

The users, sessions, accounts, and verifications tables are owned by Better Auth. The JavaScript property names in the schema are the field names Better Auth expects, while the SQL columns stay snake_case. If you add Better Auth plugins that need extra columns, regenerate the definitions with npx @better-auth/cli generate.

Users Table

The users table stores all registered accounts with role-based access control. The first user to register gets the admin role automatically. Passwords are no longer stored here; they live in accounts.password.

export const users = sqliteTable("users", {
  id: text("id").primaryKey(),
  name: text("name").notNull(),
  email: text("email").notNull().unique(),
  emailVerified: integer("email_verified", { mode: "boolean" }).notNull().default(false),
  avatarUrl: text("avatar_url"),
  username: text("username").notNull().unique(),
  displayUsername: text("display_username"),
  role: text("role", { enum: ROLES }).notNull().default("viewer"),
  banned: integer("banned", { mode: "boolean" }).notNull().default(false),
  banReason: text("ban_reason"),
  banExpires: integer("ban_expires", { mode: "timestamp" }),
  createdAt: integer("created_at", { mode: "timestamp" }).notNull().$defaultFn(() => new Date()),
  updatedAt: integer("updated_at", { mode: "timestamp" }).notNull().$defaultFn(() => new Date()),
});
ColumnTypeConstraintsNotes
idtextPRIMARY KEYGenerated by Better Auth
nametextNOT NULLDisplay name
emailtextNOT NULL, UNIQUEStored lowercase
emailVerifiedinteger (boolean)NOT NULL, default falseDecides whether an email change needs a confirmation link
avatarUrltextnullableProfile image URL (Better Auth's image field, remapped in auth.ts)
usernametextNOT NULL, UNIQUE3-31 chars, lowercase alphanumeric + hyphens/underscores (username plugin)
displayUsernametextnullableUsername as originally typed (username plugin)
roletext enumNOT NULL, default "viewer"One of: admin, editor, viewer (admin plugin)
banned, banReason, banExpiresboolean, text, timestampbanned NOT NULL, default falseBan state managed by the admin plugin
createdAtinteger (timestamp)NOT NULLAuto-set on insert, returns Date object
updatedAtinteger (timestamp)NOT NULLAuto-set on insert, returns Date object

Sessions Table

Each row is one signed-in browser. The token is a random bearer value; the cookie carries it HMAC-signed with BETTER_AUTH_SECRET, so a leaked database alone cannot be turned into a valid session cookie. Deleting a user cascades to their sessions.

export const sessions = sqliteTable("sessions", {
  id: text("id").primaryKey(),
  token: text("token").notNull().unique(),
  userId: text("user_id")
    .notNull()
    .references(() => users.id, { onDelete: "cascade" }),
  expiresAt: integer("expires_at", { mode: "timestamp" }).notNull(),
  ipAddress: text("ip_address"),
  userAgent: text("user_agent"),
  impersonatedBy: text("impersonated_by"),
  createdAt: integer("created_at", { mode: "timestamp" }).notNull().$defaultFn(() => new Date()),
  updatedAt: integer("updated_at", { mode: "timestamp" }).notNull().$defaultFn(() => new Date()),
});
ColumnTypeConstraintsNotes
idtextPRIMARY KEYSession identifier (safe to send to the browser)
tokentextNOT NULL, UNIQUEBearer token. Never send it to the client
userIdtextNOT NULL, FK → users.id (cascade)Owner of the session
expiresAtinteger (timestamp)NOT NULL30 days from creation, slid forward when less than 15 days remain
ipAddress, userAgenttextnullableRecorded when the session is created
impersonatedBytextnullableAdmin plugin field. Unused in the free edition
createdAt, updatedAtinteger (timestamp)NOT NULLAuto-set

Pages Table

The content management system stores pages with three templates and a status workflow. The authorId foreign key links each page to its creator in the users table.

export const pages = sqliteTable("pages", {
  id: text("id").primaryKey(),
  title: text("title").notNull(),
  slug: text("slug").notNull().unique(),
  content: text("content").notNull().default(""),
  template: text("template", { enum: ["default", "landing", "blog"] })
    .notNull()
    .default("default"),
  status: text("status", { enum: ["draft", "published", "archived"] })
    .notNull()
    .default("draft"),
  authorId: text("author_id")
    .notNull()
    .references(() => users.id),
  createdAt: integer("created_at", { mode: "timestamp" })
    .notNull()
    .$defaultFn(() => new Date()),
  updatedAt: integer("updated_at", { mode: "timestamp" })
    .notNull()
    .$defaultFn(() => new Date()),
  publishedAt: integer("published_at", { mode: "timestamp" }),
});
ColumnTypeConstraintsNotes
idtextPRIMARY KEYCryptographic random ID
titletextNOT NULLPage title
slugtextNOT NULL, UNIQUEURL-friendly identifier
contenttextNOT NULL, default ""Page body content
templatetext enumNOT NULL, default "default"One of: default, landing, blog
statustext enumNOT NULL, default "draft"One of: draft, published, archived
authorIdtextNOT NULL, FK → users.idPage author
createdAtinteger (timestamp)NOT NULLAuto-set on insert
updatedAtinteger (timestamp)NOT NULLAuto-set on insert
publishedAtinteger (timestamp)nullableSet when status changes to published

Notifications Table

Notifications can be user-specific or global (when userId is null). The SvelteKit app layout queries both types for the authenticated user's notification bell.

export const notifications = sqliteTable("notifications", {
  id: text("id").primaryKey(),
  userId: text("user_id").references(() => users.id),
  title: text("title").notNull(),
  message: text("message").notNull(),
  type: text("type", { enum: ["info", "warning", "error", "success"] })
    .notNull()
    .default("info"),
  read: integer("read", { mode: "boolean" }).notNull().default(false),
  createdAt: integer("created_at", { mode: "timestamp" })
    .notNull()
    .$defaultFn(() => new Date()),
});
ColumnTypeConstraintsNotes
idtextPRIMARY KEYCryptographic random ID
userIdtextnullable, FK → users.idNull = global notification for all users
titletextNOT NULLNotification title
messagetextNOT NULLNotification body text
typetext enumNOT NULL, default "info"One of: info, warning, error, success
readinteger (boolean)NOT NULL, default falseSQLite stores booleans as 0/1 integers
createdAtinteger (timestamp)NOT NULLAuto-set on insert

Accounts Table

One row per login method for a user. Email/password users have providerId = "credential" and their Argon2id hash in password; OAuth users have providerId = "google" or "github". This table replaces both the old users.password_hash column and the oauth_accounts table. A unique index on (providerId, accountId) prevents duplicate links.

export const accounts = sqliteTable(
  "accounts",
  {
    id: text("id").primaryKey(),
    accountId: text("account_id").notNull(),
    providerId: text("provider_id").notNull(),
    userId: text("user_id")
      .notNull()
      .references(() => users.id, { onDelete: "cascade" }),
    accessToken: text("access_token"),
    refreshToken: text("refresh_token"),
    idToken: text("id_token"),
    accessTokenExpiresAt: integer("access_token_expires_at", { mode: "timestamp" }),
    refreshTokenExpiresAt: integer("refresh_token_expires_at", { mode: "timestamp" }),
    scope: text("scope"),
    password: text("password"),
    createdAt: integer("created_at", { mode: "timestamp" }).notNull().$defaultFn(() => new Date()),
    updatedAt: integer("updated_at", { mode: "timestamp" }).notNull().$defaultFn(() => new Date()),
  },
  (table) => [
    index("accounts_user_id_idx").on(table.userId),
    uniqueIndex("accounts_provider_account_idx").on(table.providerId, table.accountId),
  ]
);
ColumnTypeConstraintsNotes
providerIdtextNOT NULLcredential, google, or github
accountIdtextNOT NULLThe user ID for credential accounts; the provider's user ID for OAuth
userIdtextNOT NULL, FK → users.id (cascade)Linked user account
passwordtextnullableArgon2id hash. Only set for credential accounts
accessToken, refreshToken, idToken, scopetextnullableOAuth tokens and granted scopes, with matching *ExpiresAt timestamps

Verifications Table

Short-lived tokens for password resets, email-change confirmations, and OAuth state. This replaces the old password_reset_tokens table. Better Auth's default is to store the identifier in plain text; SvelteForge sets verification.storeIdentifier: "hashed" so only SHA-256 hashes reach the database.

export const verifications = sqliteTable(
  "verifications",
  {
    id: text("id").primaryKey(),
    identifier: text("identifier").notNull(),
    value: text("value").notNull(),
    expiresAt: integer("expires_at", { mode: "timestamp" }).notNull(),
    createdAt: integer("created_at", { mode: "timestamp" }).notNull().$defaultFn(() => new Date()),
    updatedAt: integer("updated_at", { mode: "timestamp" }).notNull().$defaultFn(() => new Date()),
  },
  (table) => [index("verifications_identifier_idx").on(table.identifier)]
);

App Settings Table

A simple key-value store for application-wide configuration. The key column is the primary key — no separate ID needed.

export const appSettings = sqliteTable("app_settings", {
  key: text("key").primaryKey(),
  value: text("value").notNull(),
  updatedAt: integer("updated_at", { mode: "timestamp" })
    .notNull()
    .$defaultFn(() => new Date()),
});
ColumnTypeConstraintsNotes
keytextPRIMARY KEYSetting name (e.g., "siteName", "maintenanceMode")
valuetextNOT NULLSetting value as string
updatedAtinteger (timestamp)NOT NULLAuto-set on insert

Timestamp Modes

Drizzle ORM's { mode: "timestamp" } option on integer columns controls how values are serialized:

  • With mode: "timestamp" — Drizzle automatically converts between JavaScript Date objects and Unix timestamps. Used for createdAt, updatedAt, and publishedAt across most tables.
  • Without mode: "timestamp" — The column stores and returns raw integers. Used for sessions.expiresAt which stores milliseconds since epoch for precise expiry comparisons without Date conversion overhead.

Type Exports

The schema file also exports inferred TypeScript types for use throughout the SvelteKit application:

export type User = typeof users.$inferSelect;
export type NewUser = typeof users.$inferInsert;
export type Session = typeof sessions.$inferSelect;
export type Page = typeof pages.$inferSelect;
export type NewPage = typeof pages.$inferInsert;
export type Notification = typeof notifications.$inferSelect;
export type Account = typeof accounts.$inferSelect;
export type Verification = typeof verifications.$inferSelect;
export type AppSetting = typeof appSettings.$inferSelect;

ID Generation

Application rows (pages, notifications, seed data) get IDs from generateId() in src/lib/server/id.ts. The auth tables use Better Auth's own ID generator.

// src/lib/server/id.ts
import { randomBytes } from "node:crypto";

export function generateId(length: number = 15): string {
  const bytes = randomBytes(length);
  // ... encode as lowercase base32 without padding ...
}
  • Cryptographically secure — Uses node:crypto's randomBytes().
  • Base32 encoded — Lowercase, no padding. URL-safe and case-insensitive. The encoder is a small built-in function, so no encoding package is needed.
  • Default length: 15 bytes — Produces a 24-character string with 120 bits of entropy. The seed script uses generateId(10) for shorter IDs.

Migrations & Schema Changes

SvelteForge Admin uses Drizzle Kit for database migrations. The configuration lives in drizzle.config.ts:

// drizzle.config.ts
import { defineConfig } from "drizzle-kit";

export default defineConfig({
  schema: "./src/lib/server/db/schema.ts",
  out: "./drizzle",
  dialect: "sqlite",
  dbCredentials: {
    url: "svelteforge.db",
  },
});

Available Commands

CommandPurpose
pnpm db:pushPush schema changes directly to the database (development)
pnpm db:generateGenerate SQL migration files in the ./drizzle directory
pnpm db:studioOpen Drizzle Studio GUI in your browser to inspect/edit data
pnpm db:seedSeed the database with sample data

Upgrading a v1.x database? Run pnpm db:migrate-v2 before pnpm db:push; see Upgrading.

Step-by-Step: Changing the Schema

  1. Edit the schema — Modify src/lib/server/db/schema.ts (add columns, tables, constraints).
  2. Push changes — Run pnpm db:push to apply changes directly to your local SQLite database.
  3. Update test utilities — If you have tests, update the SCHEMA_SQL constant in test-utils.ts to match the new schema. Tests use an in-memory SQLite database that is created from this SQL string.
  4. Generate migrations (optional) — For production deployments, run pnpm db:generate to create versioned SQL migration files.

Database Seeding

The seed script at src/lib/server/db/seed.ts populates the database with realistic sample data. Run it with:

pnpm db:seed

What Gets Created

EntityCountDetails
Users50Realistic 12-month growth curve (2 users/month early, 7 users/month recent). Mix of admin, editor, and viewer roles.
Pages65Across all templates (default, landing, blog) and statuses. Earlier months mostly published, recent months more drafts.
Notifications33Mix of info, warning, error, and success types. Older ones marked as read, recent ones unread.
App Settings4siteName, timezone, defaultRole, maintenanceMode

Key Details

  • All passwords: password123 — Stored as credential accounts in accounts.password, hashed with Argon2id (memoryCost: 19456, timeCost: 2, outputLen: 32, parallelism: 1).
  • Login with: username admin (email [email protected]) / password123, or any seeded user with password123.
  • Realistic timestamps: Uses a daysAgo() helper to create dates spread across the past 12 months.
  • Runs outside SvelteKit: The seed script is executed via the locally installed tsx, not through SvelteKit's Vite server. This means it uses relative imports (./index.js, ../id.js) instead of #lib/ aliases.

Drizzle Studio

Drizzle Studio provides a browser-based GUI for inspecting and editing your SQLite database. Launch it with:

pnpm db:studio

This opens a visual interface where you can browse tables, run queries, edit rows, and inspect relationships — useful during development of your Svelte 5 components and SvelteKit server routes.

Querying Patterns

Here are common Drizzle ORM query patterns used throughout the SvelteKit server routes in SvelteForge Admin.

Select All Records

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

// Select specific columns
const allUsers = await db
  .select({
    id: users.id,
    name: users.name,
    email: users.email,
    role: users.role,
    createdAt: users.createdAt,
  })
  .from(users)
  .orderBy(users.createdAt);

Find One Record

import { eq } from "drizzle-orm";

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

Insert a Record

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

await db.insert(users).values({
  id: generateId(10),
  email: "[email protected]",
  username: "newuser",
  name: "New User",
  role: "viewer",
});

// Don't insert users for sign-in yourself: use auth.api.signUpEmail() or
// auth.api.createUser() so Better Auth also creates the credential account.

Update a Record

import { eq } from "drizzle-orm";

await db
  .update(users)
  .set({ role: "editor", updatedAt: new Date() })
  .where(eq(users.id, userId));

Delete Records

import { eq } from "drizzle-orm";

await db.delete(users).where(eq(users.id, userId));

Aggregation with SQL

import { sql, eq, and, or, isNull } from "drizzle-orm";

// Count unread notifications for a user (including global ones)
const [result] = await db
  .select({ count: sql<number>`count(*)` })
  .from(notifications)
  .where(
    and(
      eq(notifications.read, false),
      or(
        eq(notifications.userId, userId),
        isNull(notifications.userId)
      )
    )
  );

Pattern Matching (LIKE)

import { sql, or } from "drizzle-orm";

const pattern = `%${searchQuery}%`;
const results = await db
  .select({ id: users.id, name: users.name })
  .from(users)
  .where(or(
    sql`${users.name} LIKE ${pattern}`,
    sql`${users.email} LIKE ${pattern}`
  ))
  .limit(10);

Need More?

Go Premium with DashboardPack

SvelteForge Admin demonstrates a solid SQLite + Drizzle ORM setup for Svelte 5 and SvelteKit. Need more advanced database patterns? DashboardPack premium templates include multi-tenant schemas, advanced CRUD interfaces with pagination/filtering/sorting, data import/export, and production-grade database management UIs.

  • Apex (Svelte) — SvelteKit admin with 6 dashboards, advanced data tables, and full CRUD operations
  • Zenith — Analytics dashboard with complex aggregation queries and real-time data
  • Signal — Monitoring dashboard with database health metrics and query performance tracking