> ## Documentation Index
> Fetch the complete documentation index at: https://mintlify.com/trailbaseio/trailbase/llms.txt
> Use this file to discover all available pages before exploring further.

# CLI Usage

> Common TrailBase CLI commands and workflows

The `trail` CLI provides commands for managing your TrailBase server, users, migrations, and more.

## Installation

The `trail` binary is included in TrailBase releases:

```bash theme={null}
# Download from GitHub releases
curl -L https://github.com/trailbaseio/trailbase/releases/latest/download/trailbase-linux-x86_64.tar.gz | tar xz

# Make executable
chmod +x trail

# Move to PATH (optional)
sudo mv trail /usr/local/bin/
```

## Global Options

These options work with all commands:

```bash theme={null}
# Specify data directory (default: ./traildepot)
trail --data-dir /var/lib/trailbase run

# Set public URL for OAuth and emails
trail --public-url https://example.com run

# Show version
trail --version
```

## Server Commands

### Start Server

Start the HTTP server:

```bash theme={null}
# Start with defaults (localhost:4000)
trail run

# Custom address
trail run --address 0.0.0.0:8080

# Separate admin interface
trail run --admin-address localhost:4001

# Serve static files
trail run --public-dir ./web/dist

# Enable SPA fallback (serve index.html for routes)
trail run --public-dir ./web/dist --spa

# Development mode (permissive CORS)
trail run --dev

# Custom number of WASM workers
trail run --runtime-threads 8
```

<Info>
  **First Run:** On first startup, TrailBase creates admin credentials and displays them in the terminal. Save these to access the admin UI at `http://localhost:4000/_/admin`.
</Info>

### Server Options

| Option                   | Description                        | Default             |
| ------------------------ | ---------------------------------- | ------------------- |
| `--address`              | Server bind address                | `localhost:4000`    |
| `--admin-address`        | Separate admin interface address   | Same as `--address` |
| `--public-dir`           | Static file directory              | None                |
| `--spa`                  | Enable SPA fallback                | `false`             |
| `--runtime-root-fs`      | WASM sandboxed filesystem root     | None                |
| `--geoip-db-path`        | MaxMind GeoIP database path        | None                |
| `--dev`                  | Development mode (permissive CORS) | `false`             |
| `--demo`                 | Redact PII from logs               | `false`             |
| `--cors-allowed-origins` | Allowed CORS origins               | `*`                 |
| `--runtime-threads`      | Number of WASM isolates            | CPU count           |
| `--stderr-logging`       | Log to stderr instead of files     | `false`             |

## Migration Commands

### Create Migration

Generate a new migration file:

```bash theme={null}
# Create migration for main database
trail migration create_table_posts

# Output:
# Created: traildepot/migrations/main/U1234567890__create_table_posts.sql

# Create migration for attached database
trail migration add_analytics_table --db analytics
```

The generated file is ready to edit:

```sql traildepot/migrations/main/U1234567890__create_table_posts.sql theme={null}
-- Add your SQL statements here
CREATE TABLE posts (
  id INTEGER PRIMARY KEY,
  title TEXT NOT NULL
) STRICT;
```

<Tip>
  Migrations run automatically when TrailBase starts. No separate apply command is needed.
</Tip>

### View Applied Migrations

Check which migrations have been applied:

```bash theme={null}
# Using SQLite directly
sqlite3 traildepot/data/main.db "SELECT * FROM _schema_history ORDER BY version;"
```

## User Management

### Create User

Add a new verified user:

```bash theme={null}
trail user add user@example.com SecurePassword123
```

<Note>
  Users created via CLI are automatically verified and can log in immediately.
</Note>

### Change Password

```bash theme={null}
trail user change-password user@example.com NewPassword123
```

### Change Email

```bash theme={null}
trail user change-email old@example.com new@example.com
```

### Verify Email

Manually verify a user's email:

```bash theme={null}
# Verify user
trail user verify user@example.com true

# Unverify user
trail user verify user@example.com false
```

### Delete User

```bash theme={null}
trail user delete user@example.com
```

<Warning>
  Deleting a user cascades to all records with foreign keys to `_user.id`. This cannot be undone.
</Warning>

### Invalidate Session

Force a user to re-login:

```bash theme={null}
trail user invalidate-session user@example.com
```

This increments the user's session version, making existing auth tokens invalid.

### Mint Auth Token

Generate an auth token for a user (useful for automation):

```bash theme={null}
trail user mint-token user@example.com

# Output:
eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9...
```

Use the token for API requests:

```bash theme={null}
curl -H "Authorization: Bearer eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9..." \
  http://localhost:4000/api/records/todos
```

### Import Users

Import users from Auth0 or other providers:

```bash theme={null}
# Dry run (validate without importing)
trail user import --dry-run --auth0-json users.ndjson

# Actually import
trail user import --auth0-json users.ndjson
```

## Admin Management

