# LearnHouse Documentation — Full Content

> This file contains the complete text of all LearnHouse documentation pages.
> Source: https://docs.learnhouse.app

---

# Untitled
URL: https://docs.learnhouse.app

## Platform Features

## Tech Stack

| Layer | Technology |
| --- | --- |
| Frontend | Next.js 16, React 19, Tailwind CSS v4, Tiptap |
| Backend | FastAPI, Python, SQLModel, Alembic |
| Collaboration | Hocuspocus (Yjs/CRDT) |
| Database | PostgreSQL 16 + pgvector |
| Cache | Redis 7.2 |
| AI | Google Gemini, LlamaIndex |
| CLI | Commander (Node.js) |

New to LearnHouse? Start with the [Quickstart guide](/getting-started/quickstart) to get a running instance in under 5 minutes.

## Explore by Topic

### For Educators & Admins
- [Creating Courses](/platform/courses) — Chapters, activities, and collections
- [Using the Editor](/platform/editor) — Blocks, collaboration, and content creation
- [AI Features](/platform/ai) — AI tutoring for students and teaching assistants
- [User Management](/platform/users) — Roles, permissions, and authentication
- [Organizations](/platform/organizations) — Multi-tenancy and org settings

### For DevOps & Self-Hosters
- [Quick Install](/self-hosting/installation/quick-install) — One command setup with `npx learnhouse@latest setup`
- [Configuration](/self-hosting/configuration) — Environment variables, AI, email, and storage
- [Maintenance](/self-hosting/maintenance) — Updates, backups, monitoring, and troubleshooting

### For Developers
- [Architecture Overview](/developers/architecture) — How the system fits together
- [API Reference](/developers/api) — REST endpoints, authentication, and examples
- [Contributing](/developers/contributing) — Dev environment setup and guidelines

---

# CLI
URL: https://docs.learnhouse.app/cli

The LearnHouse CLI is the primary tool for deploying, managing, and developing LearnHouse. It orchestrates Docker Compose services and provides an interactive setup wizard for production deployments, as well as a full local development environment.

