Svelar Documentation
Introduction
Svelar is a Laravel-inspired framework built on top of SvelteKit 2. It brings enterprise-grade patterns like MVC, ORM, middleware pipelines, session management, and authentication to the SvelteKit ecosystem. Svelar provides a complete backend framework with a familiar developer experience for anyone coming from Laravel.
Key Features
- UI Components: Minimal, composable Svelte 5 component library (Button, Card, Input, Alert, Badge, Avatar, etc.) themed via Tailwind CSS v4
@themetokens - ORM with Relationships: Eloquent-like query builder with eager loading, relationships (hasOne, hasMany, belongsTo, belongsToMany)
- Database Migrations & Seeders: Version-controlled schema management and seed data
- Authentication: Session-based auth, JWT support, and API tokens
- Middleware Pipeline: Global and controller-level middleware with built-in CSRF, rate limiting, logging, and CORS
- i18n: Paraglide-js 2.x integration with server middleware, reroute hooks, and LanguageSwitcher component
- Forms: Superforms + Zod bridge with
createFormActionandloadFormhelpers - HTTP Utilities: CSRF-aware fetch wrapper for client-side API calls
- Form Validation: Zod-based validation with FormRequest classes (DTOs)
- Service Layer & Actions: Clean separation of concerns with services, repositories, and single-use actions
- Plugin System: Extensible plugin architecture with lifecycle hooks
- Job Queue: Background job processing with retry logic
- Scheduler: Cron-like task scheduling
- Session Management: Cookie-based sessions with memory and database stores
- Hashing: Multiple hashing drivers (scrypt, bcrypt, argon2)
- Events & Listeners: Pub/sub event system
- Storage: File storage abstraction layer
- Logging & Caching: Built-in logging and caching drivers
- Full-Text Search: Meilisearch integration with auto-syncing
Searchablemixin
Table of Contents
- Getting Started - Start here — what you get, step-by-step setup, your first 10 minutes
- Installation - CLI commands, manual setup, Docker deployment
- Database - Migrations, seeders, and database configuration
- Models & ORM - Eloquent-like ORM with relationships
- Controllers & Routing - Request handling, resources, response objects
- Validation & DTOs - Form validation with Zod, contract schemas
- Authentication - Session, JWT, refresh tokens, API tokens, request signatures
- Middleware - CORS, CSRF, rate limiting, origin validation, signatures
- Services, Actions & Repositories - Business logic layers
- Plugins - Extend Svelar with custom plugins
- Scheduler - Schedule periodic tasks
- Job Queue - Background job processing
- Sessions - Session stores (database, file, Redis, memory)
- Events & Listeners - Pub/sub event system with typed listeners
- Mail - SMTP, Postmark, Resend drivers with Mailable classes
- Broadcasting - Real-time SSE and Pusher/Soketi WebSocket
- Storage - Local and S3-compatible file storage
- PDF Generation - PDFKit (default) and Gotenberg drivers
- Excel Import/Export - Streaming Excel with ExcelJS
- Feature Flags - Per-user, per-team, and percentage rollout
- More Features - Hashing, caching, logging, notifications, config, CLI, audit, and more
- UI Components - Component library with theming and extension guide
- HTTP & Integrations - Server-side HTTP client, third-party API patterns, custom drivers
- Internationalization - Paraglide-js integration for multi-language apps
- Forms - Superforms + Zod bridge for validated form actions
- Dates - Date utilities and formatting
- Error Handling - Error pages, localization, exception handling
- Architecture & Module Communication - DDD boundaries, events as glue, anti-patterns
- SaaS Guide - Multi-tenancy, production checklist, scaling
- Deployment - Docker, Traefik, blue-green, Swarm, CI/CD, monitoring
- Security - Authentication, CSRF, rate limiting, Docker hardening, production checklist
- Full-Text Search - Meilisearch integration with Searchable mixin, auto-sync, bulk indexing
- Stripe Billing - Subscriptions, checkout, invoices, refunds, webhooks, customer portal
Quick Start
npx svelar new my-app
cd my-app
npm run dev
The new command installs dependencies, generates .env with secure random secrets, runs migrations, and seeds the database. Your app is ready at http://localhost:5173 with auth, dashboard, admin panel, teams, API keys, and more — all working out of the box.
New to Svelar? Read the Getting Started guide for a complete walkthrough of what you get and how to set everything up.
Project Structure (DDD Modular Monolith)
my-app/
├── src/
│ ├── app.ts # Bootstrap (database, hashing, providers)
│ ├── app.css # Tailwind CSS v4 + @theme tokens
│ ├── app.html # HTML template
│ ├── hooks.server.ts # Middleware pipeline (createSvelarApp)
│ ├── lib/
│ │ ├── modules/ # Domain modules (DDD)
│ │ │ ├── auth/ # User.ts, UserObserver.ts, AuthController.ts, AuthService.ts
│ │ │ ├── billing/ # Invoice.ts, BillingService.ts
│ │ │ └── posts/ # Post.ts, PostController.ts, PostRepository.ts
│ │ ├── shared/ # Cross-cutting concerns
│ │ │ ├── middleware/ # Custom middleware
│ │ │ ├── components/ # Shared Svelte components
│ │ │ ├── stores/ # Svelte stores
│ │ │ ├── jobs/ # Background queue jobs
│ │ │ ├── plugins/ # Custom plugins
│ │ │ ├── channels/ # Broadcast channel authorization
│ │ │ ├── commands/ # Custom CLI commands
│ │ │ ├── providers/ # Service providers (EventServiceProvider, etc.)
│ │ │ └── scheduler/ # Scheduled tasks
│ │ ├── events/ # Event classes (npx svelar make:event)
│ │ ├── listeners/ # Listener classes (npx svelar make:listener)
│ │ └── database/
│ │ ├── migrations/ # Database schema changes
│ │ └── seeders/ # Seed data
│ └── routes/ # SvelteKit routes
│ ├── +layout.svelte
│ ├── +page.svelte
│ ├── api/
│ ├── dashboard/
│ └── admin/
├── storage/
│ ├── logs/ # Application logs
│ ├── cache/ # File-based cache
│ ├── uploads/ # User uploads
│ └── sessions/ # File-based sessions
├── package.json
├── svelte.config.js
├── svelar.database.json
├── .env.example
└── vite.config.ts
Each module under modules/ is a self-contained domain — model, controller, service, repository, observers, DTOs, and schema all live together. The shared/ folder holds cross-cutting infrastructure that spans multiple domains.
Architecture
Svelar follows a hybrid Domain-Driven Design (DDD) architecture that cleanly separates concerns:
Request
↓
Route (+server.ts)
↓
Controller (handle request, delegate)
↓
DTO/FormRequest (validation & authorization)
↓
Service (orchestrate business logic)
↓
Action (single use-case execution)
↓
Repository (data access abstraction)
↓
Model (ORM, database interaction)
Layer Responsibilities
Controllers: Accept HTTP requests and delegate to services/actions. Handle response formatting (JSON, HTML, redirects).
DTOs/FormRequest: Validate incoming data with Zod schemas. Authorize requests before processing. Transform data if needed.
Services: Orchestrate multiple operations, compose repositories, emit events. Return ServiceResult<T> (ok/fail).
Actions: Execute single, well-defined use cases. Encapsulate business logic. Support middleware pipelines and hooks.
Repositories: Provide data access methods. Abstract the Model layer. Cache queries when needed.
Models: Map database tables to objects. Define relationships. Support eager loading and casting.
Module Communication
Modules never import each other directly. Cross-module communication goes through the event system:
Auth Module ──► Event: UserRegistered ──► Billing Module (CreateFreePlan)
──► Notifications Module (SendWelcomeEmail)
All event-to-listener mappings and model observers are registered in the EventServiceProvider, giving you a single place to see how your modules interact.
See Architecture & Module Communication for the full guide, including patterns, anti-patterns, shared contracts, and testing strategies.
Configuration
Svelar configuration happens in src/app.ts:
// src/app.ts
import { Connection } from '@beeblock/svelar/database';
import { Hash } from '@beeblock/svelar/hashing';
import { AuthManager } from '@beeblock/svelar/auth';
import { User } from './lib/models/User.js';
// Database
Connection.configure({
default: 'sqlite',
connections: {
sqlite: {
driver: 'sqlite',
filename: process.env.DB_PATH ?? 'database.db',
},
},
});
// Hashing
Hash.configure({
driver: 'scrypt', // or 'bcrypt', 'argon2'
});
// Auth
export const auth = new AuthManager({
guard: 'session', // or 'jwt', 'api'
model: User,
});
export { Connection, Hash };
Middleware Pipeline
The simplest way to set up the middleware pipeline is createSvelarApp, which auto-wires origin validation, rate limiting, CSRF, sessions, auth, error handling, and optionally i18n:
// src/hooks.server.ts
import { createSvelarApp } from '@beeblock/svelar/hooks';
import { paraglideMiddleware } from '$lib/paraglide/server';
import { getTextDirection } from '$lib/paraglide/runtime';
import { auth } from './app.js';
export const { handle, handleError } = createSvelarApp({
auth,
i18n: { paraglideMiddleware, getTextDirection },
});
For full control, use createSvelarHooks to compose the pipeline manually:
import { createSvelarHooks } from '@beeblock/svelar/hooks';
import { SessionMiddleware, DatabaseSessionStore } from '@beeblock/svelar/session';
import { AuthenticateMiddleware } from '@beeblock/svelar/auth';
import { RateLimitMiddleware, CsrfMiddleware, OriginMiddleware } from '@beeblock/svelar/middleware';
import { auth } from './app.js';
export const handle = createSvelarHooks({
middleware: [
new OriginMiddleware(),
new RateLimitMiddleware({ maxRequests: 100, windowMs: 60_000 }),
new CsrfMiddleware({ onlyPaths: ['/api/'] }),
new SessionMiddleware({
store: new DatabaseSessionStore(), // auto-creates sessions table
secret: process.env.APP_KEY!,
lifetime: 60 * 60 * 24,
}),
new AuthenticateMiddleware(auth),
],
onError: (error, event) => {
console.error('[Svelar Error]', error);
},
});
Environment Variables
Create a .env file in your project root:
# Database
DB_PATH=database.db
# App
APP_KEY=your-secret-key-for-sessions
# Auth
JWT_SECRET=your-jwt-secret-key
# Mail (optional)
MAIL_DRIVER=log
MAIL_FROM=hello@example.com
# Storage (optional)
STORAGE_DISK=local
Next Steps
- Start here: Getting Started — what you get, setup steps, first 10 minutes
- Installation — CLI commands, Docker deployment, manual setup
- Models & ORM — define your domain models
- Controllers & Routing — build your API
- Authentication — JWT, refresh tokens, API tokens, request signatures
- Architecture — DDD module boundaries and patterns
Getting Help
- Review the documentation for detailed guides
- Scaffold a new project with
npx svelar new my-appto explore working examples - Open an issue on GitHub for bugs or feature requests
Svelar Documentation © 2026. Built with ❤️ for the SvelteKit community.