Deploying TrailBase
Introduction
TrailBase is a blazingly fast, single-file, open-source application server built with Rust. It combines a SQLite database, REST API framework, authentication system, and admin dashboard into one lightweight binary, making it perfect for building modern web applications without managing multiple services.
Inspired by solutions like Firebase and Supabase, TrailBase provides a complete backend in a single executable. It features automatic CRUD API generation, built-in user authentication with email/password and OAuth, real-time subscriptions, and a powerful admin interface for managing your data.
Key highlights of TrailBase:
- Single Binary: Everything you need in one lightweight executable with no external dependencies
- SQLite-Powered: Fast, reliable, and serverless database with full SQL support
- Automatic REST APIs: Generate CRUD endpoints from your database schema automatically
- Built-in Authentication: Email/password, magic links, and OAuth providers out of the box
- Admin Dashboard: Web-based interface for managing users, data, and configuration
- Real-Time Subscriptions: WebSocket-based real-time data updates
- Type-Safe Client: Auto-generated TypeScript client for frontend development
- File Storage: Built-in file upload and storage capabilities
- Row-Level Security: Fine-grained access control at the database level
- Open Source: Licensed under OSL-3.0 for transparency and customization
This guide walks through deploying TrailBase on Klutch.sh using Docker, configuring authentication, and setting up your application backend.
Why Deploy TrailBase on Klutch.sh
Deploying TrailBase on Klutch.sh provides several advantages for application development:
Simplified Deployment: Klutch.sh automatically detects your Dockerfile and builds TrailBase without complex orchestration. Push to GitHub, and your backend deploys automatically.
Persistent Storage: Attach persistent volumes for your SQLite database and file uploads. Your data survives container restarts and redeployments.
HTTPS by Default: Klutch.sh provides automatic SSL certificates, ensuring secure API access and OAuth callbacks work correctly.
GitHub Integration: Connect your configuration repository directly from GitHub. Updates trigger automatic redeployments.
Environment Variable Management: Securely store sensitive configuration like secret keys and OAuth credentials through Klutch.sh’s environment variable system.
Low Resource Usage: TrailBase’s efficient Rust implementation means you get excellent performance without large resource allocations.
Prerequisites
Before deploying TrailBase on Klutch.sh, ensure you have:
- A Klutch.sh account
- A GitHub account with a repository for your TrailBase configuration
- Basic familiarity with Docker and REST API concepts
- (Optional) OAuth provider credentials for social login
- (Optional) A custom domain for your TrailBase instance
Understanding TrailBase Architecture
TrailBase is built on several core components:
Rust Core: The application server is written in Rust for maximum performance and memory safety.
SQLite Database: All data is stored in a SQLite database file, providing reliability without external database services.
REST API Layer: Automatic CRUD endpoints are generated from your database schema with full filtering and pagination.
Authentication System: Built-in user management with sessions, tokens, and multiple authentication methods.
Admin Dashboard: A web interface for managing database tables, users, and application settings.
WebSocket Server: Real-time data synchronization for reactive applications.
Preparing Your Repository
To deploy TrailBase on Klutch.sh, create a GitHub repository containing your Dockerfile and configuration.
Repository Structure
trailbase-deploy/├── Dockerfile├── config/│ └── trailbase.toml└── .dockerignoreCreating the Dockerfile
Create a Dockerfile in the root of your repository:
FROM trailbase/trailbase:latest
# Set environment variablesENV TRAILBASE_DATA_DIR=/dataENV TRAILBASE_SECRET_KEY=${SECRET_KEY}ENV TRAILBASE_PUBLIC_URL=${PUBLIC_URL}
# Create data directoryRUN mkdir -p /data
# Copy configuration if neededCOPY config/ /config/
# Expose the web interface portEXPOSE 4000
# Health checkHEALTHCHECK --interval=30s --timeout=10s --start-period=30s --retries=3 \ CMD curl -f http://localhost:4000/health || exit 1Configuration File
Create config/trailbase.toml for your TrailBase configuration:
[server]host = "0.0.0.0"port = 4000
[database]path = "/data/trailbase.db"
[auth]enabled = truesession_lifetime = "7d"allow_signup = true
[admin]enabled = trueEnvironment Variables Reference
| Variable | Required | Default | Description |
|---|---|---|---|
SECRET_KEY | Yes | - | Secret key for session encryption and tokens. Generate with openssl rand -hex 32 |
PUBLIC_URL | Yes | - | Public URL where TrailBase is accessible (e.g., https://app.klutch.sh) |
ADMIN_EMAIL | No | - | Email for the initial admin user |
ADMIN_PASSWORD | No | - | Password for the initial admin user |
SMTP_HOST | No | - | SMTP server for email sending |
SMTP_PORT | No | 587 | SMTP port |
SMTP_USER | No | - | SMTP username |
SMTP_PASSWORD | No | - | SMTP password |
Deploying TrailBase on Klutch.sh
Once your repository is prepared, follow these steps to deploy TrailBase:
- Select HTTP as the traffic type
- Set the internal port to 4000 (TrailBase default port)
- Detect your Dockerfile automatically
- Build the container image
- Attach the persistent volumes
- Start the TrailBase container
- Provision an HTTPS certificate
Generate Your SECRET_KEY
Before deployment, generate a secure secret key:
openssl rand -hex 32Save this key securely for the environment variables configuration.
Push Your Repository to GitHub
Initialize your repository and push to GitHub:
git initgit add Dockerfile config/ .dockerignoregit commit -m "Initial TrailBase deployment configuration"git remote add origin https://github.com/yourusername/trailbase-deploy.gitgit push -u origin mainCreate a New Project on Klutch.sh
Navigate to the Klutch.sh dashboard and create a new project. Give it a descriptive name like “trailbase” or “app-backend”.
Create a New App
Within your project, create a new app. Connect your GitHub account if you haven’t already, then select the repository containing your TrailBase Dockerfile.
Configure HTTP Traffic
In the deployment settings:
Set Environment Variables
In the environment variables section, add the following:
| Variable | Value |
|---|---|
SECRET_KEY | Your generated hex key from step 1 |
PUBLIC_URL | https://your-app-name.klutch.sh |
ADMIN_EMAIL | admin@example.com |
ADMIN_PASSWORD | A secure admin password |
Attach Persistent Volumes
Persistent storage is essential for TrailBase. Add the following volumes:
| Mount Path | Recommended Size | Purpose |
|---|---|---|
/data | 5 GB | SQLite database, file uploads, and application state |
Deploy Your Application
Click Deploy to start the build process. Klutch.sh will:
Access TrailBase
Once deployment completes, access your TrailBase instance at https://your-app-name.klutch.sh. Navigate to /admin to access the admin dashboard.
Initial Setup and Configuration
Accessing the Admin Dashboard
Navigate to https://your-app-name.klutch.sh/admin and log in with the admin credentials you configured.
Creating Database Tables
Use the admin interface to create your application’s data model:
- Go to Schema in the admin menu
- Click New Table
- Define your table columns with appropriate types
- Set primary keys and relationships
- Configure row-level security policies
API Access
TrailBase automatically generates REST endpoints for your tables:
GET /api/v1/tables/{table}- List recordsGET /api/v1/tables/{table}/{id}- Get single recordPOST /api/v1/tables/{table}- Create recordPUT /api/v1/tables/{table}/{id}- Update recordDELETE /api/v1/tables/{table}/{id}- Delete record
Authentication Setup
Email/Password Authentication
TrailBase includes built-in email/password authentication:
- Enable signup in your configuration
- Users register at
/auth/signup - Users login at
/auth/login - Sessions are managed automatically with secure cookies
OAuth Providers
Configure social login with OAuth providers:
- Register your application with the OAuth provider
- Add credentials to your environment variables
- Configure callback URLs to match your PUBLIC_URL
- Enable the provider in your TrailBase configuration
Supported providers include:
- GitHub
- Discord
- And more
Magic Links
Enable passwordless login with email magic links:
- Configure SMTP settings for email sending
- Enable magic links in authentication settings
- Users receive login links via email
Row-Level Security
Defining Policies
Control data access at the row level:
-- Users can only see their own dataCREATE POLICY user_isolation ON my_table FOR ALL USING (user_id = auth.uid());
-- Public read, authenticated writeCREATE POLICY public_read ON posts FOR SELECT USING (true);
CREATE POLICY auth_write ON posts FOR INSERT USING (auth.uid() IS NOT NULL);Policy Examples
Common security patterns:
- User Isolation: Users only access their own records
- Role-Based Access: Different permissions for different user roles
- Public Read: Anyone can read, only authenticated users can write
- Team Access: Users access records belonging to their team
Real-Time Features
WebSocket Subscriptions
Subscribe to data changes in real-time:
const ws = new WebSocket('wss://your-app.klutch.sh/realtime');
ws.send(JSON.stringify({ type: 'subscribe', table: 'messages', filter: { room_id: 1 }}));
ws.onmessage = (event) => { const change = JSON.parse(event.data); console.log('Data changed:', change);};Use Cases
Real-time features are perfect for:
- Chat applications
- Collaborative editing
- Live dashboards
- Notification systems
File Storage
Uploading Files
TrailBase includes built-in file storage:
const formData = new FormData();formData.append('file', fileInput.files[0]);
const response = await fetch('/api/v1/storage/upload', { method: 'POST', body: formData});Serving Files
Files are served at predictable URLs:
https://your-app.klutch.sh/storage/{bucket}/{filename}Production Best Practices
Security Recommendations
- Strong Secret Key: Use a properly generated SECRET_KEY
- Secure Admin Access: Use strong admin credentials
- Row-Level Security: Always implement appropriate RLS policies
- HTTPS Only: Klutch.sh provides this automatically
Backup Strategy
Protect your application data:
- Database Backups: Regularly copy the SQLite database from
/data - Export Data: Use the API to export critical data
- File Backups: Back up uploaded files from storage
Performance Optimization
- Indexes: Create database indexes for frequently queried columns
- Pagination: Use pagination for large result sets
- Caching: Leverage HTTP caching headers for static content
Troubleshooting Common Issues
Application Won’t Start
Symptoms: Container exits or fails health checks.
Solutions:
- Verify SECRET_KEY is set correctly
- Check that all volumes are mounted with proper permissions
- Review startup logs for specific errors
Authentication Issues
Symptoms: Cannot log in or OAuth not working.
Solutions:
- Verify PUBLIC_URL matches your actual deployment URL
- Check OAuth callback URLs are configured correctly
- Review authentication logs for errors
Database Errors
Symptoms: API requests failing with database errors.
Solutions:
- Verify the
/datavolume is properly mounted - Check file permissions on the data directory
- Review database migration status
Additional Resources
- TrailBase Official Website
- TrailBase Documentation
- TrailBase GitHub Repository
- Klutch.sh Persistent Volumes
- Klutch.sh Deployments
Conclusion
Deploying TrailBase on Klutch.sh gives you a complete, modern application backend in a single lightweight service. The combination of TrailBase’s all-in-one architecture and Klutch.sh’s deployment simplicity means you can build full-stack applications without managing complex infrastructure.
With built-in authentication, automatic REST APIs, real-time features, and file storage, TrailBase provides everything you need to power modern web and mobile applications. Its SQLite foundation ensures reliability while maintaining the simplicity of a single-file deployment.