Skip to content

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
└── .dockerignore

Creating the Dockerfile

Create a Dockerfile in the root of your repository:

FROM trailbase/trailbase:latest
# Set environment variables
ENV TRAILBASE_DATA_DIR=/data
ENV TRAILBASE_SECRET_KEY=${SECRET_KEY}
ENV TRAILBASE_PUBLIC_URL=${PUBLIC_URL}
# Create data directory
RUN mkdir -p /data
# Copy configuration if needed
COPY config/ /config/
# Expose the web interface port
EXPOSE 4000
# Health check
HEALTHCHECK --interval=30s --timeout=10s --start-period=30s --retries=3 \
CMD curl -f http://localhost:4000/health || exit 1

Configuration File

Create config/trailbase.toml for your TrailBase configuration:

[server]
host = "0.0.0.0"
port = 4000
[database]
path = "/data/trailbase.db"
[auth]
enabled = true
session_lifetime = "7d"
allow_signup = true
[admin]
enabled = true

Environment Variables Reference

VariableRequiredDefaultDescription
SECRET_KEYYes-Secret key for session encryption and tokens. Generate with openssl rand -hex 32
PUBLIC_URLYes-Public URL where TrailBase is accessible (e.g., https://app.klutch.sh)
ADMIN_EMAILNo-Email for the initial admin user
ADMIN_PASSWORDNo-Password for the initial admin user
SMTP_HOSTNo-SMTP server for email sending
SMTP_PORTNo587SMTP port
SMTP_USERNo-SMTP username
SMTP_PASSWORDNo-SMTP password

Deploying TrailBase on Klutch.sh

Once your repository is prepared, follow these steps to deploy TrailBase:

    Generate Your SECRET_KEY

    Before deployment, generate a secure secret key:

    Terminal window
    openssl rand -hex 32

    Save this key securely for the environment variables configuration.

    Push Your Repository to GitHub

    Initialize your repository and push to GitHub:

    Terminal window
    git init
    git add Dockerfile config/ .dockerignore
    git commit -m "Initial TrailBase deployment configuration"
    git remote add origin https://github.com/yourusername/trailbase-deploy.git
    git push -u origin main

    Create 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:

    • Select HTTP as the traffic type
    • Set the internal port to 4000 (TrailBase default port)

    Set Environment Variables

    In the environment variables section, add the following:

    VariableValue
    SECRET_KEYYour generated hex key from step 1
    PUBLIC_URLhttps://your-app-name.klutch.sh
    ADMIN_EMAILadmin@example.com
    ADMIN_PASSWORDA secure admin password

    Attach Persistent Volumes

    Persistent storage is essential for TrailBase. Add the following volumes:

    Mount PathRecommended SizePurpose
    /data5 GBSQLite database, file uploads, and application state

    Deploy Your Application

    Click Deploy to start the build process. Klutch.sh will:

    • Detect your Dockerfile automatically
    • Build the container image
    • Attach the persistent volumes
    • Start the TrailBase container
    • Provision an HTTPS certificate

    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:

  1. Go to Schema in the admin menu
  2. Click New Table
  3. Define your table columns with appropriate types
  4. Set primary keys and relationships
  5. Configure row-level security policies

API Access

TrailBase automatically generates REST endpoints for your tables:

  • GET /api/v1/tables/{table} - List records
  • GET /api/v1/tables/{table}/{id} - Get single record
  • POST /api/v1/tables/{table} - Create record
  • PUT /api/v1/tables/{table}/{id} - Update record
  • DELETE /api/v1/tables/{table}/{id} - Delete record

Authentication Setup

Email/Password Authentication

TrailBase includes built-in email/password authentication:

  1. Enable signup in your configuration
  2. Users register at /auth/signup
  3. Users login at /auth/login
  4. Sessions are managed automatically with secure cookies

OAuth Providers

Configure social login with OAuth providers:

  1. Register your application with the OAuth provider
  2. Add credentials to your environment variables
  3. Configure callback URLs to match your PUBLIC_URL
  4. Enable the provider in your TrailBase configuration

Supported providers include:

  • Google
  • GitHub
  • Discord
  • And more

Enable passwordless login with email magic links:

  1. Configure SMTP settings for email sending
  2. Enable magic links in authentication settings
  3. Users receive login links via email

Row-Level Security

Defining Policies

Control data access at the row level:

-- Users can only see their own data
CREATE POLICY user_isolation ON my_table
FOR ALL
USING (user_id = auth.uid());
-- Public read, authenticated write
CREATE 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:

  1. Database Backups: Regularly copy the SQLite database from /data
  2. Export Data: Use the API to export critical data
  3. 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 /data volume is properly mounted
  • Check file permissions on the data directory
  • Review database migration status

Additional Resources

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.