### List Admins

```bash theme={null}
trail admin list

# Output:
admin@localhost
super@example.com
```

### Promote User to Admin

```bash theme={null}
trail admin promote user@example.com
```

### Demote Admin to User

```bash theme={null}
trail admin demote admin@example.com
```

<Info>
  You cannot demote yourself. Use another admin account or direct database access.
</Info>

## Schema Commands

### Export JSON Schema

Generate JSON Schema for a table:

```bash theme={null}
# Generate schema for SELECT operations
trail schema todos

# Generate schema for INSERT operations
trail schema todos --mode insert

# Generate schema for UPDATE operations
trail schema todos --mode update
```

Output:

```json theme={null}
{
  "title": "todos",
  "type": "object",
  "properties": {
    "id": { "type": "integer" },
    "text": { "type": "string" },
    "completed": { "type": "integer" }
  },
  "required": ["id", "text", "completed"]
}
```

<Tip>
  Pipe to a file for code generation:

  ```bash theme={null}
  trail schema todos > schema/todos.json
  npx json-schema-to-typescript schema/todos.json > src/types/todos.ts
  ```
</Tip>

### Export OpenAPI Spec

Generate OpenAPI specification:

```bash theme={null}
# Print to stdout
trail openapi print

# Save to file
trail openapi print > openapi.yaml

# Run Swagger UI (requires swagger feature)
trail openapi run
# Opens http://localhost:4004
```

## Email Commands

Send emails programmatically:

```bash theme={null}
trail email \
  --to recipient@example.com \
  --subject "Test Email" \
  --body "This is a test message."
```

<Note>
  Email settings must be configured in `traildepot/config.textproto` or via environment variables.
</Note>

## Component Management

### List Available Components

Show first-party WASM components:

```bash theme={null}
trail components list

# Output:
Available first-party components:
- trailbase-guest-ts (TypeScript/JavaScript runtime)
- trailbase-guest-rust (Rust runtime)
```

### Install Component

```bash theme={null}
# Install from registry
trail components add trailbase-guest-ts

# Install from local file
trail components add ./component.wasm

# Install from URL
trail components add https://example.com/component.wasm
```

### List Installed Components

```bash theme={null}
trail components installed

# Output:
Installed components:
- trailbase-guest-ts (v1.0.0)
```

### Update Components

Update all installed first-party components:

```bash theme={null}
trail components update
```

### Remove Component

```bash theme={null}
trail components remove trailbase-guest-ts
```

## Common Workflows

### Development Setup

<Steps>
  <Step title="Start Server">
    ```bash theme={null}
    trail run --dev
    ```
  </Step>

  <Step title="Create Admin User">
    ```bash theme={null}
    trail user add admin@localhost AdminPass123
    trail admin promote admin@localhost
    ```
  </Step>

  <Step title="Create Schema">
    ```bash theme={null}
    trail migration create_initial_schema
    # Edit the migration file
    # Restart server to apply
    ```
  </Step>

  <Step title="Generate Types">
    ```bash theme={null}
    trail schema todos > schema/todos.json
    npx json-schema-to-typescript schema/todos.json > src/types/todos.ts
    ```
  </Step>
</Steps>

### Production Deployment

<Steps>
  <Step title="Set Environment Variables">
    ```bash theme={null}
    export PUBLIC_URL=https://example.com
    export OBJECT_STORE_TYPE=s3
    export OBJECT_STORE_BUCKET=my-bucket
    export OBJECT_STORE_ACCESS_KEY_ID=...
    export OBJECT_STORE_SECRET_ACCESS_KEY=...
    ```
  </Step>

  <Step title="Run Server">
    ```bash theme={null}
    trail run \
      --data-dir /var/lib/trailbase \
      --address 0.0.0.0:4000 \
      --public-dir /var/www/app
    ```
  </Step>

  <Step title="Configure Reverse Proxy">
    Use nginx, Caddy, or similar to handle:

    * TLS termination
    * Request compression
    * Static file caching
    * Rate limiting
  </Step>
</Steps>

### Database Backup

```bash theme={null}
# Manual backup
cp traildepot/data/main.db backups/main-$(date +%Y%m%d).db

# Automated backup script
#!/bin/bash
DATE=$(date +%Y%m%d-%H%M%S)
cp traildepot/data/main.db backups/main-$DATE.db

# Keep only last 7 days
find backups/ -name "main-*.db" -mtime +7 -delete
```

<Info>
  TrailBase automatically creates backups in `traildepot/backups/`. These are SQLite database files that can be restored by copying them to `traildepot/data/`.
</Info>

### Reset Admin Password

If you lose admin credentials:

```bash theme={null}
# Create new admin user
trail user add newadmin@localhost SecurePass123
trail admin promote newadmin@localhost

# Or change existing admin password
trail user change-password admin@localhost NewSecurePass123
```

### Test Configuration