**Package**: [`learnhouse`](https://www.npmjs.com/package/learnhouse) on npm

## Installation

### Quick Start (recommended)

```bash
npx learnhouse@latest setup
```

### One-line Install (macOS / Linux)

Installs Docker, Node.js, and launches the CLI:

```bash
curl -fsSL https://raw.githubusercontent.com/learnhouse/learnhouse/main/apps/cli/install.sh | bash
```

### Windows (PowerShell)

```powershell
irm https://raw.githubusercontent.com/learnhouse/learnhouse/main/apps/cli/install.ps1 | iex
```

## Requirements

- **Node.js** 18+
- **Docker** with Docker Compose v2

## What It Does

The CLI handles two main workflows:

### Production Deployment

The [setup wizard](/cli/setup-wizard) generates a complete Docker Compose deployment with:

- **LearnHouse app** container (Next.js + FastAPI)
- **PostgreSQL** database (with optional pgvector for AI)
- **Redis** cache
- **Caddy** or **Nginx** reverse proxy (with optional auto-SSL)

Each deployment gets a unique ID, allowing multiple instances on the same machine.

### Local Development

The [`dev` command](/cli/dev-mode) starts infrastructure in Docker and runs the API, web, and collaboration servers locally with hot reload.

## Quick Reference

| Command | Description |
| --- | --- |
| `npx learnhouse setup` | Interactive setup wizard |
| `npx learnhouse start` | Start all services |
| `npx learnhouse stop` | Stop all services |
| `npx learnhouse logs` | Stream container logs |
| `npx learnhouse doctor` | Run diagnostics |
| `npx learnhouse backup` | Backup database |
| `npx learnhouse dev` | Start dev environment |

See [Commands](/cli/commands) for the full reference.

---

# Commands
URL: https://docs.learnhouse.app/cli/commands

Full reference for all LearnHouse CLI commands.

## `setup`

Interactive wizard that generates a complete Docker Compose deployment. See [Setup Wizard](/cli/setup-wizard) for details.

```bash
npx learnhouse@latest setup
```

## `start`

Start all Docker containers for your deployment.

```bash
npx learnhouse start
```

## `stop`

Stop all running containers.

```bash
npx learnhouse stop
```

## `logs`

Stream logs from all containers in real-time.

```bash
npx learnhouse logs
```

## `config`

Display current installation metadata — version, directory, URL, organization slug, and file locations.

```bash
npx learnhouse config
```

## `doctor`

Run comprehensive diagnostics to identify issues. Checks:

- Docker installation and daemon status
- Docker Compose v2 availability
- Container health and restart counts
- Port availability
- DNS resolution (for non-localhost domains)
- Disk space (warns below 1 GB)
- Docker volume sizes
- Log analysis (scans for errors)
- `.env` validation (required variables, secret length)
- Image freshness

```bash
npx learnhouse doctor
```

## `backup`

Create a database backup as a `.tar.gz` archive containing a `pg_dump` and optionally your `.env` file.

```bash
npx learnhouse backup
```

Backups are saved to `{installDir}/backups/learnhouse-backup-{timestamp}.tar.gz`.

### Restore

Restore a database from a backup archive. This overwrites the current database.

```bash
npx learnhouse backup --restore
npx learnhouse restore <archive.tar.gz>
```

Restore only works with local (Docker) databases, not external connections. Restart services after restoring.

## `deployments`

View and manage deployments on the current machine.

```bash
npx learnhouse deployments
```

Features:
- List all LearnHouse deployments with container status
- Scale resource limits (memory) for `learnhouse-app`, `db`, and `redis`
- View current resource usage via `docker stats`

## `shell`

Open an interactive shell (`/bin/sh`) inside a running container.

```bash
npx learnhouse shell
```

Displays a list of running containers to choose from.

## `env`

Interactive environment variable editor. Edit variables by category:

- Domain & Hosting
- Database & Redis
- Security
- AI
- Email
- S3 Storage
- OAuth

```bash
npx learnhouse env
```

Secret values are masked in the display. Optionally restart services after changes.

## `health`

Run health checks against the running deployment.

```bash
npx learnhouse health
```

Checks container status, PostgreSQL connection, Redis ping, HTTP health endpoint, disk usage, and resource consumption.

## `dev`

Start a local development environment. See [Dev Mode](/cli/dev-mode) for details.

```bash
npx learnhouse dev
```

| Flag | Description |
| --- | --- |
| `--ee` | Enable Enterprise Edition features |

---

# Dev Mode
URL: https://docs.learnhouse.app/cli/dev-mode

The `dev` command starts a full local development environment with hot reload for all services.

```bash
npx learnhouse dev
```

## How It Works

The command splits infrastructure and application services:

- **Infrastructure** (Docker): PostgreSQL with pgvector + Redis run in containers via `.learnhouse/docker-compose.dev.yml`
- **Application** (local): API, Web, and Collab servers run directly on your machine with hot reload

## Requirements

- Docker (for database and Redis)
- [bun](https://bun.sh/) (for web and collab dependencies)
- [uv](https://docs.astral.sh/uv/) (for Python API dependencies)

The CLI auto-installs dependencies (`bun install`, `uv sync`) if `node_modules` or `.venv` are missing.

## Startup Flow

1. **Detect project root** — Looks for the monorepo structure (`apps/api`, `apps/web`, `apps/collab`)
2. **Start infrastructure** — Launches PostgreSQL and Redis containers (reuses existing ones if running)
3. **Health checks** — Waits for database and Redis to be ready
4. **Admin setup** — On first run, prompts for admin email and password. Credentials are saved and reused on subsequent runs.
5. **Install dependencies** — Runs `bun install` and `uv sync` if needed
6. **Start services** — Launches API, Web, and Collab with color-coded output

## Services

| Service | Command | Port |
| --- | --- | --- |
| API | `uv run python app.py` | 1338 |
| Web | `next dev --turbopack` | 3000 |
| Collab | `tsx watch src/index.ts` | 4000 |

## Interactive Controls

While running, you can type commands to manage services:

| Key | Action |
| --- | --- |
| `ra` | Restart API |
| `rw` | Restart Web |
| `rc` | Restart Collab |
| `rb` | Restart all services |
| `q` | Quit (graceful shutdown) |

## Enterprise Edition

Use the `--ee` flag to enable Enterprise Edition features:

```bash
npx learnhouse dev --ee
```

Without the flag, the `apps/api/ee/` directory is temporarily hidden during development.

## Shutdown

When you quit (`q` or Ctrl+C):

- Local services (API, Web, Collab) are stopped
- Docker containers (PostgreSQL, Redis) keep running for the next session
- To fully stop infrastructure:

```bash
docker compose -f .learnhouse/docker-compose.dev.yml -p learnhouse-dev down
```

Database data persists across dev sessions via Docker volumes. Your data is safe between restarts.

---

# Environment Variables
URL: https://docs.learnhouse.app/cli/environment-variables

The CLI generates a `.env` file during setup with all configuration variables. These can also be edited interactively with `npx learnhouse env`.

## Domain & Hosting

| Variable | Description | Example |
| --- | --- | --- |
| `LEARNHOUSE_DOMAIN` | Hostname | `localhost` |
| `HTTP_PORT` | HTTP port for reverse proxy | `80` |
| `NEXT_PUBLIC_LEARNHOUSE_API_URL` | Public API URL | `http://localhost/api/v1/` |
| `NEXT_PUBLIC_LEARNHOUSE_BACKEND_URL` | Backend URL | `http://localhost` |
| `NEXT_PUBLIC_LEARNHOUSE_DOMAIN` | Public domain | `localhost` |
| `NEXT_PUBLIC_LEARNHOUSE_TOP_DOMAIN` | Top-level domain | `localhost` |
| `NEXT_PUBLIC_LEARNHOUSE_MULTI_ORG` | Multi-org mode | `false` |
| `NEXT_PUBLIC_LEARNHOUSE_DEFAULT_ORG` | Default org slug | `my-school` |
| `NEXT_PUBLIC_LEARNHOUSE_HTTPS` | HTTPS enabled | `false` |

## Database & Redis

| Variable | Description | Example |
| --- | --- | --- |
| `LEARNHOUSE_SQL_CONNECTION_STRING` | PostgreSQL connection | `postgresql://learnhouse:pass@db:5432/learnhouse` |
| `LEARNHOUSE_REDIS_CONNECTION_STRING` | Redis connection | `redis://redis:6379/learnhouse` |
| `LEARNHOUSE_REDIS_URL` | Redis URL | `redis://redis:6379/learnhouse` |
| `POSTGRES_USER` | Database user (local only) | `learnhouse` |
| `POSTGRES_PASSWORD` | Database password (local only) | Auto-generated |
| `POSTGRES_DB` | Database name (local only) | `learnhouse` |

## Security & Authentication

| Variable | Description | Example |
| --- | --- | --- |
| `LEARNHOUSE_AUTH_JWT_SECRET_KEY` | JWT signing key | Auto-generated |
| `LEARNHOUSE_INITIAL_ADMIN_EMAIL` | First admin email | `admin@example.com` |
| `LEARNHOUSE_INITIAL_ADMIN_PASSWORD` | First admin password | Set during setup |
| `LEARNHOUSE_COOKIE_DOMAIN` | Cookie domain | `localhost` |
| `COLLAB_INTERNAL_KEY` | Collaboration service key | Auto-generated |
| `NEXTAUTH_SECRET` | NextAuth secret | Auto-generated |
| `NEXTAUTH_URL` | NextAuth URL | `http://localhost` |

## Application

| Variable | Description | Example |
| --- | --- | --- |
| `LEARNHOUSE_PORT` | Internal API port | `9000` |
| `LEARNHOUSE_DEVELOPMENT_MODE` | Dev mode flag | `False` |
| `NEXT_PUBLIC_COLLAB_URL` | WebSocket collab URL | `ws://localhost/collab` |

## AI

| Variable | Description | Example |
| --- | --- | --- |
| `LEARNHOUSE_IS_AI_ENABLED` | Enable AI features | `True` / `False` |
| `LEARNHOUSE_GEMINI_API_KEY` | Gemini API key | Your API key |

## Email

| Variable | Description | Example |
| --- | --- | --- |
| `LEARNHOUSE_EMAIL_PROVIDER` | Email provider | `resend` / `smtp` |
| `LEARNHOUSE_SYSTEM_EMAIL_ADDRESS` | From address | `noreply@example.com` |
| `LEARNHOUSE_RESEND_API_KEY` | Resend API key | Your API key |
| `LEARNHOUSE_SMTP_HOST` | SMTP host | `smtp.gmail.com` |
| `LEARNHOUSE_SMTP_PORT` | SMTP port | `587` |
| `LEARNHOUSE_SMTP_USERNAME` | SMTP username | `user@example.com` |
| `LEARNHOUSE_SMTP_PASSWORD` | SMTP password | Your password |
| `LEARNHOUSE_SMTP_USE_TLS` | Enable TLS | `True` / `False` |

## S3 Storage

| Variable | Description | Example |
| --- | --- | --- |
| `LEARNHOUSE_CONTENT_DELIVERY_TYPE` | Storage type | `filesystem` / `s3api` |
| `LEARNHOUSE_S3_API_BUCKET_NAME` | S3 bucket name | `my-bucket` |
| `LEARNHOUSE_S3_API_ENDPOINT_URL` | S3 endpoint (optional for AWS) | `https://s3.amazonaws.com` |

## OAuth

| Variable | Description | Example |
| --- | --- | --- |
| `LEARNHOUSE_GOOGLE_CLIENT_ID` | Google OAuth client ID | Your client ID |
| `LEARNHOUSE_GOOGLE_CLIENT_SECRET` | Google OAuth client secret | Your secret |

## Unsplash

| Variable | Description | Example |
| --- | --- | --- |
| `NEXT_PUBLIC_UNSPLASH_ACCESS_KEY` | Unsplash API key | Your access key |

---

# Setup Wizard
URL: https://docs.learnhouse.app/cli/setup-wizard

The setup wizard (`npx learnhouse@latest setup`) is an interactive 6-step process that generates a complete Docker Compose deployment. You can go back and edit any step before confirming.

## Step 1 — Install Directory

Choose where the deployment files will be created.

- **Default**: `./learnhouse`
- The directory is created if it doesn't exist

## Step 2 — Domain Configuration

Configure your hostname and HTTPS settings.

- **Domain**: hostname or IP address (default: `localhost`)
- **HTTPS options** (non-localhost only):
  - **Automatic SSL** (recommended) — Uses Let's Encrypt via Caddy. Requires a valid domain and ports 80/443.
  - **Manual SSL** — You handle the reverse proxy or Cloudflare. LearnHouse runs on HTTP internally.
  - **No HTTPS** — HTTP only (not recommended for production)
- **Port**: Automatically set based on SSL choice (443 for auto SSL, 80 for HTTP)

## Step 3 — Database & Redis

Choose local Docker containers or connect to external services.

### PostgreSQL

- **Local Docker** (recommended):
  - **AI-enabled** (recommended) — Uses `pgvector/pgvector:pg16` for RAG and vector search features
  - **Standard** — Uses `postgres:16-alpine`, lighter footprint
  - Password is auto-generated
- **External** — Provide a connection string (`postgresql://user:pass@host:5432/db`). The wizard tests connectivity before proceeding.

### Redis

- **Local Docker** (recommended) — Uses `redis:7.2.3-alpine`
- **External** — Provide a connection string. The wizard tests connectivity before proceeding.

## Step 4 — Organization

Set your organization name (e.g., "My School"). This creates the initial organization in the database.

## Step 5 — Admin Account

Create the first admin user with email and password (minimum 8 characters).

## Step 6 — Optional Features

Enable any of the following integrations:

| Feature | Required Configuration |
| --- | --- |
| **AI (Gemini)** | Gemini API key |
| **Email (Resend)** | Resend API key + system email address |
| **Email (SMTP)** | Host, port, username, password, TLS toggle + system email |
| **S3 Storage** | Bucket name, endpoint URL (optional for AWS) |
| **Google OAuth** | Client ID + Client Secret |
| **Unsplash** | Access Key |

## Confirmation

After completing all steps, the wizard shows a summary of your configuration. You can:

- **Proceed** — Generate files and optionally start the deployment
- **Edit** — Go back and change any step
- **Cancel** — Abort without generating anything

## Generated Files

After confirmation, the wizard creates:

```
{installDir}/
├── docker-compose.yml        # Service definitions
├── .env                      # All configuration variables
├── learnhouse.config.json    # CLI metadata
└── extra/
    ├── Caddyfile             # If auto-SSL enabled
    └── nginx.prod.conf       # If manual SSL or HTTP
```

## Docker Services

Each deployment gets a unique 8-character ID for container and network isolation.

| Service | Image | Purpose |
| --- | --- | --- |
| `learnhouse-app-{id}` | `ghcr.io/learnhouse/app` | Next.js + FastAPI application |
| `learnhouse-db-{id}` | `pgvector:pg16` or `postgres:16-alpine` | PostgreSQL database |
| `learnhouse-redis-{id}` | `redis:7.2.3-alpine` | Redis cache |
| `learnhouse-caddy-{id}` | `caddy:2-alpine` | Reverse proxy with auto-SSL |
| `learnhouse-nginx-{id}` | `nginx:alpine` | Reverse proxy (no auto-SSL) |

The wizard optionally starts the deployment and waits up to 3 minutes for the health check (`/api/v1/health`) to pass before showing your credentials and URL.

## Release Channels

During setup you choose a release channel:

- **Stable** — Recommended for production
- **Dev** — Bleeding edge, latest features
- **Custom** — Specify an exact image tag

---

# Developers
URL: https://docs.learnhouse.app/developers

Welcome to the LearnHouse developer documentation. This section covers everything you need to understand, build, and contribute to the LearnHouse platform.

## Project Structure

LearnHouse is organized as a monorepo containing four main applications:

| App | Technology | Description |
| --- | --- | --- |
| **web** | Next.js (React) | Frontend web application |
| **api** | FastAPI (Python) | Backend REST API |
| **collab** | Hocuspocus | Real-time collaboration WebSocket server |
| **cli** | Commander (Node.js) | Command-line interface for development and management |

All four apps live under the `apps/` directory in the [LearnHouse repository](https://github.com/learnhouse/learnhouse).

## Sections

### [Architecture](/developers/architecture)

Learn how the different parts of LearnHouse fit together, from the frontend and backend to the supporting services that power the platform.

### [Contributing](/developers/contributing)

Get your local development environment running, understand our contribution workflow, and review code style guidelines.

### [API Reference](/developers/api)

Explore the RESTful API that drives LearnHouse. Covers authentication, key endpoints, and how to interact with the platform programmatically.

---

# API Reference
URL: https://docs.learnhouse.app/developers/api

The LearnHouse API is a RESTful service built with **FastAPI**. It powers all platform operations, from user authentication to course management and AI features. All endpoints are prefixed with `/api/v1/`.

## Interactive Documentation

The interactive API documentation is only available when running in **development mode**. Production instances do not expose Swagger UI or the OpenAPI spec.

When running the development environment, auto-generated interactive API documentation is available:

- **Swagger UI** -- Available at `/docs` (e.g., [http://localhost:1338/docs](http://localhost:1338/docs))

These interfaces let you explore all available endpoints, view request and response schemas, and test API calls directly from your browser.

## Base URL

In local development, the API is available at:

```
http://localhost:1338/api/v1/
```

In production, the API is served behind a reverse proxy and is accessible at the root domain under `/api/v1/`.

## Response Format

All API responses are returned as JSON. Successful responses typically include the requested data directly, while error responses follow this structure:

```json
{
  "detail": "Description of the error"
}
```

## Sections

- **[Authentication](/developers/api/authentication)** -- How to obtain and use authentication tokens.
- **[Endpoints](/developers/api/endpoints)** -- Overview of the key API endpoint groups.

## OpenAPI Specification

Since the API is built with FastAPI, a machine-readable OpenAPI specification is available at `/openapi.json` on development instances. This can be used to generate client libraries or import into API testing tools.

The OpenAPI spec at `/openapi.json` is only served in development mode.

---

# API Authentication
URL: https://docs.learnhouse.app/developers/api/authentication

The LearnHouse API supports **JWT cookies** for browser sessions and **API tokens** for programmatic access.

## JWT Authentication

Login to receive a JWT access token (HS256, expires in 8 hours):

```bash
curl -X POST http://localhost:1338/api/v1/auth/login \
  -H "Content-Type: application/json" \
  -d '{"email": "you@example.com", "password": "your-password"}'
```

Then authenticate requests via the `Authorization` header:

```bash
curl http://localhost:1338/api/v1/users/me \
  -H "Authorization: Bearer <access_token>"
```

The token is also set as an `access_token_cookie` for browser-based sessions. Use `/api/v1/auth/refresh` to renew expired tokens within the 30-day refresh window.

## API Tokens

API tokens are available on the **Pro plan**. Create and manage them in organization settings.

For programmatic access, use API tokens (prefixed with `lh_`):

```bash
curl http://localhost:1338/api/v1/users/me \
  -H "Authorization: Bearer lh_your_api_token_here"
```

## Auth Endpoints

| Method | Endpoint | Description |
| --- | --- | --- |
| `POST` | `/api/v1/auth/login` | Login and receive a JWT |
| `GET` | `/api/v1/auth/refresh` | Refresh an expired token |
| `DELETE` | `/api/v1/auth/logout` | Invalidate the session |
| `POST` | `/api/v1/auth/oauth` | Google OAuth login |
| `POST` | `/api/v1/auth/verify-email` | Verify email address |

---

# API Endpoints
URL: https://docs.learnhouse.app/developers/api/endpoints

This page provides an overview of all API endpoint groups available in LearnHouse. All endpoints are prefixed with `/api/v1/`. For the full interactive reference with request and response schemas, visit the Swagger UI at `/docs` on a development instance.

The complete, interactive API documentation is available at [http://localhost:1338/docs](http://localhost:1338/docs) in development mode only. It includes every endpoint, parameter, and response schema.

## Core Endpoint Groups

### Authentication

Login, logout, token refresh, OAuth, and email verification.

```bash
# Login
curl -X POST http://localhost:1338/api/v1/auth/login \
  -H "Content-Type: application/json" \
  -d '{"email": "user@example.com", "password": "password"}'
```

See [Authentication](/developers/api/authentication) for full details.

### Users

User CRUD, profile management, session info, and password reset.

```bash
# Get current user profile
curl http://localhost:1338/api/v1/users/me \
  -H "Authorization: Bearer <token>"
```

### Organizations

Organization CRUD, user management, roles, invites, configuration, SEO settings, branding, API tokens, and custom domains.

```bash
# Get organization details
curl http://localhost:1338/api/v1/orgs/{org_slug} \
  -H "Authorization: Bearer <token>"
```

### Courses

Course CRUD, cloning, export/import, and contributor management.

```bash
# List courses in an organization
curl http://localhost:1338/api/v1/courses \
  -H "Authorization: Bearer <token>"

# Create a new course
curl -X POST http://localhost:1338/api/v1/courses \
  -H "Authorization: Bearer <token>" \
  -H "Content-Type: application/json" \
  -d '{
    "name": "Introduction to Python",
    "description": "A beginner-friendly Python course"
  }'
```

### Chapters

Chapter CRUD and ordering within courses.

```bash
# List chapters in a course
curl http://localhost:1338/api/v1/chapters \
  -H "Authorization: Bearer <token>"
```

### Activities

Activity CRUD -- individual content units within chapters (pages, videos, documents).

```bash
# Get activities
curl http://localhost:1338/api/v1/activities \
  -H "Authorization: Bearer <token>"
```

### Blocks

Block CRUD -- content blocks within activities.

### Collections

Collections group related courses together for organization and discovery.

```bash
# List collections
curl http://localhost:1338/api/v1/collections \
  -H "Authorization: Bearer <token>"
```

### Assignments

Assignment CRUD for course assessments.

### AI

AI-powered features including an assistant, magic blocks, course planning, and RAG (Retrieval-Augmented Generation).

```bash
# AI endpoints vary by configuration
curl http://localhost:1338/api/v1/ai/chat \
  -H "Authorization: Bearer <token>" \
  -H "Content-Type: application/json" \
  -d '{"message": "Explain this concept"}'
```

### Analytics

Course analytics and usage tracking.

### Search

Full-text search across courses and content.

### Code Execution

Code execution endpoints powered by Judge0.

### Learning Trails

Learning trail management and progress tracking.

### Video Streaming

Video streaming and delivery endpoints.

## Community Features (Standard Plan)

### Communities

Community forums for organizations.

### Discussions

Discussion threads within communities.

### User Groups

User group management for organizing learners.

## Pro Features (Pro Plan)

### Certifications

Certificate generation and management for course completion.

### Boards

Collaborative whiteboards for interactive learning.

### Playgrounds

AI-generated interactive elements for hands-on learning.

### Podcasts

Podcast and episode CRUD for audio content delivery.

## Infrastructure Endpoints

| Method | Endpoint | Description |
| --- | --- | --- |
| `GET` | `/api/v1/health` | Health check |
| `GET` | `/api/v1/instance/info` | Public instance information |
| `GET` | `/api/v1/content/...` | Content delivery (filesystem or S3) |
| `GET` | `/openapi.json` | OpenAPI spec (dev mode only) |

## Common Patterns

- All endpoints are prefixed with `/api/v1/`.
- Resources follow standard REST conventions: `GET` to list or retrieve, `POST` to create, `PUT` to update, `DELETE` to remove.
- Authenticated endpoints require either the `Authorization: Bearer <token>` header or the `access_token_cookie` cookie.
- Programmatic access uses API tokens with the `lh_` prefix (Pro plan).
- Responses are returned as JSON.

Endpoint paths and request/response schemas may evolve between versions. Always refer to the interactive `/docs` endpoint on a development instance for the most up-to-date reference.

---

# Architecture Overview
URL: https://docs.learnhouse.app/developers/architecture

LearnHouse is a multi-directory project with multiple applications that work together to deliver the full platform experience. The system follows a clear separation of concerns between the frontend, backend, and supporting services.

## Project Structure

```
learnhouse/
├── apps/
│   ├── web/          # Next.js frontend
│   ├── api/          # FastAPI backend
│   ├── collab/       # Hocuspocus collaboration server
│   └── cli/          # LearnHouse CLI
└── community-edition/ # Docker Compose deployment config
```

## How It All Fits Together

The platform consists of four applications backed by two core services:

- **Web (Next.js)** -- The user-facing frontend that communicates with the backend API and the collaboration server.
- **API (FastAPI)** -- The backend that handles authentication, course management, storage, uploads, AI features, and all business logic.
- **Collab (Hocuspocus)** -- A WebSocket server that powers real-time collaborative editing with JWT authentication, Redis persistence, and per-board user limits.
- **CLI (Commander)** -- A command-line tool used for local development and management tasks.

## Backing Services

LearnHouse relies on two primary backing services:

- **PostgreSQL 16** -- The primary relational database for storing all application data including users, courses, organizations, and activity records. Uses the pgvector extension for AI embedding storage.
- **Redis 7.2** -- Used for caching, session management, collaboration state persistence, and message brokering between services.

---

# Backend Architecture
URL: https://docs.learnhouse.app/developers/architecture/backend

The LearnHouse backend is a **FastAPI** application written in Python, located at `apps/api` in the project. It serves as the central API layer that handles all business logic and data management.

## Technology Stack

- **FastAPI** >= 0.135.1 -- High-performance Python web framework
- **Python 3.14.3**
- **SQLModel** >= 0.0.37 -- ORM for database interactions (built on SQLAlchemy and Pydantic)
- **Alembic** -- Database migration management
- **PostgreSQL 16** with **pgvector** extension -- Primary relational database
- **Redis** >= 7.2.1 -- Caching layer and session storage
- **Uvicorn** 0.41.0 -- ASGI server
- **uv** -- Python package manager

## Key Dependencies

- **psycopg2-binary** -- PostgreSQL adapter
- **pyjwt[crypto]** -- JWT token handling
- **pwdlib[argon2]** -- Password hashing with Argon2
- **google-genai** >= 1.65.0 -- Gemini AI integration
- **llama-index-core + pgvector** -- RAG and vector embeddings
- **stripe** -- Payment processing
- **workos** -- Enterprise SSO
- **boto3** -- S3-compatible storage
- **resend** -- Transactional email
- **sentry-sdk** -- Error tracking and monitoring

## Configuration

The backend uses a dual configuration system:

- **YAML config** at `config/config.yaml` for structured settings
- **Environment variables** which override YAML values when set

The API prefix for all endpoints is `/api/v1/`.

## Responsibilities

The backend handles all core platform operations:

- **Authentication and authorization** -- JWT-based token authentication with role-based access control
- **Course management** -- CRUD operations for organizations, courses, chapters, and activities
- **User management** -- Registration, profiles, and permissions
- **File storage and uploads** -- Handling media uploads with support for local filesystem and S3-compatible storage (via boto3)
- **AI features** -- Integration with Google Gemini and LlamaIndex for learning assistance and RAG
- **Search** -- Content indexing and search across courses and activities
- **Payments** -- Stripe integration for course monetization
- **Email** -- Transactional email via Resend

## Database Layer

SQLModel is used as the ORM, connecting to a PostgreSQL 16 database with the pgvector extension for AI embeddings. Database models define the schema for all entities: organizations, users, courses, chapters, activities, collections, and more. Migrations are managed with **Alembic** to keep the schema in sync across environments.

## Caching

Redis is used for:

- **Response caching** -- Frequently accessed data is cached to reduce database load.
- **Session data** -- Temporary session information is stored in Redis for fast retrieval.

## API Documentation

FastAPI automatically generates interactive API documentation, but it is only available when running in development mode.

Swagger UI (`/docs/`) and ReDoc (`/redoc/`) are only accessible when `LEARNHOUSE_DEVELOPMENT_MODE=True` is set. They are disabled in production.

## Directory Structure

```
apps/api/
├── src/
│   ├── routers/      # API route definitions
│   ├── db/           # SQLModel table definitions
│   ├── services/     # Business logic
│   ├── security/     # Authentication and authorization
│   └── core/         # Configuration and dependencies
├── migrations/       # Alembic database migrations
├── ee/               # Enterprise Edition features
└── config/           # YAML configuration files
```

## Development

The backend runs on **port 1338** by default during local development (configurable via `LEARNHOUSE_PORT`). In production Docker deployments, it runs on port 9000. Install dependencies and run the server:

```bash
uv sync          # install dependencies
uv run uvicorn   # start the dev server
```

When using the LearnHouse CLI (`learnhouse dev`), the backend starts automatically with hot reload enabled.

---

# Frontend Architecture
URL: https://docs.learnhouse.app/developers/architecture/frontend

The LearnHouse frontend is a **Next.js 16** application located at `apps/web` in the project. It serves as the primary user interface for learners, instructors, and administrators.

## Technology Stack

- **Next.js 16.1.6** with the App Router (standalone output)
- **React 19.2.4** with Server Components
- **TypeScript 5.9.3**
- **TailwindCSS v4** for styling
- **Bun** as the package manager
- **Turbopack** for development builds (`next dev --turbopack`)
- **SWR** for client-side data fetching

## Key Dependencies

- **@tiptap/core** -- Block-based rich text editor
- **@radix-ui** -- Accessible, unstyled UI primitives
- **@hocuspocus/provider** -- Real-time collaboration client
- **yjs** -- CRDT library for conflict-free collaborative editing
- **@codemirror** -- Code editor component
- **recharts** -- Charting and data visualization
- **formik / yup** -- Form handling and validation
- **motion** -- Animation library
- **i18next** -- Internationalization
- **wavesurfer.js** -- Audio/podcast player
- **jspdf / html2canvas** -- Certificate generation
- **unsplash-js** -- Unsplash image integration

## App Router

The frontend uses the Next.js App Router, which enables:

- **Server Components by default** -- Pages and layouts render on the server, reducing client-side JavaScript and improving initial load times.
- **Client Components where needed** -- Interactive elements opt into client-side rendering with the `"use client"` directive.
- **Streaming and Suspense** -- Content is progressively streamed to the browser as it becomes ready.
- **Route Groups and Layouts** -- Shared layouts and nested routing keep the codebase organized.

## Authentication

Authentication is handled via **JWT tokens** issued by the FastAPI backend. On login, the backend sets an `access_token_cookie` (HS256, 8-hour expiry) that the frontend attaches to API requests. Protected routes check for a valid session before rendering.

## Communication with the Backend

The frontend communicates with the FastAPI backend over HTTP. API calls are made from both:

- **Server Components** -- Data is fetched at request time on the server, which keeps sensitive tokens off the client.
- **Client Components** -- Interactive features make API calls directly from the browser using **SWR** for caching and revalidation.

## Directory Structure

```
apps/web/
├── app/              # App Router pages and layouts
├── components/       # Reusable UI components
├── services/         # API client and service functions
├── store/            # Client-side state management
└── public/           # Static assets
```

## Development

The frontend runs on **port 3000** during local development. Start the dev server with Turbopack enabled:

```bash
bun dev  # runs next dev --turbopack
```

When using the LearnHouse CLI (`learnhouse dev`), the frontend starts automatically with hot reload enabled.

---

# Supporting Services
URL: https://docs.learnhouse.app/developers/architecture/services

LearnHouse relies on several supporting services that run alongside the main applications. In both development and production, these services are managed via Docker (configuration in the `community-edition/` directory).

## PostgreSQL

PostgreSQL 16 (Alpine) is the primary database for LearnHouse. It stores all persistent application data including:

- Organizations and their configurations
- User accounts and authentication records
- Courses, chapters, and activities
- Collections, trails, and progress tracking
- AI vector embeddings (via the pgvector extension)

The backend connects to PostgreSQL through SQLModel. In development, the LearnHouse CLI automatically starts a PostgreSQL container.

**Default port:** `5432`

## Redis

Redis 7.2.3 (Alpine) serves as the caching, session management, and collaboration persistence layer:

- **Caching** -- Reduces database load by storing frequently accessed data in memory.
- **Session storage** -- Manages user session data for fast access.
- **Collaboration state** -- Stores Yjs document state from the Collab server with a 1-hour TTL before it is persisted to PostgreSQL.
- **Pub/Sub** -- Enables communication between services when needed.

**Default port:** `6379`

## Hocuspocus (Collaboration Server)

The Hocuspocus server, located at `apps/collab`, provides real-time collaborative editing capabilities. It is a Node.js + TypeScript application (run via tsx) built on [Hocuspocus](https://hocuspocus.dev/) ^3.0.0, which uses the Yjs CRDT library under the hood. It connects to Redis via ioredis ^5.9.3.

**Default port:** `4000` (configurable via `COLLAB_PORT` env var)

### Authentication

The Collab server performs JWT verification using the same secret as the API backend. On connection, it verifies board membership by making a request to the API.

### Persistence

Document state follows a two-tier persistence strategy:

1. **Redis** -- Yjs state is first stored in Redis with a 1-hour TTL for fast access.
2. **PostgreSQL** -- State is persisted to the database via the API with a 5-second debounce to avoid excessive writes.

### Rate Limiting and Capacity

- **Max 10 concurrent users** per board
- **Rate limiting** of 30 connections per IP per minute

### Key Features

- **Real-time document synchronization** -- Multiple users can edit the same activity simultaneously.
- **Conflict resolution** -- Yjs CRDTs handle concurrent edits without conflicts.
- **Durable persistence** -- Document state survives server restarts through Redis and PostgreSQL.

The frontend connects to Hocuspocus directly over WebSocket using the `@hocuspocus/provider` client for low-latency collaborative editing.

## nginx (Reverse Proxy)

In production deployments, nginx (Alpine) acts as the reverse proxy that routes incoming traffic to the appropriate service:

- Frontend requests go to the Next.js application
- API requests are forwarded to the FastAPI backend
- WebSocket connections for collaboration are routed to the Hocuspocus server

nginx also handles TLS termination and static asset serving in production environments.

## Service Communication

All services communicate over a shared Docker network. The typical request flow is:

```
Client
  └── nginx (reverse proxy)
        ├── web (Next.js frontend, port 3000)
        ├── api (FastAPI backend, port 9000)
        │     ├── PostgreSQL (port 5432)
        │     └── Redis (port 6379)
        └── collab (Hocuspocus, port 4000)
              ├── Redis (port 6379)
              └── api (port 9000, for persistence & auth)
```

The frontend makes HTTP requests to the backend API. The collaboration server authenticates connections via JWT (shared secret with the API), verifies board membership through the API, and persists document state to both Redis and PostgreSQL (via the API). PostgreSQL is accessed directly only by the backend.

---

# Contributing to LearnHouse
URL: https://docs.learnhouse.app/developers/contributing

Thank you for your interest in contributing to LearnHouse! Whether you are fixing a bug, adding a feature, or improving documentation, your contributions are welcome.

## Getting Started

1. **[Set up your development environment](/developers/contributing/dev-environment)** -- Get a local instance of LearnHouse running using the LearnHouse CLI.
2. **[Review the contribution guidelines](/developers/contributing/guidelines)** -- Understand our workflow, code style, and expectations for pull requests.

## Finding Work

The best place to start is the [LearnHouse GitHub issues](https://github.com/learnhouse/learnhouse/issues) page. Look for issues labeled:

- **`help wanted`** -- Issues where community contributions are especially welcome.
- **`good first issue`** -- Smaller, well-scoped tasks ideal for first-time contributors.

If you have an idea for a new feature, open an issue first to discuss it with the maintainers before starting work.

## Questions

If you have questions about contributing, feel free to open a discussion on the [GitHub repository](https://github.com/learnhouse/learnhouse) or reach out to the maintainers through the issue tracker.

---

# Development Environment Setup
URL: https://docs.learnhouse.app/developers/contributing/dev-environment

The LearnHouse CLI provides a streamlined way to set up and run the entire development environment with a single command.

## Prerequisites

Make sure you have the following installed before proceeding:

- **Docker** (with Docker Compose v2)
- **Node.js 18+**

Make sure Docker has at least **4GB of RAM** allocated. You can check and adjust this in Docker Desktop under Settings &gt; Resources.

You do **not** need to install Python, uv, Bun, or any other tooling manually. The `npx learnhouse dev` command handles all dependency installation automatically.

## Setup Steps

### 1. Clone the Repository and Start Development

```bash
git clone https://github.com/learnhouse/learnhouse && cd learnhouse && npx learnhouse dev
```

That single command handles everything:

- **Starts backing services** -- PostgreSQL and Redis are launched via Docker Compose.
- **Installs dependencies** -- Python dependencies are installed via `uv` and JavaScript dependencies via `bun`, all automatically.
- **Starts the API** -- The FastAPI backend starts on port 1338 with hot reload.
- **Starts the frontend** -- The Next.js development server starts with `--turbopack` and hot reload.
- **Starts the collaboration server** -- The Hocuspocus collaboration server starts via `tsx watch`.

All services are coordinated automatically so you do not need to manage them individually.

## Accessing the Application

Once `npx learnhouse dev` is running, you can access:

| Service | URL |
| --- | --- |
| Frontend | [http://localhost:3000](http://localhost:3000) |
| API | [http://localhost:1338](http://localhost:1338) |
| API Documentation (Swagger) | [http://localhost:1338/docs](http://localhost:1338/docs) |

The Swagger UI at `/docs` is only available in development mode. Production instances do not expose the interactive API documentation.

## Stopping the Environment

Press `Ctrl+C` in the terminal where `npx learnhouse dev` is running to stop all services.

## Troubleshooting

- **Port conflicts** -- Make sure ports 3000 and 1338 are not in use by other applications.
- **Docker not running** -- Ensure the Docker daemon is started before running `npx learnhouse dev`.
- **Dependency issues** -- The CLI installs all dependencies automatically. If you encounter issues, try deleting `node_modules` and `.venv` directories and re-running `npx learnhouse dev`.

---

# Contribution Guidelines
URL: https://docs.learnhouse.app/developers/contributing/guidelines

This page outlines the workflow and standards for contributing to LearnHouse.

## Workflow

### 1. Fork and Clone

Fork the [LearnHouse repository](https://github.com/learnhouse/learnhouse) on GitHub, then clone your fork:

```bash
git clone https://github.com/YOUR_USERNAME/learnhouse.git
cd learnhouse
```

### 2. Create a Feature Branch

Always create a new branch for your changes. Use a descriptive branch name:

```bash
git checkout -b feature/your-feature-name
```

Branch naming conventions:

- `feature/` -- New features or enhancements
- `fix/` -- Bug fixes
- `docs/` -- Documentation changes
- `refactor/` -- Code refactoring without behavior changes

### 3. Make Your Changes

Develop your changes locally using the [development environment](/developers/contributing/dev-environment). Keep commits focused and atomic.

When adding or updating dependencies:

- **Frontend** -- Use `bun` to manage JavaScript/TypeScript dependencies (e.g., `bun add <package>`).
- **Backend** -- Use `uv` to manage Python dependencies (e.g., `uv add <package>`).

### 4. Submit a Pull Request

Push your branch to your fork and open a pull request against the `main` branch of the LearnHouse repository:

```bash
git push origin feature/your-feature-name
```

In your pull request description:

- Explain **what** your change does and **why** it is needed.
- Reference any related [GitHub issues](https://github.com/learnhouse/learnhouse/issues).
- Include screenshots or recordings for UI changes.

## Code Style

### Frontend (TypeScript / React)

- Use **TypeScript** for all new code.
- Follow existing patterns in the codebase for component structure and naming.
- Use functional components with hooks.
- Format code consistently -- the project includes configuration for code formatters.

### Backend (Python)

- Follow **PEP 8** conventions.
- Use type hints for function parameters and return values.
- Write clear docstrings for public functions and classes.
- Keep functions focused and concise.

## Testing

- Test your changes locally before submitting a pull request.
- Verify that existing functionality is not broken by your changes.
- For new features, include tests where applicable.

## Review Process

After submitting a pull request:

1. A maintainer will review your code and may request changes.
2. Address any feedback by pushing additional commits to your branch.
3. Once approved, a maintainer will merge your pull request.

## Reporting Issues

If you find a bug or have a feature request, please [open an issue](https://github.com/learnhouse/learnhouse/issues/new) on GitHub. Include as much detail as possible: steps to reproduce, expected behavior, actual behavior, and any relevant logs or screenshots.

---

# Enterprise Edition
URL: https://docs.learnhouse.app/enterprise

The LearnHouse Enterprise Edition (EE) is a commercially licensed extension of the open-source platform. It includes additional features designed for organizations that need advanced identity management, compliance tooling, and support for industry-standard learning content formats.

## Licensing

The Enterprise Edition is available under a separate **EE license**. It is not covered by the open-source license that governs the core platform.

- **Self-hosted** — The EE features are included in the codebase under `apps/api/ee/` but are locked behind an Enterprise license. You need a valid license key to activate them.
- **LearnHouse Cloud** — Some EE features (like Payments) are available on lower-tier plans. Others (SSO, SCORM, Audit Logs) require an Enterprise plan.

Interested in the Enterprise Edition? Visit [learnhouse.app](https://www.learnhouse.app) to learn more about pricing and licensing.

## Enterprise Features

- **[Single Sign-On (SSO)](/enterprise/sso)** — Authenticate users through external identity providers like WorkOS, Okta, Auth0, Keycloak, or any SAML/OIDC-compatible provider.
- **[Audit Logs](/enterprise/audit-logs)** — A full audit trail of all platform activity for compliance and security monitoring, with filtering and CSV export.
- **[SCORM](/enterprise/scorm)** — Import and run SCORM 1.2 and 2004 learning packages from authoring tools like Articulate Storyline and Adobe Captivate.

---

# Audit Logs
URL: https://docs.learnhouse.app/enterprise/audit-logs

Audit logs provide a detailed record of all actions taken on the platform, giving administrators full visibility into who did what and when. This is essential for compliance, security monitoring, and troubleshooting.

Audit logs require an Enterprise plan.

## What's Captured

Every mutation (create, update, delete) on the platform is recorded with the following details:

| Field | Description |
|---|---|
| User | Who performed the action (username and ID). |
| Action | The HTTP method (POST, PUT, DELETE, PATCH). |
| Resource | What was affected (e.g., `/courses`, `/users`). |
| Resource ID | The specific item that was modified. |
| Status code | The HTTP response status. |
| IP address | The origin of the request. |
| Timestamp | When the action occurred. |
| Payload | The request body (with sensitive data scrubbed). |

## Sensitive Data Handling

Audit logs automatically scrub sensitive fields from request payloads before storing them. Fields like `password`, `token`, `secret`, and similar keys are redacted to prevent sensitive data from appearing in logs.

## Filtering & Search

You can filter audit logs by:

- User (ID, username, or full name)
- Action type
- Resource type and ID
- HTTP status code
- IP address
- Date range

## CSV Export

Audit logs can be exported as CSV files for offline analysis, compliance reporting, or integration with external SIEM tools.

## Performance

Audit log entries are buffered in Redis and flushed to the database in batches every 60 seconds. This ensures that logging does not impact platform performance, even under heavy usage.

---

# SCORM
URL: https://docs.learnhouse.app/enterprise/scorm

SCORM support requires an Enterprise plan.

LearnHouse supports importing SCORM (Sharable Content Object Reference Model) packages — the industry standard for e-learning content. Import content from authoring tools like Articulate Storyline, Adobe Captivate, or iSpring and run it directly within your courses.

## Supported Versions

- **SCORM 1.2** — The most widely supported version.
- **SCORM 2004** — Newer version with enhanced sequencing.

## Importing Packages

1. Upload a SCORM `.zip` package to a course.
2. LearnHouse analyzes the package and detects the version, title, and SCOs.
3. Assign SCOs to chapters and import — each SCO becomes a course activity.

You can also import a package as a new course, automatically creating the course structure from the package contents.

## Tracking

Imported SCORM content reports progress back to LearnHouse, including completion status, scores, time spent, and bookmarking for resume support.

---

# Single Sign-On (SSO)
URL: https://docs.learnhouse.app/enterprise/sso

LearnHouse supports enterprise Single Sign-On, allowing organizations to authenticate users through their existing identity provider. This means users can log in with their company credentials without creating a separate LearnHouse account.

SSO requires an Enterprise plan.

## Supported Providers

- **WorkOS** — Full implementation with admin portal support.
- **Okta** — OIDC-based authentication.
- **Auth0** — OIDC-based authentication.
- **Keycloak** — Self-hosted identity provider support.
- **Custom SAML** — Connect any SAML-compatible identity provider.
- **Custom OIDC** — Connect any OIDC-compatible identity provider.

## How SSO Works

1. An admin configures SSO in the organization settings, selecting a provider and entering the required credentials.
2. When a user visits the login page, they see an SSO login option if SSO is enabled for that organization.
3. Clicking the SSO button redirects the user to the identity provider's login page.
4. After authenticating with the IdP, the user is redirected back to LearnHouse with an active session.

## User Provisioning

When a user logs in via SSO for the first time, LearnHouse can automatically create their account using profile data from the identity provider:

- **First name, last name, and email** are mapped from the IdP.
- **Avatar** is imported if available.
- **Default role** is assigned based on the SSO configuration (e.g., all new SSO users get the Student role).

Existing users whose email matches are linked automatically — no duplicate accounts are created.

## Configuration Options

| Option | Description |
|---|---|
| Provider | Which identity provider to use. |
| Email domain | Restrict SSO to specific email domains. |
| Auto-provisioning | Automatically create accounts for new SSO users. |
| Default role | Role assigned to newly provisioned users. |
| Admin portal | Some providers (like WorkOS) offer an admin portal for managing the connection directly. |

---

# Getting Started
URL: https://docs.learnhouse.app/getting-started

Welcome to LearnHouse — an open-source learning management system for creating and delivering modern educational content.

This section will help you go from zero to a working LearnHouse setup, whether you choose our managed cloud platform or a self-hosted deployment.

## What you will learn

- **[Quickstart](/getting-started/quickstart)** — Get up and running in minutes with LearnHouse Cloud or the self-hosted CLI.
- **[Cloud vs Self Hosting](/getting-started/cloud-vs-self-hosting)** — Understand the trade-offs so you can pick the right deployment model.
- **[Key Concepts](/getting-started/key-concepts)** — Learn the core building blocks: organizations, courses, activities, collections, trails, and the editor.

If you already know how you want to deploy, jump straight to the [Quickstart](/getting-started/quickstart).

## Next steps

Once you have a running instance and understand the basics, explore the rest of the documentation:

- [Platform Guide](/platform) — Deep dive into courses, the editor, AI features, and user management.
- [Self Hosting](/self-hosting) — Configuration, content storage, AI setup, and organization hosting modes.
- [Developers](/developers) — Architecture overview, API reference, and contributing guide.

---

# Cloud vs Self Hosting
URL: https://docs.learnhouse.app/getting-started/cloud-vs-self-hosting

LearnHouse is open-source software. You can use the managed **LearnHouse Cloud** platform or deploy the **Community Edition** on your own infrastructure. This page explains the differences so you can make an informed choice.

## Comparison

|                              | ☁️ LearnHouse Cloud                                | 🖥️ Self Hosting                 |
| ---------------------------- | ------------------------------------------------- | -------------------------------- |
| 🌍 Worldwide CDN             | ✅ Included                                        | ⚙️ Manual setup + additional cost |
| 🔄 Weekly updates            | ✅ Automatic                                       | 🔧 Manual                        |
| 🛠️ Maintenance               | ✅ Managed by the LearnHouse team                  | 👤 Your responsibility            |
| 🔒 Security patches          | ✅ Applied automatically                           | 🔧 Manual                        |
| 📊 Threat & uptime monitoring | ✅ Included                                       | ❌ Not included                   |
| 🔐 SSL certificate           | ✅ Included                                        | 🔧 Manual                        |
| 💾 Continuous backups         | ✅ Included                                        | ⚙️ Manual + additional cost       |
| 📈 Scalability               | ✅ Automatic                                       | ⚙️ Depends on your provider       |
| 🖥️ Direct SSH & DB access    | ❌ Not available                                   | ✅ Full access                    |
| 🎧 Product support           | ✅ Email support                                   | 👥 Community support              |
| 💚 Where your money goes     | ✅ Supporting the team and funding new features     | 🏢 Third-party hosting companies  |

## ☁️ When to choose LearnHouse Cloud

**Best for:** teams, organizations, and businesses that want to focus on content and learners — not infrastructure.

- **Launch in minutes** — no servers to provision, no DevOps overhead. Your team can start building courses immediately.
- **Zero-maintenance operations** — updates, security patches, SSL certificates, and backups are handled automatically by the LearnHouse team.
- **Enterprise-grade reliability** — global CDN, threat monitoring, uptime guarantees, and automatic scaling out of the box.
- **Priority support** — dedicated email support with faster response times for production issues.
- **Invest in the product** — your subscription directly funds development of new features and improvements for the entire LearnHouse ecosystem.

LearnHouse Cloud is the recommended option for most organizations. It eliminates operational complexity and lets your team focus entirely on creating great learning experiences.

## 🖥️ When to choose Self Hosting

**Best for:** enterprises, institutions, and teams with strict infrastructure requirements and dedicated engineering resources.

- **Full data sovereignty** — host on your own infrastructure with complete control over where data lives. Ideal for organizations with data residency mandates.
- **Regulatory compliance** — meet on-premises hosting requirements for HIPAA, SOC 2, internal security policies, or government regulations.
- **Deep infrastructure access** — direct SSH, database access, and full control over networking, storage, and compute resources.
- **Custom integrations** — connect to internal systems, private networks, SSO providers, and proprietary tooling without restrictions.
- **Dedicated engineering teams** — organizations with DevOps or platform engineering teams that prefer to own their deployment pipeline.

Self hosting requires your team to manage updates, backups, security patches, and scaling. Make sure you have the engineering capacity before choosing this path.

Both options give you access to the same core feature set. Self-hosted instances can be upgraded at any time by pulling the latest release from the [Community Edition repository](https://github.com/learnhouse/community-edition).

## Next steps

- Ready to get started? Head to the [Quickstart](/getting-started/quickstart).
- Want to try the cloud platform? Visit [learnhouse.app](https://learnhouse.app) to create your account.
- Need help configuring a self-hosted instance? See the [Self Hosting Guide](/self-hosting/hosting-guide).

---

# Key Concepts
URL: https://docs.learnhouse.app/getting-started/key-concepts

This page introduces the core building blocks of LearnHouse. Understanding these concepts will help you navigate the platform and structure your content effectively.

## Organizations

An **organization** is the top-level tenant in LearnHouse. Each organization has its own courses, users, settings, and branding. A single LearnHouse instance can host multiple organizations, making it well-suited for multi-tenant deployments such as schools, companies, or platform providers.

## Courses

A **course** is the primary unit of content. Every course contains one or more **chapters**, and each chapter contains one or more **activities**. Think of a course as a structured curriculum that guides learners from start to finish.

## Activities

An **activity** is a single piece of learning content inside a chapter. LearnHouse supports several activity types:

- **Dynamic pages** — Rich, block-based pages built with the LearnHouse editor.
- **Videos** — Hosted video content with playback tracking.
- **Documents** — PDF and other document uploads for reference material.
- **Quizzes** — Assessments that test learner understanding and feed into progress tracking.

## Collections

A **collection** groups related courses together. Collections make it easy for learners to discover all courses on a particular topic and for instructors to present a structured learning path across multiple courses.

## Trails

A **trail** tracks a learner's progress through a course. It records completed activities, quiz results, and overall advancement. Teachers can use trail data to monitor student performance, while learners can see their own progress and pick up where they left off.

## Editor

LearnHouse includes a block-based **WYSIWYG editor** for authoring dynamic page activities. The editor supports a variety of block types — text, headings, images, code, callouts, embeds, and more — and offers real-time collaborative editing so multiple authors can work on the same page simultaneously.

For a deeper look at each of these features, explore the [Platform Guide](/platform) and the [Features](/features) documentation.

---

# Quickstart
URL: https://docs.learnhouse.app/getting-started/quickstart

There are two ways to start using LearnHouse: the managed **LearnHouse Cloud** or a **self-hosted** deployment. Pick the path that suits your needs.

---

## Option A — LearnHouse Cloud

The fastest way to get started. No infrastructure to manage.

1. **Sign up** — Create an account at [learnhouse.app](https://learnhouse.app).
2. **Create an organization** — After signing in, create your first organization. This is the top-level container for all of your courses, users, and settings.
3. **Create your first course** — Inside the organization dashboard, click **New Course**, give it a title, and start adding chapters and activities.

You are ready to go. LearnHouse Cloud handles hosting, updates, backups, and SSL for you.

Not sure whether Cloud or self-hosting is right for you? See the [Cloud vs Self Hosting](/getting-started/cloud-vs-self-hosting) comparison.

---

## Option B — Self-Hosted

Run LearnHouse on your own infrastructure using the LearnHouse CLI. You'll need [Docker](https://docs.docker.com/get-docker/) and [Node.js](https://nodejs.org/) (v18+) installed.

### 1. Run the setup wizard

```bash
npx learnhouse@latest setup
```

The interactive wizard walks you through domain configuration, database setup, admin account creation, and optional features (AI, email, storage, OAuth).

### 2. Start LearnHouse

```bash
npx learnhouse start
```

Your instance will be available at `http://localhost` (or the domain you configured during setup).

### 3. Manage your instance

```bash
npx learnhouse stop     # Stop all services
npx learnhouse logs     # Stream logs
npx learnhouse backup   # Backup database
npx learnhouse doctor   # Run diagnostics
```

For detailed installation options, see the [Quick Install](/self-hosting/installation/quick-install) guide. For environment variables and configuration, see [Configuration](/self-hosting/configuration).

---

## What to do next

- Familiarize yourself with the [Key Concepts](/getting-started/key-concepts) — organizations, courses, activities, and more.
- Explore the [Editor](/platform/editor) to see how content authoring works.
- Set up [AI features](/self-hosting/configuration/ai-setup) if you want built-in AI assistance for students and teachers.

---

# Platform Overview
URL: https://docs.learnhouse.app/platform

This section covers all the features and capabilities of the LearnHouse platform. Whether you are a student, teacher, or administrator, you will find detailed documentation on every aspect of the system here.

## Sections

- **[Courses](/platform/courses)** — Create and manage courses, chapters, activities, collections, and trails.
- **[Editor](/platform/editor)** — A block-based WYSIWYG editor for building rich course content.
- **[Assignments](/platform/assignments)** — Assessable tasks with grading, submissions, and auto-graded code execution.
- **[Playgrounds](/platform/playgrounds)** — Interactive code environments for hands-on practice and experimentation.
- **[Discussions](/platform/discussions)** — Community discussion threads with comments, voting, and reactions.
- **[Boards](/platform/boards)** — Real-time collaborative documents for group work and brainstorming.
- **[Podcasts](/platform/podcasts)** — Audio content with episode management and streaming.
- **[Certifications](/platform/certifications)** — Automatic certificate generation on course completion.
- **[Analytics](/platform/analytics)** — Engagement tracking and usage metrics for your organization.
- **[Search](/platform/search)** — Find courses, collections, and users across your organization.
- **[Payments](/platform/payments)** — Sell courses with Stripe, manage offers, subscriptions, and enrollments.
- **[AI](/platform/ai)** — Context-aware AI assistant for students and teachers.
- **[Users & Access](/platform/users)** — User management, roles, permissions, and authentication.
- **[Organizations](/platform/organizations)** — Multi-tenant organization management, branding, and settings.

---

# AI
URL: https://docs.learnhouse.app/platform/ai

LearnHouse includes a context-aware AI assistant powered by OpenAI. The AI understands the content of your courses and activities, enabling it to provide relevant, targeted assistance to both students and teachers.

## How It Works

The AI assistant operates at the course and activity level. It reads the content of the current course or activity to provide contextually accurate responses. This means answers are grounded in your actual teaching material rather than generic knowledge.

AI features require an OpenAI API key to be configured in your organization settings. See [Organization Settings](/platform/organizations/settings) for details.

## Learn More

- [AI for Students](/platform/ai/for-students) — How students use the AI assistant during learning.
- [AI for Teachers](/platform/ai/for-teachers) — How teachers leverage AI for content creation and course management.

---

# AI for Students
URL: https://docs.learnhouse.app/platform/ai/for-students

Students can interact with the LearnHouse AI assistant while working through course content. The AI acts as an on-demand tutor that understands the material being studied.

## Context-Aware Chat

When a student opens the AI chat from within a course or activity, the assistant automatically has context about:

- The current activity content
- The broader course material
- The chapter structure and related topics

This allows students to ask questions and receive answers that are directly relevant to what they are studying, rather than generic responses.

## Example Use Cases

- **Clarifying concepts** — Ask the AI to explain a topic from the current lesson in different terms.
- **Summarizing content** — Request a summary of a long activity or chapter.
- **Practice questions** — Ask the AI to generate practice questions based on the current material.
- **Deeper exploration** — Explore related topics that build on the course content.

---

# AI for Teachers
URL: https://docs.learnhouse.app/platform/ai/for-teachers

The LearnHouse AI assistant helps teachers create and manage course content more efficiently.

## Content Creation Assistance

Teachers can use the AI to accelerate the course-building process:

- **Draft generation** — Generate initial drafts for activity content based on a topic or outline.
- **Content improvement** — Refine existing content for clarity, tone, or completeness.
- **Quiz creation** — Generate quiz questions based on the course material.

## Course Management

Beyond content creation, the AI can assist with organizing and structuring courses:

- Suggest how to break a topic into chapters and activities.
- Identify gaps in course coverage.
- Recommend improvements based on the existing content structure.

## Getting Started

The AI assistant is available from the course editor interface. Make sure your organization has an OpenAI API key configured in the [organization settings](/platform/organizations/settings).

---

# Analytics
URL: https://docs.learnhouse.app/platform/analytics

LearnHouse provides analytics to help administrators and teachers understand how learners engage with content. Analytics track user activity, course engagement, and platform usage.

Analytics must be enabled in your [Organization Settings](/platform/organizations/settings) to be available.

## What's Tracked

- **User engagement** — Activity views, time spent, and interaction patterns.
- **Course analytics** — Which courses and activities are most popular and how students progress through them.
- **Organization-level metrics** — Overall platform usage and growth trends.

## How Analytics Work

Events are tracked as users interact with the platform — viewing activities, completing courses, submitting assignments, and more. These events are aggregated into dashboards accessible from the admin panel.

## Accessing Analytics

Administrators can access the global analytics dashboard from the organization admin panel. Analytics data is scoped to the current organization, so each organization sees only its own data.

Analytics uses event caching for performance. Data may take a short time to reflect the most recent activity.

---

# Assignments
URL: https://docs.learnhouse.app/platform/assignments

Assignments let teachers create assessable tasks within courses. Students submit their work, and teachers can review and grade submissions individually or in bulk.

## How Assignments Work

Each assignment is linked to a course activity and can contain one or more tasks. Students complete tasks, upload files, or write code, and then submit their work for grading.

Assignments must be enabled in your [Organization Settings](/platform/organizations/settings) to be available.

## Key Features

- **Multi-task assignments** — Break assignments into individual tasks, each with its own submission and grade.
- **File uploads** — Students can attach files as part of their submission.
- **Submission tracking** — Teachers see submission status for each student and task.
- **Grading** — Grade individual tasks or entire assignments. Scores are recorded in the student's [Trail](/platform/courses/trails).

## Learn More

- [Grading & Submissions](/platform/assignments/grading) — How the grading workflow works.
- [Code Execution](/platform/code-execution) — Auto-graded coding assignments with multi-language support.

---

# Grading & Submissions
URL: https://docs.learnhouse.app/platform/assignments/grading

LearnHouse provides a straightforward grading workflow for teachers to review and score student submissions.

## Submission Flow

1. A teacher creates an assignment with one or more tasks.
2. Students complete each task and submit their work (text, files, or code).
3. The teacher reviews submissions and assigns grades per task.
4. Grades are aggregated at the assignment level and reflected in the student's Trail.

## Grading Options

- **Task-level grading** — Assign a score to each individual task within an assignment.
- **Assignment-level grading** — Review and finalize the overall assignment grade.
- **Bulk review** — View all submissions for a task across students to compare and grade efficiently.

## Submission Status

Each submission is tracked with a status so teachers can see at a glance which students have submitted, which are pending, and which have been graded.

Submissions are tied to the student's Trail, so all grading data contributes to the overall course progress view.

---

# Boards
URL: https://docs.learnhouse.app/platform/boards

Boards are collaborative documents that multiple users can edit together in real time. They use the same block-based editor as course activities but are designed for freeform collaboration outside the course structure.

Boards must be enabled in your [Organization Settings](/platform/organizations/settings) to be available.

## How Boards Work

A board is a shared document with real-time synchronization powered by Yjs. Multiple users can view and edit a board simultaneously, with changes synced instantly across all participants.

## Key Features

- **Real-time collaboration** — Multiple users can edit a board at the same time with live cursor tracking and instant sync.
- **Role-based access** — Board members can be assigned roles: **Owner**, **Editor**, or **Viewer**.
- **Block-based editing** — Boards use the same rich block editor as course activities, supporting text, media, and advanced blocks.
- **Member management** — Board owners can invite members and manage their access levels.

## Use Cases

- **Group projects** — Students collaborate on shared documents for team assignments.
- **Meeting notes** — Teachers and staff maintain shared notes for planning and coordination.
- **Brainstorming** — Teams use boards as collaborative whiteboards for idea generation.

---

# Certifications
URL: https://docs.learnhouse.app/platform/certifications

LearnHouse can generate certificates when students complete a course, providing formal recognition of their learning achievements.

## How Certifications Work

When a student completes all activities in a course, a certification record is created and linked to their profile. Teachers and administrators can manage certifications at the course level.

## Key Features

- **Automatic generation** — Certificates are generated when a student's Trail shows full course completion.
- **Course-level configuration** — Each course can have certifications enabled or disabled.
- **Certificate retrieval** — Students can view and access their earned certificates from their profile.
- **Verification** — Each certificate has a unique identifier that can be used for verification.

## Use Cases

- **Professional development** — Issue certificates for compliance training or continuing education.
- **Academic programs** — Provide completion certificates for course series or learning paths.
- **Skill validation** — Give students a shareable credential they can reference externally.

---

# Code Execution
URL: https://docs.learnhouse.app/platform/code-execution

LearnHouse integrates with Judge0 to provide sandboxed code execution for coding assignments. Students can write and run code directly in the platform, and teachers can define test cases for automatic grading.

## Supported Languages

The code execution engine supports 30+ programming languages including Python, JavaScript, Java, C, C++, Go, Rust, Ruby, and many more.

## How It Works

1. A teacher creates an assignment task with one or more test cases (input/output pairs).
2. Students write their solution in the built-in code editor.
3. On submission, the code is executed against all test cases in a sandboxed environment.
4. Results are reported per test case — pass/fail, execution time, and memory usage.

## Test Cases

Each test case defines:

- **Input** — The standard input provided to the program.
- **Expected Output** — The output the program should produce.

The system runs the student's code against each test case and compares the actual output to the expected output.

Code execution requires a Judge0 instance to be configured. See the [Self-Hosting Configuration](/self-hosting/configuration) for setup details.

## Batch Execution

For assignments with multiple test cases, the platform executes all test cases in a single batch request, providing a comprehensive results summary that shows which tests passed and which failed.

---

# Courses
URL: https://docs.learnhouse.app/platform/courses

Courses are the core content unit in LearnHouse. Each course is made up of chapters, and each chapter contains activities that students work through.

<br/>

## Activity Types

LearnHouse supports several activity types to accommodate different teaching styles:

- **Dynamic Pages** — Rich WYSIWYG content built with the block-based editor.
- **Videos** — Upload video files directly or embed from YouTube and other external sources.
- **Documents** — PDF documents displayed with a built-in viewer.
- **Quizzes** — Interactive assessments to test student understanding.

## Getting Started

To create a course, navigate to your organization dashboard and select **Create Course**. From there you can add chapters, populate them with activities, and publish when ready.

Courses can be grouped into [Collections](/platform/courses/collections) for better organization, and student progress is tracked via [Trails](/platform/courses/trails).

---

# Chapters and Activities
URL: https://docs.learnhouse.app/platform/courses/chapters-and-activities

Courses in LearnHouse follow a clear hierarchy: **Course → Chapters → Activities**. This structure keeps content organized and gives students a logical path through the material.

## Chapters

Chapters are the top-level groupings within a course. Use them to break your course into modules, units, or topics. You can reorder chapters at any time from the course editor.

## Activities

Activities are the individual pieces of content within a chapter. Each activity has a specific type that determines how content is presented to students.

### Dynamic Pages

Dynamic Pages use the built-in block-based editor to create rich, interactive content. You can combine text, images, code blocks, callouts, embeds, and more in a single page. This is the most flexible activity type.

### Videos

Video activities let you upload video files directly to LearnHouse or embed videos from YouTube and other external platforms. Uploaded videos are served through LearnHouse's media pipeline.

### Documents

Document activities display PDF files using a built-in viewer. Upload a PDF and students can read it directly within the platform without downloading.

### Quizzes

Quiz activities provide interactive assessments. Teachers can create questions and review student results. Quiz data is recorded in the student's [Trail](/platform/courses/trails) for progress tracking.

You can mix and match activity types within a single chapter to create a varied learning experience.

---

# Collections
URL: https://docs.learnhouse.app/platform/courses/collections

Collections let you group related courses together, making it easier for students to discover and navigate structured learning paths.

## Use Cases

- **Learning Paths** — Arrange courses in a recommended sequence so students know what to take and in what order.
- **Curricula** — Bundle all courses for a program, department, or certification into a single collection.
- **Categorization** — Organize courses by topic, difficulty level, or audience.

## How Collections Work

A collection is simply a named group of courses. Each course can belong to one or more collections. When students browse a collection, they see all the included courses in the order you define.

To create a collection, go to your organization dashboard and select **Collections**. From there you can name the collection, add courses, and arrange their order.

---

# Trails
URL: https://docs.learnhouse.app/platform/courses/trails

Trails let students track their progress through courses, providing a clear view of what they have completed and what is left.

<br/>

## How Trails Work

When a student starts a course, a Trail is automatically created for them. As they work through activities, their progress is recorded — including activity completions and quiz submissions.

Students can view their Trail at any time to see:

- Which activities they have completed
- Quiz results and scores
- Overall course progression

This encourages self-directed learning and helps students stay on track.

A Trail is created automatically when a student starts a course. All quiz submissions and progression data are recorded in the Trail.

---

# Discussions
URL: https://docs.learnhouse.app/platform/discussions

Discussions provide a community space within your organization where students and teachers can ask questions, share ideas, and collaborate outside of course content.

## How Discussions Work

Discussions are organized within communities tied to your organization. Users can create threads, reply with comments, vote on posts and comments, and react with emojis.

Discussions must be enabled in your [Organization Settings](/platform/organizations/settings) to be available.

## Key Features

- **Threaded conversations** — Create discussion topics and reply with comments for focused conversations.
- **Voting** — Upvote discussions and comments to surface the most helpful content.
- **Reactions** — React to discussions with emojis to provide quick feedback.
- **Pinning & locking** — Teachers and admins can pin important discussions or lock threads that have been resolved.
- **Labels** — Categorize discussions with labels for easy filtering and discovery.

## Learn More

- [Comments & Reactions](/platform/discussions/comments) — Engaging with discussion threads.

---

# Comments & Reactions
URL: https://docs.learnhouse.app/platform/discussions/comments

Comments and reactions are the primary ways users engage with discussion threads.

## Comments

Any member of the organization can reply to a discussion with a comment. Comments support text content and are displayed in chronological order within the thread.

### Voting on Comments

Comments can be upvoted by other users. This helps surface the most helpful or relevant replies within a discussion. Vote counts are displayed alongside each comment.

## Reactions

Reactions let users respond to discussions quickly with emoji reactions. Multiple users can add the same reaction, and the count is displayed on the discussion.

## Moderation

Teachers and admins have additional controls over discussions:

- **Pin** a discussion to keep it at the top of the list.
- **Lock** a discussion to prevent further comments.
- **Delete** comments or discussions that violate guidelines.

---

# Editor
URL: https://docs.learnhouse.app/platform/editor

LearnHouse includes a block-based WYSIWYG editor for creating course content. The editor provides a Notion-like experience where you build pages by stacking and arranging content blocks.

## Key Features

- **Block-based editing** — Each piece of content (paragraph, image, code snippet) is an independent block that you can move, duplicate, or delete.
- **Rich formatting** — Full text formatting including bold, italic, links, and inline code.
- **Drag and drop** — Rearrange blocks by dragging them into the desired position.
- **Slash commands** — Type `/` to quickly insert any block type.

## Learn More

- [Available Blocks](/platform/editor/blocks) — See all the block types you can use.

---

# Blocks
URL: https://docs.learnhouse.app/platform/editor/blocks

Paragraph,
  TextHOne,
  TextHTwo,
  TextHThree,
  TextHFour,
  TextHFive,
  TextHSix,
  ListBullets,
  ListNumbers,
  CodeBlock,
  Image,
  Video,
  SpeakerHigh,
  FilePdf,
  Globe,
  Browser,
  Question,
  Terminal,
  Sparkle,
  MathOperations,
  Cards,
  FlowArrow,
  Tag,
  Info,
  Warning,
  Table,
  Minus,
} from '@phosphor-icons/react/dist/ssr'

export const Block = ({ icon: Icon, name, description }) => (
  <li style={{ display: 'flex', alignItems: 'center', gap: 8, listStyle: 'none' }}>
    
    <span><strong>{name}</strong> — {description}</span>
  </li>
)

# Blocks

The LearnHouse editor supports a wide range of block types for building rich course content. You can insert any block by typing `/` and selecting from the menu.

## Text Blocks

<ul style={{ listStyle: 'none', padding: 0, display: 'flex', flexDirection: 'column', gap: 8 }}>
  
  
  
  
  
  
  
  
  
  
</ul>

## Media Blocks

<ul style={{ listStyle: 'none', padding: 0, display: 'flex', flexDirection: 'column', gap: 8 }}>
  
  
  
  
  
  
</ul>

## Interactive Blocks

<ul style={{ listStyle: 'none', padding: 0, display: 'flex', flexDirection: 'column', gap: 8 }}>
  
  
  
  
  
  
</ul>

## UI Blocks

<ul style={{ listStyle: 'none', padding: 0, display: 'flex', flexDirection: 'column', gap: 8 }}>
  
  
  
  
  
</ul>

## Using Blocks

Each block can be individually moved, duplicated, or deleted. Click the handle on the left side of a block to drag it to a new position, or use the block menu for additional options.

---

# Organizations
URL: https://docs.learnhouse.app/platform/organizations

Organizations are the top-level tenant in LearnHouse. Every piece of content, every user, and every setting is scoped to an organization.

## What an Organization Contains

Each organization has its own:

- **Courses and collections** — All educational content is owned by the organization.
- **Users** — Members belong to an organization and are assigned roles within it.
- **Settings** — Branding, AI configuration, signup rules, and more are configured per-organization.

## Learn More

- [Multi-Tenancy](/platform/organizations/multi-tenancy) — Running single or multiple organizations on one LearnHouse instance.
- [Settings](/platform/organizations/settings) — Configuring your organization's preferences and features.

---

# Multi-Tenancy
URL: https://docs.learnhouse.app/platform/organizations/multi-tenancy

Multi-tenancy is an **Enterprise** feature. It is not available on the open-source or standard plans.

LearnHouse supports running one or more organizations on a single instance. This multi-tenant architecture lets you serve different groups from the same deployment.

## Single Organization (Default)

By default, LearnHouse runs with a single organization. This is the simplest setup and is suitable for most deployments where one team, school, or company uses the platform.

## Multi-Organization

In multi-org mode, a single LearnHouse instance hosts multiple independent organizations. Each organization operates as if it were its own separate platform:

- Courses, users, and settings are fully scoped to each organization.
- Data is stored in a shared database but isolated by organization ID.
- Each organization can have its own branding and configuration.

Multi-org mode is useful for platforms that serve multiple schools, departments, or clients from a centralized deployment.

## Data Isolation

All database queries are scoped by `org_id`, ensuring that one organization cannot access another's data. Users, courses, collections, trails, and settings are all partitioned at the organization level.

---

# Organization Settings
URL: https://docs.learnhouse.app/platform/organizations/settings

Each organization in LearnHouse has its own configurable settings that control branding, features, and access.

## Branding

Customize the look and feel of your organization:

- Organization name and description
- Logo and favicon
- Color scheme and theme preferences

## AI Configuration

Configure the AI assistant for your organization:

- Enable or disable AI features
- Set your OpenAI API key
- Adjust AI behavior and context settings

An OpenAI API key is required for AI features to function. Without one, the AI assistant will be unavailable to students and teachers.

## User and Access Settings

Control how users interact with your organization:

- **Signup mechanism** — Choose between open signup and invite-only registration.
- **User limits** — Set maximum user counts if needed.
- **Default role** — Configure the default role assigned to new users.

## Managing Settings

Organization settings are accessible to Admin users from the organization dashboard. Navigate to **Settings** to view and modify all available options.

---

# Payments
URL: https://docs.learnhouse.app/platform/payments

LearnHouse integrates with Stripe to let you sell courses and content directly from your platform. You can create offers, bundle courses into groups, and manage subscriptions and one-time purchases.

Payments is available on the **Standard plan** and above on LearnHouse Cloud. For self-hosted instances, it requires the **Enterprise Edition**. It must also be enabled in your [Organization Settings](/platform/organizations/settings).

## How Payments Work

1. Connect your Stripe account to your organization.
2. Create offers — either subscriptions or one-time purchases.
3. Assign courses or course bundles to each offer.
4. Students purchase access through a checkout flow powered by Stripe.
5. Enrollment is granted automatically on successful payment.

## Stripe Connect Modes

LearnHouse supports two ways to connect with Stripe:

- **Standard Mode** — You connect your own existing Stripe account via OAuth.
- **Express Mode** — LearnHouse creates a Stripe Express account on your behalf, simplifying onboarding.

## Learn More

- [Offers & Pricing](/platform/payments/offers) — Create and manage products with flexible pricing.
- [Groups & Bundles](/platform/payments/groups) — Bundle courses together for package deals.
- [Enrollments & Checkout](/platform/payments/enrollments) — How students purchase and gain access.

---

# Enrollments & Checkout
URL: https://docs.learnhouse.app/platform/payments/enrollments

Enrollments track student access to paid content. When a student completes a purchase, an enrollment record is created that grants them access to the associated courses.

## Checkout Flow

1. A student selects an offer from the storefront or course page.
2. They are redirected to a Stripe-hosted checkout page.
3. On successful payment, an enrollment is created automatically.
4. The student gains immediate access to the purchased courses.

## Enrollment Statuses

| Status | Description |
|---|---|
| Pending | Payment initiated but not yet confirmed. |
| Completed | One-time payment successful, access granted. |
| Active | Subscription is active, access granted. |
| Cancelled | Subscription cancelled, access revoked. |
| Failed | Payment failed. |
| Refunded | Payment refunded, access revoked. |

## Billing Portal

Students with active subscriptions can access a Stripe billing portal to manage their payment methods, view invoices, and cancel or update their subscriptions.

## Stripe Dashboard

Administrators can view an overview of charges, subscriptions, and customers directly from the LearnHouse admin panel without needing to log into Stripe separately.

---

# Groups & Bundles
URL: https://docs.learnhouse.app/platform/payments/groups

Groups let you bundle multiple courses together and sell them as a single package. When a student purchases an offer linked to a group, they get access to all courses in that group.

## How Groups Work

1. Create a group and give it a name.
2. Add courses to the group.
3. Link the group to one or more offers.
4. When a student purchases the offer, they are enrolled in all courses within the group.

## User Group Sync

Groups can be synced with user groups for automatic access provisioning. When a payment group is synced to a user group, students who purchase an offer linked to that group are automatically added to the corresponding user group, granting them access to all associated resources.

## Direct Resource Linking

If you don't need a group, you can also link individual courses directly to an offer. This is useful for selling single courses without creating a bundle.

---

# Offers & Pricing
URL: https://docs.learnhouse.app/platform/payments/offers

Offers are the products you sell to students. Each offer defines what students get, how much they pay, and whether the payment is recurring or one-time.

## Offer Types

- **Subscription** — Recurring payments that grant access as long as the subscription is active.
- **One-time purchase** — A single payment that grants permanent access.

## Pricing Options

- **Fixed price** — Set a specific amount in your chosen currency.
- **Customer choice** — Let students pay what they want (pay-what-you-want model).

## Offer Details

Each offer includes:

- **Name & description** — What the student is buying.
- **Benefits** — A list of what's included in the offer.
- **Amount & currency** — The price (e.g., $49 USD).
- **Public listing** — Whether the offer appears on your public storefront.
- **Linked resources** — Courses or groups that the offer grants access to.

## Public Storefront

Offers marked as public are displayed on your organization's storefront page. Each listing shows the offer details, included courses, and a purchase button that launches the Stripe checkout flow.

---

# Playgrounds
URL: https://docs.learnhouse.app/platform/playgrounds

Playgrounds are interactive code environments where users can write, run, and experiment with code directly in the browser. They can be created manually or generated by AI.

Playgrounds must be enabled in your [Organization Settings](/platform/organizations/settings) to be available.

## How Playgrounds Work

A playground provides an in-browser coding environment where users can write code, execute it, and see results in real time. Playgrounds support multiple programming languages through the Judge0 code execution engine.

## Key Features

- **AI-generated playgrounds** — Use AI to generate interactive playgrounds from a prompt or course context.
- **Multi-language support** — Write and execute code in 30+ programming languages.
- **Reactions** — Users can react to playgrounds to provide feedback.
- **Sharing** — Playgrounds can be shared with specific user groups or made available to the entire organization.
- **Multiple iterations** — Playgrounds support multiple response iterations, letting users refine and build on their work.

## Use Cases

- **Practice exercises** — Give students hands-on coding practice alongside course material.
- **Code demonstrations** — Teachers can create interactive examples that students can modify and run.
- **Experimentation** — Students can freely explore and test ideas in a sandboxed environment.

---

# Podcasts
URL: https://docs.learnhouse.app/platform/podcasts

Podcasts let you create and manage audio content within your organization. You can organize audio material into podcasts with individual episodes, providing an alternative content format alongside courses.

Podcasts must be enabled in your [Organization Settings](/platform/organizations/settings) to be available.

## How Podcasts Work

Each podcast acts as a container for related episodes. You create a podcast, add metadata like a name, description, and thumbnail, then populate it with episodes. Episodes are streamed to users with optimized audio delivery.

## Key Features

- **Episode management** — Add, edit, reorder, and remove episodes within a podcast.
- **Audio streaming** — Episodes are streamed with HTTP Range request support for efficient playback and seeking.
- **Deploy to Apple Podcasts & Spotify** — Publish your podcasts to Apple Podcasts and Spotify to reach a wider audience beyond your platform.
- **Metadata & discovery** — Each podcast and episode supports names, descriptions, and tags for easy browsing.
- **Thumbnails** — Upload custom artwork for podcasts and episodes.

## Use Cases

- **Lecture recordings** — Provide audio versions of lectures for on-the-go learning.
- **Supplementary material** — Share interviews, discussions, or expert commentary alongside course content.
- **Audio courses** — Build entire courses around audio content for topics that suit a listening format.

---

# Search
URL: https://docs.learnhouse.app/platform/search

LearnHouse includes a built-in search system that lets users find courses, collections, and other users across the organization.

## How Search Works

Search is scoped to the current organization. When a user enters a query, the system searches across:

- **Courses** — Match by course title, description, and content.
- **Collections** — Find collections by name or description.
- **Users** — Look up organization members by name or username.

Results are returned with pagination, displaying up to 50 results per page.

## Features

- **Organization-scoped** — Each organization's search results are isolated, ensuring users only see content from their own organization.
- **Cross-content search** — A single search query returns results across multiple content types.
- **Pagination** — Results are paginated for efficient browsing of large result sets.

---

# Users and Access
URL: https://docs.learnhouse.app/platform/users

LearnHouse provides a user management system with role-based access control. Each user belongs to an organization and is assigned a role that determines what they can see and do.

## Key Concepts

- **Users** — Individual accounts that can log in and interact with the platform.
- **Roles** — Each user has a role (Admin, Teacher/Staff, or Student) that defines their permissions.
- **Authentication** — Users authenticate via OAuth providers or standard credentials.

## Learn More

- [Roles and Permissions](/platform/users/roles-and-permissions) — Understand what each role can access.
- [Authentication](/platform/users/authentication) — Configure how users sign in and sign up.

---

# Authentication
URL: https://docs.learnhouse.app/platform/users/authentication

LearnHouse supports multiple authentication methods to fit different deployment scenarios.

## OAuth Providers

LearnHouse supports OAuth login with providers like Google, depending on your configuration.

## Signup Mechanisms

Organizations can control how new users join the platform:

- **Open signup** — Anyone can create an account and join the organization.
- **Invite-only** — Only users who receive an invitation can create an account.

The signup mechanism is configured per-organization in the [organization settings](/platform/organizations/settings).

Choose invite-only signup for private or internal deployments where you want to control exactly who has access.

## Session Management

Once authenticated, users maintain a session via JWT tokens. The backend issues an access token (8-hour expiry) and a refresh token (30-day expiry) that keep users signed in across page loads.

---

# Roles and Permissions
URL: https://docs.learnhouse.app/platform/users/roles-and-permissions

LearnHouse uses a role-based access control model. Every user within an organization is assigned one of three roles.

## Admin

Admins have full control over the organization. They can:

- Manage all courses, collections, and content
- Manage users and assign roles
- Configure organization settings (branding, AI, signup)
- Access all platform features

## Teacher / Staff

Teachers and staff members can create and manage educational content. They can:

- Create and edit courses, chapters, and activities
- View student Trails and quiz results
- Use the AI assistant for content creation
- Manage collections

Teachers cannot modify organization-level settings or manage other users' roles.

## Student

Students are the primary learners on the platform. They can:

- Browse and enroll in available courses
- Complete activities and quizzes
- View their own Trail and progress
- Interact with the AI assistant for learning support

Students cannot create or edit courses or access administrative features.

---

# Self-Hosting LearnHouse
URL: https://docs.learnhouse.app/self-hosting

LearnHouse can be self-hosted on your own infrastructure using the **LearnHouse CLI**. The CLI handles everything from initial setup to ongoing maintenance, including Docker Compose generation, environment file management, service orchestration, backups, and health checks.

## Quick Start

Make sure you have **Docker Engine 20.10+**, **Docker Compose 2.0+**, and **Node.js 18+** installed, then run:

```bash
npx learnhouse@latest setup
```

The interactive setup wizard will walk you through domain configuration, database settings, admin credentials, and optional features. Once complete, start all services:

```bash
npx learnhouse start
```

LearnHouse will be available at **http://localhost** (or your configured domain). Log in with the admin credentials you provided during setup.

The CLI generates `docker-compose.yml`, `.env`, and reverse proxy configuration for you. You do not need to write or maintain these files manually.

### Verify the installation

```bash
npx learnhouse doctor
```

### Common management commands

```bash
npx learnhouse stop       # Stop all services
npx learnhouse start      # Start all services
npx learnhouse logs       # Stream container logs
npx learnhouse config     # View current configuration
npx learnhouse backup     # Backup or restore the database
npx learnhouse doctor     # Diagnose issues
```

## Documentation

### [Installation](/self-hosting/installation)

System requirements, quick install steps, and the full CLI command reference.

### [Configuration](/self-hosting/configuration)

Environment variables, AI features, email delivery, content storage, and SSL/domain setup.

### [Maintenance](/self-hosting/maintenance)

Updates, backups, monitoring, and troubleshooting guides.

---

# Configuration Overview
URL: https://docs.learnhouse.app/self-hosting/configuration

LearnHouse uses environment variables as its primary configuration method. When you run `learnhouse setup`, the CLI generates a `.env` file with all the necessary variables based on your choices.

## Configuration Methods

LearnHouse supports two configuration methods:

1. **Environment variables** (via `.env` file) -- the primary and recommended method
2. **Configuration file** (`config.yaml`) -- an alternative for advanced users

If both are present, environment variables always take precedence over values defined in `config.yaml`.

## Editing Configuration

You can modify your configuration at any time using the CLI:

```bash
learnhouse config --edit
```

Alternatively, edit the `.env` file directly and restart services:

```bash
learnhouse restart
```

## Configuration Sections

- [Environment Variables](/self-hosting/configuration/environment-variables) -- Complete reference of all available environment variables.
- [AI Setup](/self-hosting/configuration/ai-setup) -- Enable and configure AI-powered features.
- [Email](/self-hosting/configuration/email) -- Set up email delivery for invitations, password resets, and notifications.
- [Content Storage](/self-hosting/configuration/storage) -- Configure filesystem or S3-compatible storage for uploaded content.
- [SSL and Domain](/self-hosting/configuration/ssl) -- Set up your domain name and SSL certificates.

---

# AI Setup
URL: https://docs.learnhouse.app/self-hosting/configuration/ai-setup

LearnHouse includes AI-powered features for learning assistance and content editing. The primary AI provider is **Google Gemini**, with OpenAI also supported as an alternative. These features are optional and disabled by default.

LearnHouse uses **llama-index** with **pgvector** for RAG (Retrieval-Augmented Generation), enabling AI assistants to answer questions using your course content as context.

## Enabling AI

### Using Google Gemini (Recommended)

Set the following environment variables in your `.env` file:

```env
LEARNHOUSE_GEMINI_API_KEY=your-gemini-api-key
LEARNHOUSE_IS_AI_ENABLED=true
```

To get a Gemini API key, visit [Google AI Studio](https://aistudio.google.com/apikey).

### Using OpenAI

Alternatively, you can use OpenAI as your AI provider:

```env
LEARNHOUSE_OPENAI_API_KEY=sk-your-openai-api-key
LEARNHOUSE_IS_AI_ENABLED=true
```

After updating your `.env` file, restart your instance:

```bash
learnhouse stop
learnhouse start
```

AI features require a valid API key with sufficient credits. Usage costs are billed directly by your chosen provider based on the models and volume used.

## Per-Organization AI Configuration

AI settings can also be configured on a per-organization basis through the organization configuration in the admin panel. This allows you to:

- Enable or disable AI for specific organizations
- Select which AI model to use per organization
- Control which AI features are available

## AI Feature Toggles

The following AI features can be individually enabled or disabled per organization:

| Feature | Description |
|---|---|
| `activity_ask` | AI assistant within learning activities, allows learners to ask questions about activity content |
| `course_ask` | AI assistant at the course level, answers questions using the full course material as context |
| `editor` | AI-powered writing assistance in the content editor |
| `global_ai_ask` | Global AI assistant available across the platform |

## Usage Limits

You can configure usage limits per organization to control API costs. Limits can be set on the number of AI requests per user per day, preventing unexpected charges on your provider account.

## Model Selection

The AI model used for generating responses can be configured per organization. This allows you to balance quality and cost by choosing different models for different use cases.

---

# Email Configuration
URL: https://docs.learnhouse.app/self-hosting/configuration/email

LearnHouse supports two email providers for transactional email delivery: **Resend** and **SMTP**. Email is used for user invitations, password resets, and system notifications.

## Choosing a Provider

Set the email provider in your `.env` file using the `LEARNHOUSE_EMAIL_PROVIDER` variable:

```env
LEARNHOUSE_EMAIL_PROVIDER=resend   # or "smtp"
```

## Option 1: Resend

[Resend](https://resend.com) is a developer-friendly email API service.

```env
LEARNHOUSE_EMAIL_PROVIDER=resend
LEARNHOUSE_RESEND_API_KEY=re_your-resend-api-key
LEARNHOUSE_SYSTEM_EMAIL_ADDRESS=noreply@example.com
```

### Getting a Resend API Key

1. Create an account at [resend.com](https://resend.com)
2. Add and verify your sending domain
3. Generate an API key from the Resend dashboard
4. Copy the API key into your `.env` file

## Option 2: SMTP

You can use any SMTP server, including services like Amazon SES, Mailgun, or your own mail server.

```env
LEARNHOUSE_EMAIL_PROVIDER=smtp
LEARNHOUSE_SMTP_HOST=smtp.example.com
LEARNHOUSE_SMTP_PORT=587
LEARNHOUSE_SMTP_USERNAME=user@example.com
LEARNHOUSE_SMTP_PASSWORD=your-smtp-password
LEARNHOUSE_SMTP_USE_TLS=true
LEARNHOUSE_SYSTEM_EMAIL_ADDRESS=noreply@example.com
```

### SMTP Variables

| Variable | Description | Default |
|---|---|---|
| `LEARNHOUSE_SMTP_HOST` | SMTP server hostname | -- |
| `LEARNHOUSE_SMTP_PORT` | SMTP server port | `587` |
| `LEARNHOUSE_SMTP_USERNAME` | SMTP authentication username | -- |
| `LEARNHOUSE_SMTP_PASSWORD` | SMTP authentication password | -- |
| `LEARNHOUSE_SMTP_USE_TLS` | Enable TLS encryption | `true` |

## Applying Changes

After updating your email configuration, restart your instance:

```bash
learnhouse stop
learnhouse start
```

## System Email Address

The `LEARNHOUSE_SYSTEM_EMAIL_ADDRESS` is the "from" address used for all outgoing emails. When using Resend, this address must belong to a domain that is verified in your Resend account. When using SMTP, ensure the address is permitted by your SMTP server.

If email is not configured, features like user invitations and password resets will not work. Users can still be created manually by an administrator.

## What Emails Are Sent

LearnHouse sends the following types of email:

- **User invitations** -- when an admin invites a user to join the platform or an organization
- **Password resets** -- when a user requests a password reset
- **System notifications** -- important system-level notifications

---

# Environment Variables
URL: https://docs.learnhouse.app/self-hosting/configuration/environment-variables

Complete reference of all environment variables used by LearnHouse. These are configured in the `.env` file generated by `learnhouse setup`.

Environment variables override any values set in configuration files. The `.env` file is the recommended configuration method.

## General

| Variable | Description | Example |
|---|---|---|
| `LEARNHOUSE_SITE_NAME` | The name of your LearnHouse instance | `LearnHouse` |
| `LEARNHOUSE_SITE_DESCRIPTION` | A short description of your site | `An open-source learning platform` |
| `LEARNHOUSE_CONTACT_EMAIL` | Contact email address displayed on the site | `admin@example.com` |
| `LEARNHOUSE_SELF_HOSTED` | Set to `true` for self-hosted deployments | `true` |
| `LEARNHOUSE_ENV` | Environment name | `production` |
| `LEARNHOUSE_DEVELOPMENT_MODE` | Enable development mode | `false` |

## Hosting

| Variable | Description | Example |
|---|---|---|
| `LEARNHOUSE_DOMAIN` | Your site domain | `learn.example.com` |
| `LEARNHOUSE_SSL` | Enable SSL (`true` or `false`) | `true` |
| `LEARNHOUSE_ALLOWED_ORIGINS` | Comma-separated list of allowed CORS origins | `https://learn.example.com` |
| `LEARNHOUSE_COOKIE_DOMAIN` | Domain used for cookies (prefix with `.` for subdomains) | `.example.com` |
| `LEARNHOUSE_ALLOWED_REGEXP` | Regex pattern for additional allowed origins | `\b((?:https?://)[^\s/$.?#].[^\s]*)\b` |
| `LEARNHOUSE_PORT` | Backend port (default 9000) | `9000` |

## Database

| Variable | Description | Example |
|---|---|---|
| `LEARNHOUSE_SQL_CONNECTION_STRING` | PostgreSQL connection string | `postgresql://learnhouse:learnhouse@db:5432/learnhouse` |

## Redis

| Variable | Description | Example |
|---|---|---|
| `LEARNHOUSE_REDIS_CONNECTION_STRING` | Redis connection string | `redis://redis:6379/learnhouse` |

## Authentication

| Variable | Description | Example |
|---|---|---|
| `LEARNHOUSE_AUTH_JWT_SECRET_KEY` | Secret key for JWT token signing | Generate with `openssl rand -base64 32` |

## Initial Admin

| Variable | Description | Example |
|---|---|---|
| `LEARNHOUSE_INITIAL_ADMIN_EMAIL` | Email for the first admin account | `admin@example.com` |
| `LEARNHOUSE_INITIAL_ADMIN_PASSWORD` | Password for the first admin account | Use a strong password |

## Frontend

| Variable | Description | Example |
|---|---|---|
| `NEXT_PUBLIC_LEARNHOUSE_MULTI_ORG` | Enable multi-organization mode | `false` |
| `NEXT_PUBLIC_LEARNHOUSE_DEFAULT_ORG` | Default organization slug | `defaultorg` |
| `NEXT_PUBLIC_LEARNHOUSE_API_URL` | Backend API URL (used by the frontend) | `http://localhost/api/v1/` |
| `NEXT_PUBLIC_LEARNHOUSE_BACKEND_URL` | Backend base URL | `http://localhost` |
| `NEXT_PUBLIC_LEARNHOUSE_TOP_DOMAIN` | Top-level domain for the frontend | `localhost` |
| `NEXT_PUBLIC_LEARNHOUSE_HTTPS` | Whether the frontend uses HTTPS | `false` |
| `NEXT_PUBLIC_LEARNHOUSE_MEDIA_URL` | URL for serving media content | `http://localhost/api/v1/` |
| `NEXT_PUBLIC_UNSPLASH_ACCESS_KEY` | Unsplash API key for stock images | `your-unsplash-key` |

## AI

| Variable | Description | Example |
|---|---|---|
| `LEARNHOUSE_GEMINI_API_KEY` | Google Gemini API key (primary AI provider) | `AIza...` |
| `LEARNHOUSE_OPENAI_API_KEY` | OpenAI API key (alternative AI provider) | `sk-...` |
| `LEARNHOUSE_IS_AI_ENABLED` | Enable AI features globally | `true` |

## Email

| Variable | Description | Example |
|---|---|---|
| `LEARNHOUSE_EMAIL_PROVIDER` | Email provider: `resend` or `smtp` | `resend` |
| `LEARNHOUSE_RESEND_API_KEY` | Resend API key (when using `resend` provider) | `re_...` |
| `LEARNHOUSE_SYSTEM_EMAIL_ADDRESS` | System email address (sender address) | `noreply@example.com` |
| `LEARNHOUSE_SMTP_HOST` | SMTP server hostname (when using `smtp` provider) | `smtp.example.com` |
| `LEARNHOUSE_SMTP_PORT` | SMTP server port (default 587) | `587` |
| `LEARNHOUSE_SMTP_USERNAME` | SMTP username | `user@example.com` |
| `LEARNHOUSE_SMTP_PASSWORD` | SMTP password | `your-smtp-password` |
| `LEARNHOUSE_SMTP_USE_TLS` | Enable TLS for SMTP | `true` |

## Content Storage

| Variable | Description | Example |
|---|---|---|
| `LEARNHOUSE_CONTENT_DELIVERY_TYPE` | Storage type: `filesystem` or `s3api` | `filesystem` |
| `LEARNHOUSE_S3_API_BUCKET_NAME` | S3 bucket name (when using `s3api`) | `learnhouse-content` |
| `LEARNHOUSE_S3_API_ENDPOINT_URL` | S3 endpoint URL (when using `s3api`) | `https://s3.amazonaws.com` |

## Collaboration Server

| Variable | Description | Example |
|---|---|---|
| `COLLAB_PORT` | Collaboration server port (default 4000) | `4000` |
| `COLLAB_INTERNAL_KEY` | Internal key for collaboration service auth | `your-collab-key` |
| `LEARNHOUSE_API_URL` | API URL used by the collaboration server | `http://learnhouse-app:9000/api/v1` |
| `LEARNHOUSE_REDIS_URL` | Redis URL used by the collaboration server | `redis://redis:6379` |

## Payments

| Variable | Description | Example |
|---|---|---|
| `LEARNHOUSE_STRIPE_SECRET_KEY` | Stripe secret key | `sk_live_...` |
| `LEARNHOUSE_STRIPE_PUBLISHABLE_KEY` | Stripe publishable key | `pk_live_...` |

## Code Execution

| Variable | Description | Example |
|---|---|---|
| `LEARNHOUSE_JUDGE0_API_URL` | Judge0 API URL for code execution | `https://judge0.example.com` |
| `LEARNHOUSE_JUDGE0_CLIENT_ID` | Judge0 client ID | `your-client-id` |
| `LEARNHOUSE_JUDGE0_CLIENT_SECRET` | Judge0 client secret | `your-client-secret` |

## Analytics

| Variable | Description | Example |
|---|---|---|
| `LEARNHOUSE_TINYBIRD_API_URL` | Tinybird API URL | `https://api.tinybird.co` |
| `LEARNHOUSE_TINYBIRD_INGEST_TOKEN` | Tinybird ingest token | `your-ingest-token` |
| `LEARNHOUSE_TINYBIRD_READ_TOKEN` | Tinybird read token | `your-read-token` |

## Observability

| Variable | Description | Example |
|---|---|---|
| `LEARNHOUSE_SENTRY_DSN` | Sentry DSN for error tracking | `https://abc@sentry.io/123` |
| `LEARNHOUSE_LOGFIRE_ENABLED` | Enable Logfire logging | `false` |

## Full Example

```env filename=".env" copy
# General
LEARNHOUSE_SITE_NAME=LearnHouse
LEARNHOUSE_SITE_DESCRIPTION=An open-source learning platform
LEARNHOUSE_CONTACT_EMAIL=admin@example.com
LEARNHOUSE_SELF_HOSTED=true
LEARNHOUSE_ENV=production

# Hosting
LEARNHOUSE_DOMAIN=learn.example.com
LEARNHOUSE_SSL=true
LEARNHOUSE_ALLOWED_ORIGINS=https://learn.example.com
LEARNHOUSE_COOKIE_DOMAIN=.example.com
LEARNHOUSE_PORT=9000

# Database
LEARNHOUSE_SQL_CONNECTION_STRING=postgresql://learnhouse:learnhouse@db:5432/learnhouse

# Redis
LEARNHOUSE_REDIS_CONNECTION_STRING=redis://redis:6379/learnhouse

# Authentication
LEARNHOUSE_AUTH_JWT_SECRET_KEY=your-generated-jwt-secret
NEXTAUTH_SECRET=your-generated-nextauth-secret
NEXTAUTH_URL=https://learn.example.com/

# Initial Admin
LEARNHOUSE_INITIAL_ADMIN_EMAIL=admin@example.com
LEARNHOUSE_INITIAL_ADMIN_PASSWORD=change-this-password

# Frontend
NEXT_PUBLIC_LEARNHOUSE_MULTI_ORG=false
NEXT_PUBLIC_LEARNHOUSE_DEFAULT_ORG=defaultorg
NEXT_PUBLIC_LEARNHOUSE_API_URL=http://localhost/api/v1/
NEXT_PUBLIC_LEARNHOUSE_BACKEND_URL=http://localhost
NEXT_PUBLIC_LEARNHOUSE_HTTPS=false

# AI (optional)
LEARNHOUSE_GEMINI_API_KEY=
LEARNHOUSE_IS_AI_ENABLED=false

# Email (optional)
LEARNHOUSE_EMAIL_PROVIDER=resend
LEARNHOUSE_RESEND_API_KEY=
LEARNHOUSE_SYSTEM_EMAIL_ADDRESS=

# Content Storage
LEARNHOUSE_CONTENT_DELIVERY_TYPE=filesystem
```

---

# SSL and Domain Setup
URL: https://docs.learnhouse.app/self-hosting/configuration/ssl

Securing your LearnHouse instance with SSL is strongly recommended for production deployments. This guide covers domain configuration and SSL setup options.

## Domain Configuration

Set your domain in the `.env` file:

```env
LEARNHOUSE_DOMAIN=learn.example.com
LEARNHOUSE_SSL=true
LEARNHOUSE_COOKIE_DOMAIN=.example.com
```

Make sure your DNS records point to the server running LearnHouse before enabling SSL.

## Using a Reverse Proxy

The recommended approach for SSL termination is to place a reverse proxy in front of LearnHouse. This gives you flexibility in certificate management and allows you to serve other applications on the same server.

### Caddy

Caddy automatically obtains and renews Let's Encrypt certificates. Create a `Caddyfile`:

```
learn.example.com {
    reverse_proxy localhost:80
}
```

### Nginx

An example nginx configuration with Let's Encrypt (via Certbot):

```nginx
server {
    listen 443 ssl;
    server_name learn.example.com;

    ssl_certificate /etc/letsencrypt/live/learn.example.com/fullchain.pem;
    ssl_certificate_key /etc/letsencrypt/live/learn.example.com/privkey.pem;

    location / {
        proxy_pass http://localhost:80;
        proxy_set_header Host $host;
        proxy_set_header X-Real-IP $remote_addr;
        proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
        proxy_set_header X-Forwarded-Proto $scheme;
    }
}

server {
    listen 80;
    server_name learn.example.com;
    return 301 https://$server_name$request_uri;
}
```

### Traefik

If you use Traefik as your reverse proxy, you can configure it to route traffic to LearnHouse and handle Let's Encrypt certificates automatically through its built-in ACME support.

## Let's Encrypt

For free, automated SSL certificates, use Let's Encrypt with one of the reverse proxy options above:

- **Caddy** handles Let's Encrypt automatically with zero configuration.
- **Nginx** works with [Certbot](https://certbot.eff.org/) for automated certificate issuance and renewal.
- **Traefik** has built-in ACME/Let's Encrypt support.

When enabling SSL, update all related configuration to use `https://` URLs, including `LEARNHOUSE_ALLOWED_ORIGINS` and `NEXTAUTH_URL`.

## Cookie Domain

The `LEARNHOUSE_COOKIE_DOMAIN` variable controls which domain cookies are scoped to. This is important for authentication to work correctly.

- For a single domain like `learn.example.com`, set it to `.example.com`
- Using a leading dot (`.example.com`) allows cookies to work across subdomains, which is required if you use multi-organization mode with subdomains

---

# Content Storage
URL: https://docs.learnhouse.app/self-hosting/configuration/storage

LearnHouse supports two storage backends for uploaded content such as images, videos, and documents.

## Storage Options

### Filesystem (Default)

By default, uploaded content is stored on the local filesystem using a Docker volume. This is the simplest option and works well for small to medium deployments.

```env
LEARNHOUSE_CONTENT_DELIVERY_TYPE=filesystem
```

Content is persisted in a Docker volume, so it survives container restarts. The `learnhouse backup` command includes filesystem content in its backups.

### S3-Compatible Storage

For production deployments or when you need scalable storage, you can use any S3-compatible storage service:

- **AWS S3**
- **CloudFlare R2**
- **MinIO** (self-hosted)
- Any other S3-compatible provider

```env
LEARNHOUSE_CONTENT_DELIVERY_TYPE=s3api
LEARNHOUSE_S3_API_BUCKET_NAME=learnhouse-content
LEARNHOUSE_S3_API_ENDPOINT_URL=https://s3.amazonaws.com
```

After updating your storage configuration, restart your instance:

```bash
learnhouse stop
learnhouse start
```

When using S3-compatible storage, make sure the bucket exists and the credentials have read/write permissions. For AWS S3, credentials are typically provided via standard AWS environment variables or instance roles.

## Choosing a Storage Backend

| Consideration | Filesystem | S3-Compatible |
|---|---|---|
| Setup complexity | Simple, works out of the box | Requires external service or additional container |
| Scalability | Limited by server disk | Virtually unlimited |
| Backup | Included in `learnhouse backup` | Managed separately by your storage provider |
| Cost | Included with your server | Varies by provider |
| Redundancy | Single disk, no redundancy | Built-in redundancy (provider-dependent) |

For most self-hosted installations starting out, filesystem storage is a good default. You can migrate to S3-compatible storage later as your needs grow.

## Using MinIO for Self-Hosted S3

If you want S3-compatible storage without relying on a cloud provider, you can run MinIO alongside LearnHouse. MinIO provides an S3-compatible API on your own infrastructure.

Configure the endpoint URL to point to your MinIO instance:

```env
LEARNHOUSE_CONTENT_DELIVERY_TYPE=s3api
LEARNHOUSE_S3_API_BUCKET_NAME=learnhouse-content
LEARNHOUSE_S3_API_ENDPOINT_URL=http://minio:9000
```

---

# Installation Overview
URL: https://docs.learnhouse.app/self-hosting/installation

The **LearnHouse CLI** is the recommended and officially supported way to install and manage self-hosted LearnHouse instances. The CLI automates the entire deployment process, so you can go from a fresh server to a running LearnHouse instance in minutes.

## What the CLI Does

The LearnHouse CLI handles:

- **Interactive setup wizard** that walks you through initial configuration
- **Docker Compose generation** based on your setup choices
- **Environment file generation** with all required variables pre-configured
- **Service management** to start, stop, and restart your instance
- **Health checks** to verify all services are running correctly
- **Backups and restores** for your database and uploaded content
- **Updates** to pull the latest LearnHouse images and apply them

You do not need to manually create or edit Docker Compose files. The CLI generates and manages them for you based on your configuration choices.

## Next Steps

- [Requirements](/self-hosting/installation/requirements) -- Verify your server meets the minimum system requirements.
- [Quick Install](/self-hosting/installation/quick-install) -- Install the CLI and set up LearnHouse in minutes.
- [CLI Reference](/self-hosting/installation/cli-reference) -- Full reference of all available CLI commands.

---

# CLI Reference
URL: https://docs.learnhouse.app/self-hosting/installation/cli-reference

Complete reference for all LearnHouse CLI commands. The CLI is published as `learnhouse` on npm (v1.1.0) and is typically run via `npx learnhouse@latest`.

## Setup and Configuration

### `learnhouse setup`

Run the interactive setup wizard. This command generates `docker-compose.yml`, `.env`, `learnhouse.config.json`, and nginx/Caddy configuration files based on your choices.

```bash
learnhouse setup
```

You can re-run this command at any time to reconfigure your instance. Existing configuration will be preserved as defaults in the prompts.

### `learnhouse config`

View the current configuration.

```bash
learnhouse config
```

## Service Management

### `learnhouse start`

Start all LearnHouse services. On first run, this pulls the required Docker images before starting containers.

```bash
learnhouse start
```

### `learnhouse stop`

Stop all running LearnHouse services. Data is preserved in Docker volumes.

```bash
learnhouse stop
```

### `learnhouse logs`

Stream container logs for all services.

```bash
learnhouse logs
```

### `learnhouse dev`

Start a full development environment. Useful when working on LearnHouse locally.

```bash
learnhouse dev
```

## Diagnostics

### `learnhouse doctor`

Run diagnostics on your LearnHouse installation. Checks Docker availability, container health, port conflicts, DNS resolution, and disk space.

```bash
learnhouse doctor
```

### `learnhouse shell`

Open an interactive shell inside a running container for debugging.

```bash
learnhouse shell
```

## Infrastructure

### `learnhouse deployments`

View or set resource limits (CPU, memory) for your LearnHouse containers.

```bash
learnhouse deployments
```

## Backup

### `learnhouse backup`

Backup or restore the database. This command handles both creating new backups and restoring from existing backup files.

```bash
learnhouse backup
```

## Command Summary

| Command | Description |
|---|---|
| `learnhouse setup` | Interactive setup wizard, generates docker-compose.yml, .env, and config files |
| `learnhouse start` | Start all services |
| `learnhouse stop` | Stop all services |
| `learnhouse logs` | Stream container logs |
| `learnhouse config` | View current configuration |
| `learnhouse doctor` | Diagnose Docker, containers, ports, DNS, and disk |
| `learnhouse shell` | Open a shell in a running container |
| `learnhouse backup` | Backup or restore the database |
| `learnhouse deployments` | View or set resource limits |
| `learnhouse dev` | Start full development environment |

---

# Quick Install
URL: https://docs.learnhouse.app/self-hosting/installation/quick-install

Follow these steps to install and start a self-hosted LearnHouse instance using the LearnHouse CLI.

## Step 1: Run the Setup Wizard

The quickest way to get started is to run the setup wizard directly using `npx`. No global installation is needed.

```bash
npx learnhouse@latest setup
```

You can also use the one-line installer scripts if you prefer:

**macOS / Linux:**
```bash
curl -fsSL https://raw.githubusercontent.com/learnhouse/learnhouse/main/install.sh | bash
```

**Windows (PowerShell):**
```powershell
irm https://raw.githubusercontent.com/learnhouse/learnhouse/main/install.ps1 | iex
```

The wizard will prompt you for:

- **Domain configuration** -- your domain name or localhost for local development
- **Database settings** -- PostgreSQL configuration (defaults are provided)
- **Admin credentials** -- email and password for the initial admin account
- **Optional features** -- AI features, email delivery, and more

The wizard generates `docker-compose.yml`, `.env`, `learnhouse.config.json`, and an nginx or Caddy configuration based on your choices. Sensible defaults are provided for most options -- you can press Enter to accept them and adjust settings later.

## Step 2: Start LearnHouse

Once setup is complete, start all services:

```bash
learnhouse start
```

The CLI will pull the required Docker images (on first run), create the containers, and start all services. This typically takes one to two minutes on first launch.

## Step 3: Access LearnHouse

Once all services are running, access LearnHouse at your configured domain or:

- **http://localhost** (if using the default local configuration)

Log in with the admin credentials you provided during setup.

Change the default admin password after your first login. The initial credentials are intended only for the first setup. Navigate to your account settings to update your password.

## Verifying the Installation

Run the built-in diagnostics to check that everything is working:

```bash
learnhouse doctor
```

This command checks Docker, container health, port availability, DNS resolution, and disk space, then reports any issues it finds.

You can also verify the health endpoint directly:

```bash
curl http://localhost/api/v1/health
```

## Next Steps

- [CLI Reference](/self-hosting/installation/cli-reference) -- Learn all available CLI commands.
- [Configuration](/self-hosting/configuration) -- Customize your instance with environment variables, AI, email, and more.

---

# System Requirements
URL: https://docs.learnhouse.app/self-hosting/installation/requirements

Before installing LearnHouse, ensure your server meets the following requirements.

## Software Requirements

| Software | Minimum Version | Notes |
|---|---|---|
| Docker Engine | 20.10+ | Required for running containers |
| Docker Compose | 2.0+ | Included with Docker Desktop; install separately on Linux |
| Node.js | 18+ | Required to run the LearnHouse CLI |
| npm | 8+ | Comes with Node.js |

## Hardware Requirements

| Resource | Minimum | Recommended |
|---|---|---|
| RAM | 2 GB | 4 GB |
| Disk Space | 10 GB | 20 GB+ |
| CPU | 1 core | 2+ cores |

Disk usage will grow over time depending on the amount of uploaded content (videos, documents, images). Plan storage capacity accordingly if you expect heavy usage.

## Operating System

LearnHouse is supported on:

- **Linux** (Ubuntu 20.04+, Debian 11+, CentOS 8+, or any distribution with Docker support)
- **macOS** (with Docker Desktop)
- **Windows** (via WSL2 with Docker Desktop)

Linux is recommended for production deployments.

## Network Requirements

- Port **80** (HTTP) and/or port **443** (HTTPS) must be available
- Outbound internet access is required during installation to pull Docker images
- A domain name is recommended for production use but not required for local testing

## Verifying Prerequisites

Run the following commands to verify your system is ready:

```bash
# Check Docker
docker --version

# Check Docker Compose
docker compose version

# Check Node.js
node --version

# Check npm
npm --version
```

All commands should return version numbers that meet or exceed the minimums listed above.

---

# Maintenance Overview
URL: https://docs.learnhouse.app/self-hosting/maintenance

Keeping your self-hosted LearnHouse instance healthy requires periodic maintenance. The LearnHouse CLI provides built-in tools for the most common maintenance tasks.

## Maintenance Tasks

### [Updates](/self-hosting/maintenance/updates)

Keep LearnHouse up to date with the latest features, improvements, and security patches using `learnhouse update`.

### [Backups](/self-hosting/maintenance/backups)

Protect your data with regular backups of the database and uploaded content using `learnhouse backup`.

### [Monitoring](/self-hosting/maintenance/monitoring)

Monitor the health and performance of your instance using `learnhouse status` and `learnhouse logs`.

### [Troubleshooting](/self-hosting/maintenance/troubleshooting)

Diagnose and resolve common issues with your self-hosted instance.

---

# Backups
URL: https://docs.learnhouse.app/self-hosting/maintenance/backups

Regular backups are essential for protecting your LearnHouse data. The LearnHouse CLI provides built-in backup and restore functionality.

## Creating a Backup

Create a backup with a single command:

```bash
learnhouse backup
```

This creates a timestamped archive file containing:

- **PostgreSQL database dump** -- all users, courses, organizations, and configuration data
- **Uploaded content** -- images, videos, documents, and other files stored on the filesystem

The backup file is saved in the current working directory with a name like `backup-2025-01-15-120000.tar.gz`.

## Restoring from a Backup

To restore from a backup file:

```bash
learnhouse restore backup-2025-01-15-120000.tar.gz
```

The restore process:

1. Stops all running services
2. Restores the database from the dump
3. Restores uploaded content files
4. Restarts all services

Restoring a backup overwrites all current data. Make sure you are restoring to the correct instance.

## Automating Backups

It is recommended to set up automated backups using a cron job. For example, to create a daily backup at 2:00 AM:

```bash
# Edit your crontab
crontab -e

# Add this line for daily backups at 2 AM
0 2 * * * /usr/local/bin/learnhouse backup
```

## Backup Retention

Backup files can accumulate over time and consume significant disk space. Implement a retention policy to remove old backups. For example, keep the last 7 daily backups:

```bash
# Remove backups older than 7 days
find /path/to/backups -name "backup-*.tar.gz" -mtime +7 -delete
```

## S3 Storage Considerations

If you use S3-compatible storage for uploaded content, the `learnhouse backup` command backs up the database only. Your S3 content is managed by your storage provider, which typically offers its own backup and versioning features.

For S3-based deployments, ensure your storage provider's backup or versioning features are enabled to protect uploaded content.

---

# Monitoring
URL: https://docs.learnhouse.app/self-hosting/maintenance/monitoring

Monitoring your self-hosted LearnHouse instance helps you catch issues early and ensure a reliable experience for your users.

## Service Health Checks

Run the built-in diagnostics to check the health of your installation:

```bash
learnhouse doctor
```

This checks Docker availability, container health, port conflicts, DNS resolution, and disk space. It reports any issues found and suggests fixes.

You can also verify the application health endpoint directly:

```bash
curl http://localhost/api/v1/health
```

## Viewing Logs

Stream logs from all containers:

```bash
learnhouse logs
```

## What to Monitor

### Application Health

- Run `learnhouse doctor` regularly to verify all services are running and healthy
- Watch for container restarts, which may indicate memory issues or application errors

### Disk Usage

- Monitor disk space, especially if using filesystem storage for uploaded content
- Database size grows over time as more content is created
- Docker images and logs also consume disk space

### Memory Usage

- LearnHouse requires at least 2 GB of RAM
- Monitor memory consumption to ensure the server is not swapping, which degrades performance

### Database Performance

- Watch for slow queries in the application logs
- Monitor PostgreSQL connection counts

## Monitoring Recommendations

For production deployments, consider setting up:

- **Uptime monitoring** -- use an external service to check that your LearnHouse instance is accessible (e.g., monitor `http://your-domain/api/v1/health`)
- **Disk space alerts** -- get notified before disk space runs out
- **Log aggregation** -- ship logs to a centralized logging system for easier analysis
- **Container monitoring** -- tools like Docker's built-in stats, cAdvisor, or Prometheus with node-exporter can track resource usage over time

---

# Troubleshooting
URL: https://docs.learnhouse.app/self-hosting/maintenance/troubleshooting

This guide covers common issues with self-hosted LearnHouse instances and how to resolve them.

## First Step: Run Diagnostics

Before diving into specific issues, run the built-in diagnostics:

```bash
learnhouse doctor
```

This checks Docker availability, container health, port conflicts, DNS resolution, and disk space. It will often identify the root cause of problems automatically.

## Services Not Starting

**Symptoms:** `learnhouse start` fails, or containers are stopped or restarting.

**Common causes:**

- **Docker is not running.** Verify Docker is running with `docker info`. Start the Docker daemon if needed.
- **Insufficient memory.** LearnHouse requires at least 2 GB of RAM. Check available memory with `free -m` (Linux) or Activity Monitor (macOS).
- **Port conflicts.** Another service may be using port 80 or 443. Check with `lsof -i :80` and stop the conflicting service. `learnhouse doctor` will also detect port conflicts.
- **Corrupted configuration.** Re-run `learnhouse setup` to regenerate configuration files.

## Database Connection Errors

**Symptoms:** Application logs show database connection errors, or the app fails to start with PostgreSQL-related messages.

**Steps to resolve:**

1. Run diagnostics to check container health:
   ```bash
   learnhouse doctor
   ```

2. Check database logs:
   ```bash
   learnhouse logs
   ```
   Look for log lines from the `db` container.

3. Verify the connection string in your `.env` file matches the database container's configuration.

4. If the database container keeps restarting, it may be running out of disk space. Check available disk space on the host.

## Port Conflicts

**Symptoms:** Error messages about ports already being in use.

Check which process is using the port:

```bash
# Check port 80
lsof -i :80

# Check port 443
lsof -i :443
```

Stop the conflicting service, or reconfigure LearnHouse to use a different port by re-running `learnhouse setup`.

## Storage Permission Errors

**Symptoms:** File upload fails, or logs show permission denied errors when writing to storage.

**For filesystem storage:**

- Docker volumes should handle permissions automatically. If issues persist, check that the Docker daemon has appropriate permissions on the host filesystem.

**For S3 storage:**

- Verify your S3 credentials have read and write permissions on the configured bucket.
- Check that the bucket name (`LEARNHOUSE_S3_API_BUCKET_NAME`) and endpoint URL (`LEARNHOUSE_S3_API_ENDPOINT_URL`) are correct in your `.env` file.
- Test connectivity to the S3 endpoint from the server.

## Authentication Issues

**Symptoms:** Users cannot log in, or sessions expire immediately.

- Verify `NEXTAUTH_SECRET` is set and has not changed since the last restart. Changing the secret invalidates all existing sessions.
- Verify `LEARNHOUSE_COOKIE_DOMAIN` matches your actual domain. Incorrect cookie domain prevents authentication from working.
- If using SSL, ensure `NEXTAUTH_URL` uses `https://`.

## Performance Issues

**Symptoms:** Slow page loads, timeouts, or high resource usage.

1. Run diagnostics:
   ```bash
   learnhouse doctor
   ```

2. Review application logs for errors or slow operations:
   ```bash
   learnhouse logs
   ```

3. Check resource limits on your containers:
   ```bash
   learnhouse deployments
   ```

4. Consider increasing server resources (RAM, CPU) if usage is consistently high.

5. If using filesystem storage with a large amount of content, consider migrating to S3-compatible storage.

## Resetting Your Instance

Resetting your instance deletes all data. Create a backup first if you want to preserve any data.

If you need to start fresh:

```bash
# Back up current data (optional)
learnhouse backup

# Stop all services
learnhouse stop

# Re-run setup
learnhouse setup

# Start fresh
learnhouse start
```

## Getting Help

If you cannot resolve an issue using this guide:

1. Run `learnhouse doctor` and include the output in your report.
2. Check the [LearnHouse GitHub issues](https://github.com/learnhouse/learnhouse/issues) for known problems and solutions.
3. Open a new issue with details about your problem, including relevant log output and your environment (OS, Docker version, RAM).

---

# Updates
URL: https://docs.learnhouse.app/self-hosting/maintenance/updates

Keeping LearnHouse up to date ensures you have the latest features, bug fixes, and security patches.

## Updating LearnHouse

There is no dedicated update command in the CLI. To update your instance, pull the latest Docker images and restart the services manually:

```bash
docker compose pull
learnhouse stop
learnhouse start
```

This pulls the latest LearnHouse Docker images (`ghcr.io/learnhouse/app:latest` and others), stops the running services, and starts them again with the new images.

Always create a backup before updating. This allows you to roll back if anything goes wrong.

## Recommended Update Procedure

```bash
# 1. Create a backup
learnhouse backup

# 2. Pull the latest images
docker compose pull

# 3. Restart services with the new images
learnhouse stop
learnhouse start

# 4. Verify all services are healthy
learnhouse doctor

# 5. Check logs for any errors
learnhouse logs
```

## Checking for Updates

Review the [LearnHouse release notes](https://github.com/learnhouse/learnhouse/releases) before updating to understand what has changed. Some updates may include:

- New features or UI changes
- Database migrations (applied automatically)
- Configuration changes that may require updating your `.env` file
- Breaking changes (rare, but documented in release notes)

## Rolling Back

If an update causes issues, restore from your backup using the backup command:

```bash
learnhouse backup
```

The backup command handles both creating new backups and restoring from existing ones. Follow the prompts to select a restore operation, which will restore both the database and uploaded content to the state captured in the backup.