```bash theme={null}
# Validate config by starting server
trail run

# Check logs for errors
tail -f traildepot/logs/trailbase.log

# Test with cURL
curl http://localhost:4000/_/health
```

## Environment Variables

Override CLI options with environment variables:

```bash theme={null}
# Data directory
export DATA_DIR=/var/lib/trailbase

# Public URL
export PUBLIC_URL=https://example.com

# Server address
export ADDRESS=0.0.0.0:4000

# WASM runtime threads
export RUNTIME_THREADS=8

# Run server
trail run
```

## Configuration File

Main configuration file: `traildepot/config.textproto`

Example configuration:

```protobuf traildepot/config.textproto theme={null}
server {
  application_name: "My App"
  site_url: "https://example.com"
}

auth {
  disable_password_auth: false
  require_email_verification: true
  
  password_policy {
    min_length: 8
    require_uppercase: true
    require_lowercase: true
    require_number: true
  }
  
  oauth_providers: [
    {
      key: "github"
      value {
        client_id: "your-client-id"
        client_secret: "your-client-secret"
        provider_id: GITHUB
      }
    }
  ]
}

email {
  smtp_host: "smtp.gmail.com"
  smtp_port: 587
  smtp_username: "your-email@gmail.com"
  smtp_password: "your-app-password"
  from_address: "noreply@example.com"
}

record_apis: [
  {
    name: "todos"
    table_name: "todos"
    acl_authenticated: [CREATE, READ, UPDATE, DELETE]
  }
]
```

## Logging

TrailBase logs to:

* `traildepot/logs/trailbase.log` - Main application log
* `traildepot/logs/access.log` - HTTP access log
* `stderr` - With `--stderr-logging` flag

View logs:

```bash theme={null}
# Tail main log
tail -f traildepot/logs/trailbase.log

# View access log
tail -f traildepot/logs/access.log

# Search logs
grep ERROR traildepot/logs/trailbase.log
```

## Debugging

### Verbose Logging

```bash theme={null}
# Set log level via environment
export RUST_LOG=debug
trail run
```

### Test Database Queries

```bash theme={null}
# Open database
sqlite3 traildepot/data/main.db

# List tables
.tables

# Describe table
.schema todos

# Query data
SELECT * FROM todos;

# Check migrations
SELECT * FROM _schema_history;
```

### Health Check

```bash theme={null}
# Check if server is running
curl http://localhost:4000/_/health

# Output:
{"status":"ok"}
```

## Systemd Service

Run TrailBase as a systemd service:

```ini /etc/systemd/system/trailbase.service theme={null}
[Unit]
Description=TrailBase Server
After=network.target

[Service]
Type=simple
User=trailbase
Group=trailbase
WorkingDirectory=/var/lib/trailbase
Environment="DATA_DIR=/var/lib/trailbase"
Environment="PUBLIC_URL=https://example.com"
ExecStart=/usr/local/bin/trail run --address 0.0.0.0:4000
Restart=always
RestartSec=10

[Install]
WantedBy=multi-user.target
```

Manage the service:

```bash theme={null}
# Enable and start
sudo systemctl enable trailbase
sudo systemctl start trailbase

# Check status
sudo systemctl status trailbase

# View logs
sudo journalctl -u trailbase -f

# Restart
sudo systemctl restart trailbase
```

## Docker

Run TrailBase in Docker:

```bash theme={null}
# Pull image
docker pull trailbase/trailbase:latest

# Run container
docker run -d \
  --name trailbase \
  -p 4000:4000 \
  -v $(pwd)/traildepot:/data \
  -e PUBLIC_URL=http://localhost:4000 \
  trailbase/trailbase:latest

# View logs
docker logs -f trailbase

# Execute commands
docker exec trailbase trail admin list
```

Docker Compose:

```yaml docker-compose.yml theme={null}
version: '3.8'

services:
  trailbase:
    image: trailbase/trailbase:latest
    ports:
      - "4000:4000"
    volumes:
      - ./traildepot:/data
    environment:
      - DATA_DIR=/data
      - PUBLIC_URL=https://example.com
    command: run --address 0.0.0.0:4000
    restart: unless-stopped
```

## Next Steps

<CardGroup cols={2}>
  <Card title="First App" icon="rocket" href="/guides/first-app">
    Build your first application
  </Card>

  <Card title="Migrations" icon="code-branch" href="/guides/migrations">
    Learn about database migrations
  </Card>

  <Card title="Authentication" icon="lock" href="/guides/authentication">
    Manage users and auth
  </Card>

  <Card title="WASM Runtime" icon="bolt" href="/guides/wasm-runtime">
    Extend with WebAssembly
  </Card>
</CardGroup>

## Reference

* [GitHub Repository](https://github.com/trailbaseio/trailbase)
* [Docker Hub](https://hub.docker.com/r/trailbase/trailbase)
* [Installation Guide](/getting-started/install)
