# 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

---
title: Home
---

## 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 |
| 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 restore <archive.tar.gz>
npx learnhouse backup --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 memory limits 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 (Resend only — edit `.env` directly to set SMTP credentials)
- 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 (keeps the `ee/` folder active) |
| `--admin-email <email>` | Admin email (default: `admin@school.dev`) |
| `--admin-password <password>` | Admin password (skips the interactive prompt) |

## `update`

Update LearnHouse to the latest release or a specific version. See [Updates](/self-hosting/maintenance/updates) for details.

```bash
npx learnhouse update
npx learnhouse update --version 1.4.2
```

| Flag | Description |
| --- | --- |
| `--version <tag>` | Pull a specific image tag from `ghcr.io/learnhouse/app` |
| `--migrate` | Run database migrations without prompting |
| `--no-migrate` | Skip database migrations without prompting |

## `status`

Show the status of each LearnHouse service.

```bash
npx learnhouse status
```

---

# 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)

`bun` and `uv` must be installed beforehand. The CLI runs `bun install` and `uv sync` to install project dependencies, but it does not install the package managers themselves.

## 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** — When the database and Redis containers are created for the first time, prompts for an admin email and password. On subsequent runs with existing containers, the prompt is skipped and the existing credentials remain valid. You can also pass `--admin-email` and `--admin-password` to skip the prompt.
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):
  - Uses `pgvector/pgvector:pg16` (PostgreSQL 16 with the pgvector extension, used for AI/RAG features when enabled)
  - 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:latest` (or `:dev`) | Next.js + FastAPI application |
| `learnhouse-db-{id}` | `pgvector/pgvector:pg16` | 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 (pulls `ghcr.io/learnhouse/app:latest`)
- **Dev** — Bleeding edge, latest features (pulls `ghcr.io/learnhouse/app:dev`)

To pin to a specific image tag after setup, use `learnhouse update --version <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

The login endpoint accepts `application/x-www-form-urlencoded` data with `username` (the user's email) and `password` fields, and returns a JWT access token (HS256, expires in 8 hours):

```bash
curl -X POST http://localhost:1338/api/v1/auth/login \
  -F 'username=you@example.com' \
  -F 'password=your-password'
```

Then authenticate requests via the `Authorization` header:

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

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

Logins are rate-limited by IP, and repeated failed attempts temporarily lock the account. SaaS deployments also require `email_verified=true` before login succeeds.

## 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/profile \
  -H "Authorization: Bearer lh_your_api_token_here"
```

## Auth Endpoints

| Method | Endpoint | Description |
| --- | --- | --- |
| `POST` | `/api/v1/auth/login` | Login with form-encoded `username` + `password` |
| `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 |
| `POST` | `/api/v1/auth/resend-verification` | Resend a verification email |

---

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

This page provides an overview of the 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 (form-encoded, not JSON)
curl -X POST http://localhost:1338/api/v1/auth/login \
  -F 'username=user@example.com' \
  -F '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/profile \
  -H "Authorization: Bearer <token>"
```

### Organizations

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

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

### Courses

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

```bash
# List courses in an organization (paginated)
curl "http://localhost:1338/api/v1/courses/org_slug/{org_slug}/page/1/limit/20" \
  -H "Authorization: Bearer <token>"

# Create a new course (multipart form data)
curl -X POST "http://localhost:1338/api/v1/courses/?org_id=1" \
  -H "Authorization: Bearer <token>" \
  -F 'name=Introduction to Python' \
  -F 'description=A beginner-friendly Python course' \
  -F 'public=false' \
  -F 'about=...'
```

### Chapters

Chapter CRUD and ordering within courses.

### Activities

Activity CRUD — individual content units within chapters. Activity types include dynamic pages, videos, documents, assignments, custom, and SCORM (1.2 and 2004).

### Blocks

Block CRUD — content blocks within dynamic page activities.

### Collections

Collections group related courses together for organization and discovery.

### Assignments

Assignment CRUD for course assessments. Task types include file submissions, quizzes, and custom (`OTHER`) tasks.

### AI

AI-powered features including the course assistant, magic blocks, course planning, and RAG (Retrieval-Augmented Generation). All AI features are powered by Google Gemini.

Routes live under `/api/v1/ai/` and include streaming endpoints such as `POST /api/v1/ai/stream/editor/message`. Refer to `/docs` for the full list.

### Analytics

Course analytics and usage tracking (backed by Tinybird with a Redis cache layer).

### Search

Full-text search across courses and content. Results are paginated with a default page size of 10 and a maximum of 50 per page.

### Code Execution

Code execution endpoints powered by Judge0 (used by the Code Playground editor block).

### 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, including pinning, locking, labels, votes, and reactions.

### User Groups

User group management for organizing learners.

## Pro Features (Pro Plan)

### Certifications

Certificate generation and management for course completion.

### Boards

Real-time collaborative canvases (Miro/FigJam-style), powered by Yjs and Hocuspocus.

### Playgrounds

AI-generated interactive HTML playgrounds (separate from the Judge0-powered Code Playground editor block).

### Podcasts

Podcast and episode CRUD for audio content delivery, exposing a standard RSS feed for manual submission to directories like Apple Podcasts and Spotify.

## 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.
- Create/update endpoints commonly accept **multipart form data** rather than JSON, since many also accept file uploads (e.g. thumbnails, avatars).
- 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
├── docker/       # Production Dockerfile helpers (nginx config, start.sh)
└── Dockerfile    # Monolithic image used by the CLI setup wizard
```

Self-hosted deployments do not have a checked-in `docker-compose.yml`. The LearnHouse CLI (`apps/cli`) generates `docker-compose.yml`, `.env`, and reverse proxy config at setup time from the templates in `apps/cli/src/templates/`.

## 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 (pgvector)** -- The primary relational database for storing all application data including users, courses, organizations, and activity records. Uses the pgvector extension for AI embedding storage. Both dev and self-host production use the `pgvector/pgvector:pg16` image.
- **Redis** -- Used for caching, session management, collaboration state persistence, and message brokering between services. Dev mode uses `redis:8.6.1-alpine`; the CLI-generated self-host production stack uses `redis:7.2.3-alpine`.

---

# 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.3 -- High-performance Python web framework
- **Python 3.14**
- **SQLModel** 0.0.38 -- ORM for database interactions (built on SQLAlchemy and Pydantic)
- **Alembic** -- Database migration management
- **PostgreSQL 16** with **pgvector** extension -- Primary relational database
- **redis-py** 7.4.0 -- Python Redis client
- **Uvicorn** 0.44.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.71.0 -- Gemini AI integration (the only AI provider)
- **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 python app.py # start the dev server (which calls uvicorn internally)
```

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.2.3** with the App Router (standalone output)
- **React 19.2.5** with Server Components
- **TypeScript 6.0.2**
- **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
├── hooks/         # Shared React hooks
├── lib/           # Utilities and client helpers
├── locales/       # i18next translation resources
├── styles/        # Global styles
├── ee/            # Enterprise Edition components
└── 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 **development** (`learnhouse dev`), PostgreSQL and Redis run in Docker via `.learnhouse/docker-compose.dev.yml` while the API, web, and collab processes run locally on the host.
- In **self-hosted production**, the LearnHouse CLI generates a `docker-compose.yml` from templates in `apps/cli/src/templates/` that runs PostgreSQL, Redis, a single `learnhouse-app` container (which bundles web + API + collab), and either nginx or Caddy as a reverse proxy.

## PostgreSQL

`pgvector/pgvector:pg16` (PostgreSQL 16 with the pgvector extension) 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.

**Default port:** `5432`

## Redis

Redis 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.

The dev compose uses `redis:8.6.1-alpine`; the CLI-generated self-host production compose uses `redis:7.2.3-alpine`.

**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` in dev) 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 (`REDIS_YDOC_TTL = 3600`) for fast access.
2. **PostgreSQL** -- State is persisted to the database via the API with a 5-second debounce (`DB_FLUSH_DELAY = 5000`) to avoid excessive writes.

### Rate Limiting and Capacity

- **Max 10 concurrent users** per board (`MAX_BOARD_USERS`)
- **Rate limiting** of 30 connections per IP per minute (`RATE_LIMIT_MAX`, `RATE_LIMIT_WINDOW_MS`)

### Key Features

- **Real-time document synchronization** -- Multiple users can edit the same board 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.

## Reverse Proxy (nginx or Caddy)

The CLI-generated self-host stack uses one of two reverse proxies depending on the SSL choice made during setup:

- **Caddy** (`caddy:2-alpine`) — selected when "Automatic SSL" is enabled; handles Let's Encrypt certificate issuance and renewal automatically.
- **nginx** (`nginx:alpine`) — selected for manual SSL or HTTP-only setups.

Both route traffic to the single `learnhouse-app` container, which internally serves the Next.js frontend, the FastAPI backend, and the Hocuspocus collaboration server.

## Service Communication

Logically, a request flows like this:

```
Client
  └── nginx / caddy (reverse proxy)
        └── learnhouse-app (single container)
              ├── Next.js (web)
              ├── FastAPI (api)
              │     ├── PostgreSQL (port 5432)
              │     └── Redis (port 6379)
              └── Hocuspocus (collab)
                    ├── Redis (port 6379)
                    └── FastAPI (for persistence & JWT-based auth)
```

The Hocuspocus 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+**
- **[Bun](https://bun.sh/)** — used to install and run the web and collab workspaces
- **[uv](https://docs.astral.sh/uv/)** — used to manage and run the Python API

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

`npx learnhouse dev` runs `bun install` and `uv sync` to install project dependencies, but it does **not** install `bun` or `uv` themselves — install them on your host first.

## 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 (web), 1338 (API), 4000 (collab), 5432 (Postgres), and 6379 (Redis) 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.

---

# Migrating Content into LearnHouse
URL: https://docs.learnhouse.app/developers/migration

This section explains how to bring existing course content into LearnHouse using the public API. There are two supported approaches:

1. **Programmatic Migration** -- you script every step (create the course, then chapters, then activities, then upload files). Use this when you need full control of the resulting structure -- typical for migrating from another LMS where you already know the chapter/activity layout.
2. **AI-Assisted Migration** -- you upload a folder of media (videos, PDFs, images, audio) and LearnHouse asks Gemini to propose a chapter/activity tree. You review and confirm, and a single endpoint creates the entire course in one transaction. Use this when you have a pile of files but no predefined structure.

Both approaches share the same underlying data model -- a Course contains Chapters, and each Chapter contains an ordered list of Activities.

All endpoints below are prefixed with `/api/v1/`. In local development the base URL is `http://localhost:1338/api/v1/`. In production it is served at `/api/v1/` on your instance domain.

## Authentication

Every migration call must be authenticated. There are two token types:

- **JWT access tokens** (`POST /api/v1/auth/login`) -- a user session, 8-hour lifetime, refreshable.
- **API tokens** (Pro plan) -- prefixed with `lh_`, issued per organization, no expiry.

Both are sent the same way:

```bash
curl http://localhost:1338/api/v1/courses/?org_id=1 \
  -H "Authorization: Bearer lh_your_api_token_here"
```

API tokens are bound to a single organization at creation time. Any attempt to operate on a different `org_id` is rejected at the auth layer, so a leaked token cannot reach across tenants.

**API tokens cannot call every endpoint.** A small set of routers -- including the AI-assisted migration endpoints under `/api/v1/courses/migrate/*` and several user-scoped endpoints like `/users/profile` -- explicitly reject API tokens (HTTP 403, `"API tokens cannot access this resource"`). For these calls, you need a user JWT. The supported pattern is the **admin token-swap**: use your API token once to mint a JWT on behalf of any user in your organization, then use that JWT for the protected calls.

```bash
# Mint a user JWT using your API token
curl -X POST 'http://localhost:1338/api/v1/admin/{org_slug}/auth/token' \
  -H 'Authorization: Bearer lh_your_api_token' \
  -H 'Content-Type: application/json' \
  -d '{"user_id": 1}'
# → { "access_token": "eyJ...", "token_type": "bearer", "user_id": 1, "user_uuid": "..." }
```

The minted JWT is a normal user session and works on every endpoint, including the migration endpoints. The API token must have the `users.action_read` permission and the target user must belong to the same organization.

| Endpoint group | API token | JWT |
| --- | --- | --- |
| `POST /courses/`, `PUT /courses/{uuid}`, `DELETE /courses/{uuid}` | ✓ | ✓ |
| `POST /chapters/`, `PUT /chapters/{id}/...`, `DELETE /chapters/{id}` | ✓ | ✓ |
| `POST /activities/`, `/activities/video`, `/activities/external_video`, `/activities/documentpdf` | ✓ | ✓ |
| `POST /blocks/{image,video,pdf,audio}` | ✓ | ✓ |
| `POST /courses/migrate/upload` / `/suggest` / `/create` | ✗ | ✓ |

See [Authentication](/developers/api/authentication) for token issuance.

## The data model in one diagram

```
Organization (org_id)
└── Course (course_uuid, course_id)
    └── Chapter (chapter_uuid, chapter_id)
        └── Activity (activity_uuid, activity_id)
            └── (optional) Block (block_uuid)  ← media files referenced from a dynamic page
```

Two ID conventions to keep straight:

- **`*_uuid`** strings (e.g. `course_uuid`, `activity_uuid`, `chapter_uuid`) are the public identifiers used in URLs and most `GET` endpoints.
- **`*_id`** integers (e.g. `course_id`, `chapter_id`) are the internal primary keys. They are required when **creating** a child resource (a chapter needs `course_id`, an activity needs `chapter_id`).

Both are returned in every create response, so capture them as you go.

## Activity types at a glance

| `activity_type` | `activity_sub_type` | What it is | How content is supplied |
| --- | --- | --- | --- |
| `TYPE_DYNAMIC` | `SUBTYPE_DYNAMIC_PAGE` | Rich-text page (TipTap / ProseMirror) | JSON document in `content` |
| `TYPE_DYNAMIC` | `SUBTYPE_DYNAMIC_MARKDOWN` | Page rendered from a remote Markdown URL | `content: { markdown_url }` |
| `TYPE_DYNAMIC` | `SUBTYPE_DYNAMIC_EMBED` | Iframe embed (Google Doc, Notion, etc.) | `content: { embed_url }` |
| `TYPE_VIDEO` | `SUBTYPE_VIDEO_HOSTED` | Self-hosted video file | Multipart upload to `/activities/video` |
| `TYPE_VIDEO` | `SUBTYPE_VIDEO_YOUTUBE` | Embedded YouTube / Vimeo video | JSON `POST /activities/external_video` |
| `TYPE_DOCUMENT` | `SUBTYPE_DOCUMENT_PDF` | PDF document | Multipart upload to `/activities/documentpdf` |
| `TYPE_DOCUMENT` | `SUBTYPE_DOCUMENT_DOC` | Generic document | Reserved -- not exposed via dedicated upload endpoint |
| `TYPE_ASSIGNMENT` | `SUBTYPE_ASSIGNMENT_ANY` | Graded assignment with tasks | Three-step: activity shell + assignment record + at least one task |
| `TYPE_CUSTOM` | `SUBTYPE_CUSTOM` | Free-form structured content | JSON `content` of any shape |
| `TYPE_SCORM` | `SUBTYPE_SCORM_12` / `SUBTYPE_SCORM_2004` | SCORM packages | Reserved -- handled via the SCORM uploader |

The full per-type `content` JSON schemas, including the dynamic page block list, are documented in [Activity Types Reference](/developers/migration/activity-types).

## Quick start: the four building blocks

A complete migration boils down to four call types, in order:

1. **Create a course.** `POST /api/v1/courses/?org_id={org_id}` (multipart). Capture `course_uuid` and `id` from the response.
2. **Create chapters.** `POST /api/v1/chapters/` (JSON), one per chapter, passing `course_id` and `org_id`. Capture each chapter's `id`.
3. **Create activities.** Either the generic `POST /api/v1/activities/` (JSON, for dynamic / embed / markdown / custom / assignment shells) or one of the typed endpoints `/activities/video`, `/activities/external_video`, `/activities/documentpdf` (multipart, for hosted media).
4. **(Optional) Upload media blocks** referenced from a dynamic page via `/api/v1/blocks/{image,video,pdf,audio}` (multipart) and embed them in the page's TipTap content.

A copy-pasteable bash script for the full flow lives in [Programmatic Migration](/developers/migration/programmatic).

## Common pitfalls

**`chapter_id` and `course_id` are integers, not UUIDs.** Many `GET` endpoints take a UUID, but every `create` body wants the integer primary key. Read it from the previous response's `id` field, not its `chapter_uuid` / `course_uuid` field.

**Activity type is immutable.** You cannot change `activity_type` or `activity_sub_type` after creation. Delete and recreate the activity if you picked the wrong type.

**Modifying `content` creates a new version.** Each `PUT /api/v1/activities/{activity_uuid}` that touches `content` increments the activity's `current_version`. This is normal -- learners always see the published version -- but expect your migration to leave a tidy version history.

**Set `published: false` while migrating** and flip it to `true` only once you have spot-checked the result. Unpublished activities are returned by `GET /courses/{course_uuid}/meta?with_unpublished_activities=true` so you can preview the final tree before exposing it to learners.

**Typed-upload endpoints (`/activities/video`, `/activities/external_video`, `/activities/documentpdf`) always create activities with `published: false` regardless of any payload field.** Follow the create call with `PUT /api/v1/activities/{activity_uuid}` setting `{"published": true}` to publish them. Only the generic `POST /activities/` honours `published` on creation.

**`TYPE_ASSIGNMENT` is a three-step create.** A bare assignment activity renders as an empty panel. You also need to `POST /api/v1/assignments/` to attach the title/description/grading, and at least one `POST /api/v1/assignments/{uuid}/tasks` for a submission UI. See [Activity Types Reference -- Assignments](/developers/migration/activity-types#assignments).

**`TYPE_CUSTOM` has no built-in renderer.** A custom activity will appear as an empty container in the learner viewer until you ship your own React component for it. Prefer `SUBTYPE_DYNAMIC_PAGE` (TipTap) or `SUBTYPE_DYNAMIC_EMBED` (iframe) unless you specifically have custom frontend code in place.

## Where to next

- [Programmatic Migration](/developers/migration/programmatic) -- step-by-step guide with curl examples for each call.
- [Activity Types Reference](/developers/migration/activity-types) -- the exact `content` JSON shape for every activity sub-type, including TipTap blocks for dynamic pages.
- [AI-Assisted Migration](/developers/migration/assisted) -- the three-call upload / suggest / create flow for bulk file imports.

---

# Activity Types Reference
URL: https://docs.learnhouse.app/developers/migration/activity-types

Every activity in LearnHouse is described by two enums and one JSON `content` blob:

- `activity_type` -- one of `TYPE_DYNAMIC`, `TYPE_VIDEO`, `TYPE_DOCUMENT`, `TYPE_ASSIGNMENT`, `TYPE_CUSTOM`, `TYPE_SCORM`.
- `activity_sub_type` -- a more specific variant within the type (e.g. `SUBTYPE_VIDEO_YOUTUBE` vs `SUBTYPE_VIDEO_HOSTED`).
- `content` -- a JSON object whose shape depends on the sub-type.

This page is the canonical reference for what `content` (and `details`) must contain for each combination, alongside the create endpoint to use.

The list of valid types and sub-types is enforced by the API as Python enums. Sending an unknown value returns a 422 Unprocessable Entity. The full enum is reproduced at the bottom of this page.

## Dynamic activities

`activity_type: "TYPE_DYNAMIC"` -- pages rendered inside the activity viewer.

### Dynamic Page (`SUBTYPE_DYNAMIC_PAGE`)

The flagship activity type. `content` is a [TipTap](https://tiptap.dev/) / ProseMirror document.

**Create endpoint:** `POST /api/v1/activities/` (JSON body, see [Programmatic Migration](/developers/migration/programmatic#3a-generic-json-create----post-apiv1activities)).

**Initial content:** start empty (`"content": {}`) and update later, or send a complete document on creation:

```json
{
  "name": "Welcome to the course",
  "chapter_id": 7,
  "activity_type": "TYPE_DYNAMIC",
  "activity_sub_type": "SUBTYPE_DYNAMIC_PAGE",
  "content": {
    "type": "doc",
    "content": [
      {
        "type": "heading",
        "attrs": { "level": 1 },
        "content": [{ "type": "text", "text": "Welcome" }]
      },
      {
        "type": "paragraph",
        "content": [
          { "type": "text", "text": "This is a " },
          { "type": "text", "text": "bold", "marks": [{ "type": "bold" }] },
          { "type": "text", "text": " introduction." }
        ]
      },
      {
        "type": "bulletList",
        "content": [
          {
            "type": "listItem",
            "content": [{
              "type": "paragraph",
              "content": [{ "type": "text", "text": "Learning objective 1" }]
            }]
          },
          {
            "type": "listItem",
            "content": [{
              "type": "paragraph",
              "content": [{ "type": "text", "text": "Learning objective 2" }]
            }]
          }
        ]
      }
    ]
  }
}
```

The root must be `{ "type": "doc", "content": [...] }`. Each child is a block node.

#### Valid TipTap block types

The API validates dynamic-page content against this whitelist (unknown types are accepted but logged):

```
paragraph, heading, bulletList, orderedList, listItem,
codeBlock, table, tableRow, tableHeader, tableCell,
horizontalRule, hardBreak, text,

calloutInfo, calloutWarning,
blockImage, blockVideo, blockPDF, blockAudio, blockMathEquation,
blockEmbed, blockQuiz, blockUser, blockWebPreview,
flipcard, scenarios, button, badge
```

The `block*` types correspond to LearnHouse's custom node extensions. Standard TipTap block types (`paragraph`, `heading`, etc.) behave as in any TipTap editor.

#### Inline marks

Text nodes (`"type": "text"`) can carry inline marks:

```json
{ "type": "text", "text": "see link", "marks": [
  { "type": "link", "attrs": { "href": "https://example.com" } }
] }
```

Supported marks: `bold`, `italic`, `code`, `link`, plus the standard StarterKit marks.

The web client tolerates `strong` and `em` (HTML aliases) and rewrites them to `bold` / `italic` on render. Prefer `bold` / `italic` directly in API payloads.

#### Alternative: simplified blocks-only content

When the [AI-assisted migration](/developers/migration/assisted) creates a dynamic-page activity from a single image or audio file, it writes a simpler legacy shape instead of TipTap JSON:

```json
{
  "blocks": [
    {
      "block_uuid": "block_7522d174-...",
      "block_type": "BLOCK_IMAGE",
      "content": { "file_id": "3a80fc43-...", "file_format": "png" }
    }
  ]
}
```

The dynamic-page renderer accepts both shapes. Use the TipTap shape when authoring rich content; the simpler `blocks` shape exists primarily for migration-style media-only pages.

#### Embedding media blocks

Media blocks (`blockImage`, `blockVideo`, `blockPDF`, `blockAudio`) are atom nodes that point to a previously-uploaded Block via the `blockObject` attribute:

```json
{
  "type": "blockImage",
  "attrs": {
    "blockObject": {
      "block_uuid": "block_2a8...",
      "block_type": "BLOCK_IMAGE",
      "content": {
        "file_id": "block_a1b2c3...",
        "file_format": "png",
        "file_name": "diagram.png",
        "file_size": 24576,
        "file_type": "image/png",
        "activity_uuid": "activity_91c..."
      }
    },
    "size": { "width": 600 },
    "alignment": "center"
  }
}
```

The full `BlockRead` object returned by `POST /api/v1/blocks/image` (or `/video` / `/pdf` / `/audio`) goes into `attrs.blockObject`. Attribute defaults per block:

| Block node | Required attrs | Optional attrs |
| --- | --- | --- |
| `blockImage` | `blockObject` | `size: { width }`, `alignment` (`center`, `left`, `right`), `unsplash_*` |
| `blockVideo` | `blockObject` | -- |
| `blockPDF` | `blockObject` | -- |
| `blockAudio` | `blockObject` | -- |

#### Code blocks

Code blocks include a `language` attribute consumed by lowlight syntax highlighting:

```json
{
  "type": "codeBlock",
  "attrs": { "language": "python" },
  "content": [
    { "type": "text", "text": "def hello():\n    print(\"Hello, world!\")" }
  ]
}
```

Common languages: `python`, `javascript`, `typescript`, `java`, `cpp`, `c`, `rust`, `go`, `php`, `ruby`, `kotlin`, `csharp`, `swift`, `scala`, `perl`, `r`, plus anything supported by `lowlight`'s `common` set.

#### Quiz blocks

```json
{
  "type": "blockQuiz",
  "attrs": {
    "quizId": "quiz_1",
    "questions": [
      {
        "id": "q1",
        "question": "What does Python's print() do?",
        "options": [
          { "id": "a", "text": "Outputs to stdout", "correct": true },
          { "id": "b", "text": "Reads input", "correct": false }
        ]
      }
    ]
  }
}
```

The exact `questions` schema is the same one rendered by the editor's `QuizBlockComponent`. Inspect a real quiz in the editor and export the JSON if you need an authoritative shape -- it has evolved over time and is best treated as opaque to migration scripts.

### Dynamic Markdown (`SUBTYPE_DYNAMIC_MARKDOWN`)

Renders a Markdown file fetched from a remote URL.

```json
{
  "name": "README",
  "chapter_id": 7,
  "activity_type": "TYPE_DYNAMIC",
  "activity_sub_type": "SUBTYPE_DYNAMIC_MARKDOWN",
  "content": { "markdown_url": "https://github.com/user/repo/raw/main/README.md" }
}
```

The viewer fetches and renders the URL on each page load.

### Dynamic Embed (`SUBTYPE_DYNAMIC_EMBED`)

Renders an arbitrary URL inside an iframe (Google Docs, Notion, Figma, etc.):

```json
{
  "name": "Course brief",
  "chapter_id": 7,
  "activity_type": "TYPE_DYNAMIC",
  "activity_sub_type": "SUBTYPE_DYNAMIC_EMBED",
  "content": { "embed_url": "https://docs.google.com/document/d/abc123/edit" }
}
```

The embedded site must allow iframe embedding (`X-Frame-Options` / `Content-Security-Policy`). LearnHouse cannot work around a destination's frame-blocking headers.

## Video activities

`activity_type: "TYPE_VIDEO"`.

### Hosted video (`SUBTYPE_VIDEO_HOSTED`)

Created via the dedicated multipart endpoint -- you cannot create a hosted video by sending JSON to `/activities/`.

The endpoint creates the activity with `published: false` regardless of any payload field. To publish, follow up with `PUT /api/v1/activities/{activity_uuid}` setting `{"published": true}`. The same is true for `/activities/external_video` and `/activities/documentpdf`.

**Create endpoint:** `POST /api/v1/activities/video`

```bash
curl -X POST "http://localhost:1338/api/v1/activities/video" \
  -H "Authorization: Bearer lh_your_api_token" \
  -F 'name=Lesson 1 walkthrough' \
  -F 'chapter_id=7' \
  -F 'video_file=@./lesson-01.mp4;type=video/mp4' \
  -F 'details={"startTime":0,"endTime":null,"autoplay":false,"muted":false}'
```

`Content-Type` is checked strictly -- only `video/mp4` and `video/webm` are accepted. The server stores the file, builds the `content` object internally, and returns the resulting `ActivityRead`. The persisted `content` looks like:

```json
{
  "filename": "1e231d81-ae8a-4142-b165-e2b158057bc1_video.mp4",
  "activity_uuid": "activity_ec39ecc1-..."
}
```

`filename` is the safe-on-disk name LearnHouse generated; the player resolves it through `/api/v1/content/...`. The `details` form field is a JSON-encoded string with player options:

| `details` key | Type | Notes |
| --- | --- | --- |
| `startTime` | number (seconds) | Seek-to point on play |
| `endTime` | number or `null` | Stop point (omit to play to end) |
| `autoplay` | boolean | -- |
| `muted` | boolean | -- |

### External video (`SUBTYPE_VIDEO_YOUTUBE`)

For YouTube and Vimeo embeds. Note the sub-type name is historical -- the same sub-type covers Vimeo too, distinguished by the `type` field in the request.

**Create endpoint:** `POST /api/v1/activities/external_video`

```bash
curl -X POST "http://localhost:1338/api/v1/activities/external_video" \
  -H "Authorization: Bearer lh_your_api_token" \
  -H "Content-Type: application/json" \
  -d '{
    "name": "Intro lecture",
    "uri": "https://www.youtube.com/watch?v=dQw4w9WgXcQ",
    "type": "youtube",
    "chapter_id": "7",
    "details": "{\"startTime\":0,\"endTime\":null,\"autoplay\":false,\"muted\":false}"
  }'
```

| Field | Type | Required | Notes |
| --- | --- | --- | --- |
| `name` | string | Yes | Activity title |
| `uri` | string | Yes | YouTube or Vimeo URL |
| `type` | enum | Yes | `"youtube"` or `"vimeo"` |
| `chapter_id` | string | Yes | Numeric chapter ID, sent as a string |
| `details` | string | No | JSON-encoded player options (same keys as above), defaults to `"{}"` |

The persisted `content` is `{ uri, type, activity_uuid }`.

## Document activities

`activity_type: "TYPE_DOCUMENT"`.

### PDF (`SUBTYPE_DOCUMENT_PDF`)

**Create endpoint:** `POST /api/v1/activities/documentpdf`

```bash
curl -X POST "http://localhost:1338/api/v1/activities/documentpdf" \
  -H "Authorization: Bearer lh_your_api_token" \
  -F 'name=Course syllabus' \
  -F 'chapter_id=7' \
  -F 'pdf_file=@./syllabus.pdf;type=application/pdf'
```

`Content-Type` must be `application/pdf`. The persisted `content` is:

```json
{
  "filename": "9325f6f7-...-d4ecbfdc89c1_documentpdf.pdf",
  "activity_uuid": "activity_37d02abc-..."
}
```

The viewer renders the PDF with PDF.js.

### Generic document (`SUBTYPE_DOCUMENT_DOC`)

Reserved sub-type. There is no dedicated upload endpoint -- if you need to host arbitrary downloadable files, use a hosted-video-style upload via the editor UI, or wrap the file in a Block and reference it from a dynamic page.

## Assignments

`activity_type: "TYPE_ASSIGNMENT"`, `activity_sub_type: "SUBTYPE_ASSIGNMENT_ANY"`.

**An assignment activity on its own is an empty box.** The activity record is just a placeholder -- the title, description, due date, grading type, and any submission tasks live in a separate `Assignment` record. If you create the activity but skip the second step, learners see a blank panel. Treat both calls as a single transaction in your migration script.

An assignment is a **three-step** create when you want learners to actually submit something:

### Step 1 -- Create the activity shell

Generic `POST /api/v1/activities/`:

```json
{
  "name": "Final assignment",
  "chapter_id": 7,
  "activity_type": "TYPE_ASSIGNMENT",
  "activity_sub_type": "SUBTYPE_ASSIGNMENT_ANY",
  "content": {},
  "published": true
}
```

Capture `id` and `activity_uuid` from the response.

### Step 2 -- Create the linked Assignment record

`POST /api/v1/assignments/` with the assignment metadata. **All numeric IDs are required**:

```json
{
  "title": "Final assignment",
  "description": "Submit your final project.",
  "due_date": "2026-12-31",
  "grading_type": "PERCENTAGE",
  "published": true,
  "org_id": 1,
  "course_id": 17,
  "chapter_id": 7,
  "activity_id": 145,
  "auto_grading": false,
  "anti_copy_paste": false,
  "show_correct_answers": false
}
```

| Field | Type | Required | Notes |
| --- | --- | --- | --- |
| `title` | string | Yes | Shown in the assignment header |
| `description` | string | Yes | Body text |
| `due_date` | string (`YYYY-MM-DD`) | Yes | -- |
| `grading_type` | enum | Yes | `ALPHABET`, `NUMERIC`, `PERCENTAGE`, `PASS_FAIL`, `GPA_SCALE` |
| `org_id` / `course_id` / `chapter_id` / `activity_id` | int | Yes | All four foreign keys are required |
| `published` | boolean | No | Defaults `false` |
| `auto_grading` / `anti_copy_paste` / `show_correct_answers` | boolean | No | All default `false` |

The response includes `assignment_uuid`, which is the handle for step 3.

### Step 3 -- Add at least one Task

Without tasks, the assignment renders the description but has no submission UI. `POST /api/v1/assignments/{assignment_uuid}/tasks`:

```json
{
  "title": "Submit your project file",
  "description": "Upload a PDF of your final project.",
  "hint": "Use a clear filename.",
  "assignment_type": "FILE_SUBMISSION",
  "contents": {},
  "max_grade_value": 100
}
```

Task types (`assignment_type`): `FILE_SUBMISSION`, `QUIZ`, `FORM`, `CODE`, `SHORT_ANSWER`, `NUMBER_ANSWER`, `OTHER`. Each task type interprets `contents` differently -- the safest path for unknown types is `{}`. See the `/api/v1/assignments/` endpoint group in Swagger UI for the per-type contents schema.

**Anonymous learners** can view an assignment's structure (description, tasks, allowed file formats) on a public course, but the file upload form shows "Please sign in to upload files". Submission requires authentication. The metadata fetch (`GET /api/v1/assignments/activity/{activity_uuid}`) itself works anonymously.

## Custom

`activity_type: "TYPE_CUSTOM"`, `activity_sub_type: "SUBTYPE_CUSTOM"`.

A free-form activity. `content` is any JSON object you want -- the platform stores it verbatim and exposes it to a custom renderer that you supply on the frontend. Use this when no built-in type fits and you have your own UI for the activity.

```json
{
  "name": "Custom widget",
  "chapter_id": 7,
  "activity_type": "TYPE_CUSTOM",
  "activity_sub_type": "SUBTYPE_CUSTOM",
  "content": { "anything": "you want", "shape": [1, 2, 3] }
}
```

**Stock LearnHouse has no built-in renderer for `TYPE_CUSTOM`.** The activity will appear as an empty container in the learner viewer until you ship a custom frontend component for it. Treat `TYPE_CUSTOM` as a hook for your own integration code -- if you don't already have that integration, prefer `SUBTYPE_DYNAMIC_PAGE` (TipTap) or `SUBTYPE_DYNAMIC_EMBED` (iframe) instead.

## SCORM

`activity_type: "TYPE_SCORM"`, sub-types `SUBTYPE_SCORM_12` and `SUBTYPE_SCORM_2004`.

SCORM packages are uploaded through the editor UI -- the manifest (`imsmanifest.xml`) is parsed, files are extracted to storage, and the `content` is populated with launch metadata. Programmatic creation of SCORM activities is not currently exposed as a documented public endpoint; check the Swagger UI on a development instance for the latest interface.

## The full enum (verbatim)

Reproduced from `apps/api/src/db/courses/activities.py`:

```python
class ActivityTypeEnum(str, Enum):
    TYPE_VIDEO = "TYPE_VIDEO"
    TYPE_DOCUMENT = "TYPE_DOCUMENT"
    TYPE_DYNAMIC = "TYPE_DYNAMIC"
    TYPE_ASSIGNMENT = "TYPE_ASSIGNMENT"
    TYPE_CUSTOM = "TYPE_CUSTOM"
    TYPE_SCORM = "TYPE_SCORM"

class ActivitySubTypeEnum(str, Enum):
    # Dynamic
    SUBTYPE_DYNAMIC_PAGE = "SUBTYPE_DYNAMIC_PAGE"
    SUBTYPE_DYNAMIC_MARKDOWN = "SUBTYPE_DYNAMIC_MARKDOWN"
    SUBTYPE_DYNAMIC_EMBED = "SUBTYPE_DYNAMIC_EMBED"
    # Video
    SUBTYPE_VIDEO_YOUTUBE = "SUBTYPE_VIDEO_YOUTUBE"
    SUBTYPE_VIDEO_HOSTED = "SUBTYPE_VIDEO_HOSTED"
    # Document
    SUBTYPE_DOCUMENT_PDF = "SUBTYPE_DOCUMENT_PDF"
    SUBTYPE_DOCUMENT_DOC = "SUBTYPE_DOCUMENT_DOC"
    # Assignment
    SUBTYPE_ASSIGNMENT_ANY = "SUBTYPE_ASSIGNMENT_ANY"
    # Custom
    SUBTYPE_CUSTOM = "SUBTYPE_CUSTOM"
    # SCORM
    SUBTYPE_SCORM_12 = "SUBTYPE_SCORM_12"
    SUBTYPE_SCORM_2004 = "SUBTYPE_SCORM_2004"

class ActivityLockType(str, Enum):
    PUBLIC = "public"                # anyone, including anonymous, can view
    AUTHENTICATED = "authenticated"  # must be signed in
    RESTRICTED = "restricted"        # only members of assigned usergroups
```

---

# AI-Assisted Migration
URL: https://docs.learnhouse.app/developers/migration/assisted

LearnHouse exposes a three-call API that uploads a folder of media files, asks Gemini to organise them into chapters and activities, and then creates the entire course in a single transaction. This is the right path when you have a directory full of legacy lecture recordings, PDFs, and images but no existing structure.

All three endpoints live under `/api/v1/courses/migrate/`. They require an **authenticated user session (JWT)** with permission to create courses in the target organization.

**API tokens are blocked here.** Unlike the standard course/chapter/activity endpoints, the migration endpoints reject requests authenticated with an `lh_*` API token (`HTTP 403: API tokens cannot access this resource. Only user authentication is allowed.`). If you only have an API token, use the **admin token-swap** to mint a JWT first:

```bash
JWT=$(curl -s -X POST 'http://localhost:1338/api/v1/admin/{org_slug}/auth/token' \
  -H 'Authorization: Bearer lh_your_api_token' \
  -H 'Content-Type: application/json' \
  -d '{"user_id": 1}' | jq -r .access_token)

# Now use $JWT for the migrate/* calls
curl -X POST "http://localhost:1338/api/v1/courses/migrate/upload?org_id=1" \
  -H "Authorization: Bearer $JWT" -F 'files=@./video.mp4'
```

The token-swap endpoint requires the API token to have the `users.action_read` permission and the target user must belong to the same organization.

## When to use this vs. programmatic migration

| Situation | Use |
| --- | --- |
| You have a clean export from another LMS with a known chapter / activity layout | [Programmatic Migration](/developers/migration/programmatic) |
| You need every detail of the resulting tree to be exact (titles, ordering, types) | Programmatic |
| You have a pile of files and want LearnHouse to propose a structure | AI-assisted (this page) |
| You want to author rich-text dynamic pages | Programmatic (AI-assisted produces media-only activities) |

The assisted flow only handles **media files** -- video, PDF, image, and audio. It does not import HTML, Markdown, or rich-text content into dynamic pages. For text-heavy migrations, write a programmatic script.

## Supported file types

| Extension | Resulting activity | Sub-type |
| --- | --- | --- |
| `mp4`, `webm`, `mov` | `TYPE_VIDEO` | `SUBTYPE_VIDEO_HOSTED` |
| `pdf` | `TYPE_DOCUMENT` | `SUBTYPE_DOCUMENT_PDF` |
| `png`, `jpg`, `jpeg`, `webp` | `TYPE_DYNAMIC` (image block) | `SUBTYPE_DYNAMIC_PAGE` |
| `mp3`, `wav` | `TYPE_DYNAMIC` (audio block) | `SUBTYPE_DYNAMIC_PAGE` |

Files with any other extension are skipped. Per-file size limit is **5 GB**, and total upload size per migration is **20 GB**.

## Endpoint overview

| # | Method | Path | Purpose |
| --- | --- | --- | --- |
| 1 | `POST` | `/api/v1/courses/migrate/upload?org_id={org_id}` | Upload one or more files to a temporary holding area. Returns a `temp_id`. |
| 2 | `POST` | `/api/v1/courses/migrate/suggest?org_id={org_id}` | Ask Gemini to propose a course tree from the uploaded files. Returns the structure for you to review. |
| 3 | `POST` | `/api/v1/courses/migrate/create?org_id={org_id}` | Commit the (possibly edited) structure: creates the course, chapters, activities, and uploads each file to its final destination. |

Temporary uploads older than 60 minutes are garbage-collected automatically, so finish a migration in one sitting.

## Step 1 -- Upload files

Upload up to 20 GB of files in one or more requests. Pass `temp_id` on subsequent requests to append to the same migration package:

```bash
# First batch -- creates a new temp_id
curl -X POST "http://localhost:1338/api/v1/courses/migrate/upload?org_id=1" \
  -H "Authorization: Bearer lh_your_api_token" \
  -F 'files=@./lectures/lesson-01.mp4' \
  -F 'files=@./lectures/lesson-02.mp4' \
  -F 'files=@./handouts/syllabus.pdf'
```

Response:

```json
{
  "temp_id": "9c4e3...-d8f1-4...",
  "files": [
    {
      "file_id": "f1a2b3...",
      "filename": "lesson-01.mp4",
      "file_type": "video/mp4",
      "size": 41943040,
      "extension": "mp4"
    },
    ...
  ],
  "skipped": []
}
```

Append more files to the same `temp_id`:

```bash
curl -X POST "http://localhost:1338/api/v1/courses/migrate/upload?org_id=1&temp_id=9c4e3...-d8f1-4..." \
  -H "Authorization: Bearer lh_your_api_token" \
  -F 'files=@./images/diagram-01.png'
```

`skipped` lists files rejected because of unsupported extension or size. They do not count against the total but you should re-encode and re-upload if you need them.

The server limits concurrent uploads to **3 simultaneous requests per process**. If you parallelise the upload of a large package, throttle yourself accordingly.

## Step 2 -- Ask for a suggested structure

Send the `temp_id` and a course name; Gemini groups the files into chapters and proposes activity titles:

```bash
curl -X POST "http://localhost:1338/api/v1/courses/migrate/suggest?org_id=1" \
  -H "Authorization: Bearer lh_your_api_token" \
  -H "Content-Type: application/json" \
  -d '{
    "temp_id": "9c4e3...-d8f1-4...",
    "course_name": "Introduction to Astronomy",
    "description": "Self-paced intro to astronomy concepts."
  }'
```

Response:

```json
{
  "course_name": "Introduction to Astronomy",
  "course_description": "Self-paced intro to astronomy concepts.",
  "chapters": [
    {
      "name": "Foundations",
      "activities": [
        {
          "name": "Course syllabus",
          "activity_type": "TYPE_DOCUMENT",
          "activity_sub_type": "SUBTYPE_DOCUMENT_PDF",
          "file_ids": ["f3c4d5..."]
        },
        {
          "name": "Lecture 1 -- The night sky",
          "activity_type": "TYPE_VIDEO",
          "activity_sub_type": "SUBTYPE_VIDEO_HOSTED",
          "file_ids": ["f1a2b3..."]
        }
      ]
    },
    {
      "name": "The solar system",
      "activities": [...]
    }
  ]
}
```

The AI prompt is parameterised by file extensions (see the table at the top of this page), so the suggested types are deterministic per extension; only the **names**, **chapter grouping**, and **ordering** are AI-generated.

If the AI call fails or quota is exhausted, the endpoint falls back to a **flat structure** -- a single chapter named "Content" containing one activity per file, with names derived from filenames. This guarantees you can still complete the migration even if the AI service is degraded.

### Editing the suggestion

The structure is just JSON -- mutate it in your client however you like before posting to step 3. Common edits:

- Rename chapters and activities
- Move activities between chapters (move a `file_ids` entry between activities, or duplicate the activity object)
- Split or merge chapters
- Reorder activities (the order in the array becomes the activity order)
- Drop an activity by removing it from the array (its file will simply not be imported)

The only constraints are that every `file_id` you reference must exist in the manifest, every `activity_type` / `activity_sub_type` must be a valid enum value, and every file should be referenced by **at most one activity** (referencing the same file twice will fail on the second copy).

## Step 3 -- Create the course

Post the (possibly edited) structure back with the same `temp_id`. The server creates the course, chapters, activities, and copies each file from the temporary upload area to its final location -- all in a single database transaction:

```bash
curl -X POST "http://localhost:1338/api/v1/courses/migrate/create?org_id=1" \
  -H "Authorization: Bearer lh_your_api_token" \
  -H "Content-Type: application/json" \
  -d '{
    "temp_id": "9c4e3...-d8f1-4...",
    "structure": {
      "course_name": "Introduction to Astronomy",
      "course_description": "Self-paced intro to astronomy concepts.",
      "chapters": [
        {
          "name": "Foundations",
          "activities": [
            {
              "name": "Course syllabus",
              "activity_type": "TYPE_DOCUMENT",
              "activity_sub_type": "SUBTYPE_DOCUMENT_PDF",
              "file_ids": ["f3c4d5..."]
            }
          ]
        }
      ]
    }
  }'
```

Response:

```json
{
  "course_uuid": "course_b7e1...",
  "course_name": "Introduction to Astronomy",
  "chapters_created": 3,
  "activities_created": 12,
  "success": true,
  "error": null
}
```

The created course is **unpublished and private** by default (`public: false`, `published: false`). Visit `/{org_slug}/courses/{course_uuid}/edit` in the dashboard to review and publish it, or use `PUT /api/v1/courses/{course_uuid}` to publish programmatically.

If anything fails (database error, file copy failure, missing files), the entire transaction is rolled back and `success` is `false` with the error in `error`. The temporary upload directory is cleaned up either way -- start over from step 1 with a fresh upload.

## End-to-end script (bash)

```bash
#!/usr/bin/env bash
set -euo pipefail

API=http://localhost:1338/api/v1
API_TOKEN=lh_your_api_token        # Pro-plan API token
ORG_SLUG=default
ORG_ID=1
USER_ID=1                          # the user to act as
COURSE_NAME="Migrated content"

# 0. Swap the API token for a user JWT (migrate/* endpoints reject API tokens)
TOKEN=$(curl -fsS -X POST "$API/admin/$ORG_SLUG/auth/token" \
  -H "Authorization: Bearer $API_TOKEN" \
  -H "Content-Type: application/json" \
  -d "{\"user_id\":$USER_ID}" | jq -r .access_token)

# 1. Upload everything in ./content/
UPLOAD_RESP=$(curl -fsS -X POST "$API/courses/migrate/upload?org_id=$ORG_ID" \
  -H "Authorization: Bearer $TOKEN" \
  $(for f in ./content/*; do echo -n "-F files=@$f "; done))
TEMP_ID=$(echo "$UPLOAD_RESP" | jq -r '.temp_id')

# 2. Suggest structure
STRUCTURE=$(curl -fsS -X POST "$API/courses/migrate/suggest?org_id=$ORG_ID" \
  -H "Authorization: Bearer $TOKEN" \
  -H "Content-Type: application/json" \
  -d "{\"temp_id\":\"$TEMP_ID\",\"course_name\":\"$COURSE_NAME\"}")

# 3. (Optional) Edit the structure here, e.g. with `jq` -- skipped in this example.

# 4. Create the course
curl -fsS -X POST "$API/courses/migrate/create?org_id=$ORG_ID" \
  -H "Authorization: Bearer $TOKEN" \
  -H "Content-Type: application/json" \
  -d "{\"temp_id\":\"$TEMP_ID\",\"structure\":$STRUCTURE}"
```

## Cleaning up

If you abandon a migration mid-way, the temporary directory is deleted automatically after 60 minutes by the periodic cleanup task. There is no public endpoint to delete a `temp_id` early -- if you need to retry immediately, just start a new upload (you will get a new `temp_id`).

A successfully completed migration leaves no temporary state behind: step 3 deletes the temp directory once the transaction commits.

## Limitations

- **Media only.** Text content (Markdown, HTML, rich text) is not imported. The dynamic-page activities created from images and audio contain a single block referencing the file; no surrounding prose is generated.
- **Single-chapter fallback.** If Gemini is unavailable, every file lands in one chapter named "Content". You can edit the structure before step 3 to rearrange.
- **No assignments / quizzes / SCORM.** The flow does not infer interactive content from media. Create those separately via the programmatic flow.
- **One file per activity.** Each migrated activity references exactly one source file. If you need an activity that combines multiple files (e.g. a dynamic page with several images), build that with the programmatic flow.

For anything beyond the limits above, drop down to [Programmatic Migration](/developers/migration/programmatic) -- you can also use the assisted flow for the bulk of media and follow up with programmatic calls to add rich-text pages, assignments, and quizzes.

---

# Programmatic Migration
URL: https://docs.learnhouse.app/developers/migration/programmatic

This guide walks through the full sequence of API calls needed to build a course from scratch -- the same calls the LearnHouse web UI makes when an editor clicks through the dashboard. Use it as a reference when writing your own migration script.

The base URL in every example is `http://localhost:1338/api/v1` -- replace it with your instance domain.

All examples use an API token (`Authorization: Bearer lh_...`). A user JWT works identically.

## 1. Create the course

```bash
curl -X POST "http://localhost:1338/api/v1/courses/?org_id=1" \
  -H "Authorization: Bearer lh_your_api_token" \
  -F 'name=Introduction to Python' \
  -F 'description=A beginner-friendly Python course' \
  -F 'public=false' \
  -F 'about=Hands-on Python from zero to writing your first scripts.' \
  -F 'thumbnail_type=image' \
  -F 'thumbnail=@./thumbnail.png'
```

`org_id` is a query parameter on the create endpoint. The body is **multipart form data** because the same call optionally uploads a thumbnail image or video.

| Field | Type | Required | Notes |
| --- | --- | --- | --- |
| `name` | string | Yes | Course title |
| `description` | string | Yes | Short description (one-liner) |
| `about` | string | Yes | Long-form description shown on the course page |
| `public` | boolean | Yes | `true` = listed publicly, `false` = members only |
| `thumbnail_type` | enum | No | `image` (default) or `video` |
| `thumbnail` | file | No | Image or video file matching `thumbnail_type` |
| `learnings` | string | No | JSON-encoded array of learning objectives |
| `tags` | string | No | JSON-encoded array of tags |

The response is a `CourseRead`:

```json
{
  "id": 42,
  "course_uuid": "course_8e3...",
  "org_id": 1,
  "name": "Introduction to Python",
  "description": "A beginner-friendly Python course",
  "about": "Hands-on Python from zero to writing your first scripts.",
  "public": false,
  "published": false,
  "thumbnail_type": "image",
  "thumbnail_image": "thumbnail.png",
  "thumbnail_video": "",
  "creation_date": "2026-04-25 10:00:00",
  "update_date": "2026-04-25 10:00:00",
  "authors": [...]
}
```

**Capture both `id` and `course_uuid`.** You will need `id` (integer) to create chapters, and `course_uuid` to fetch, update, or delete the course later.

## 2. Create chapters

Chapters are created one at a time with a JSON body:

```bash
curl -X POST "http://localhost:1338/api/v1/chapters/" \
  -H "Authorization: Bearer lh_your_api_token" \
  -H "Content-Type: application/json" \
  -d '{
    "name": "Chapter 1 — Getting set up",
    "description": "Install Python, pick an editor, write hello world.",
    "course_id": 42,
    "org_id": 1,
    "lock_type": "public"
  }'
```

| Field | Type | Required | Notes |
| --- | --- | --- | --- |
| `name` | string | Yes | Chapter title |
| `course_id` | integer | Yes | Course primary key from step 1 |
| `org_id` | integer | Yes | Same org as the course |
| `description` | string | No | Short description |
| `thumbnail_image` | string | No | URL or path to a thumbnail |
| `lock_type` | enum | No | `public` (default), `authenticated`, or `restricted` |

Response (`ChapterRead`):

```json
{
  "id": 7,
  "chapter_uuid": "chapter_4d1...",
  "name": "Chapter 1 — Getting set up",
  "description": "Install Python, pick an editor, write hello world.",
  "course_id": 42,
  "org_id": 1,
  "lock_type": "public",
  "is_locked": false,
  "activities": [],
  "creation_date": "...",
  "update_date": "..."
}
```

Capture `id` -- it is the `chapter_id` you will pass when creating activities.

Chapters appear in the order they are created. To rearrange them later (or to reorder activities inside a chapter), call `PUT /api/v1/chapters/course/{course_uuid}/order` with the desired ordering. See [Reordering](#reordering) below.

## 3. Create activities

There are three families of activity-create endpoints, depending on the activity type:

### 3a. Generic JSON create -- `POST /api/v1/activities/`

Use this for **dynamic pages, markdown pages, embeds, assignments (shell), and custom activities**. The body is `ActivityCreate`:

```bash
curl -X POST "http://localhost:1338/api/v1/activities/" \
  -H "Authorization: Bearer lh_your_api_token" \
  -H "Content-Type: application/json" \
  -d '{
    "name": "Hello, world",
    "chapter_id": 7,
    "activity_type": "TYPE_DYNAMIC",
    "activity_sub_type": "SUBTYPE_DYNAMIC_PAGE",
    "content": {},
    "details": {},
    "published": false,
    "lock_type": "public"
  }'
```

| Field | Type | Required | Notes |
| --- | --- | --- | --- |
| `name` | string | Yes | Activity title |
| `chapter_id` | integer | Yes | Chapter primary key from step 2 |
| `activity_type` | enum | Yes | See [Activity Types Reference](/developers/migration/activity-types) |
| `activity_sub_type` | enum | Yes | Sub-type for the chosen `activity_type` |
| `content` | object | Yes | Per-type JSON payload (see reference) |
| `details` | object | No | Per-type metadata (e.g. video player options) |
| `published` | boolean | No | Defaults to `false` |
| `lock_type` | enum | No | `public`, `authenticated`, or `restricted` |

The response is an `ActivityRead`. Capture `id` and `activity_uuid` -- you will need `activity_uuid` if you plan to upload media blocks for a dynamic page, and to update `content` later.

### 3b. Hosted video upload -- `POST /api/v1/activities/video`

Multipart form data. Creates a `TYPE_VIDEO` / `SUBTYPE_VIDEO_HOSTED` activity in one call:

```bash
curl -X POST "http://localhost:1338/api/v1/activities/video" \
  -H "Authorization: Bearer lh_your_api_token" \
  -F 'name=Lesson 1 walkthrough' \
  -F 'chapter_id=7' \
  -F 'video_file=@./lesson-01.mp4;type=video/mp4' \
  -F 'details={"startTime":0,"endTime":null,"autoplay":false,"muted":false}'
```

`chapter_id` is sent as a string in the form -- it is parsed to an integer server-side.

The endpoint validates `Content-Type` strictly: only `video/mp4` and `video/webm` are accepted. Curl's automatic content-type detection works for real `.mp4` / `.webm` files, but if the upload is rejected with `"Video : Wrong video format"`, append `;type=video/mp4` (or `video/webm`) to the `-F` argument to set it explicitly.

### 3c. External video -- `POST /api/v1/activities/external_video`

JSON body. Creates a `TYPE_VIDEO` / `SUBTYPE_VIDEO_YOUTUBE` activity that embeds an external player:

```bash
curl -X POST "http://localhost:1338/api/v1/activities/external_video" \
  -H "Authorization: Bearer lh_your_api_token" \
  -H "Content-Type: application/json" \
  -d '{
    "name": "Intro lecture",
    "uri": "https://www.youtube.com/watch?v=dQw4w9WgXcQ",
    "type": "youtube",
    "chapter_id": "7",
    "details": "{\"startTime\":0,\"endTime\":null,\"autoplay\":false,\"muted\":false}"
  }'
```

`type` accepts `"youtube"` or `"vimeo"`. `chapter_id` and `details` are both **strings** for this endpoint -- `details` is a JSON-encoded string that the server parses.

### 3d. PDF document -- `POST /api/v1/activities/documentpdf`

Multipart form data. Creates a `TYPE_DOCUMENT` / `SUBTYPE_DOCUMENT_PDF` activity:

```bash
curl -X POST "http://localhost:1338/api/v1/activities/documentpdf" \
  -H "Authorization: Bearer lh_your_api_token" \
  -F 'name=Course syllabus' \
  -F 'chapter_id=7' \
  -F 'pdf_file=@./syllabus.pdf;type=application/pdf'
```

`Content-Type` must be exactly `application/pdf`, otherwise the server returns `"Pdf : Wrong pdf format"`. As with video uploads, curl auto-detects this for real PDFs but `;type=application/pdf` makes it explicit.

### 3e. Assignments (three-step)

An assignment is **never just an activity**. It is an activity shell + an `Assignment` record + at least one `AssignmentTask`. Skip any of those steps and learners see a blank panel. Full sequence:

```bash
# 1. Activity shell
ACT=$(curl -fsS -X POST "http://localhost:1338/api/v1/activities/" \
  -H "Authorization: Bearer lh_your_api_token" \
  -H "Content-Type: application/json" \
  -d '{
    "name": "Final project",
    "chapter_id": 7,
    "activity_type": "TYPE_ASSIGNMENT",
    "activity_sub_type": "SUBTYPE_ASSIGNMENT_ANY",
    "content": {},
    "published": true
  }')
ACT_ID=$(echo "$ACT" | jq -r .id)

# 2. Assignment record (all four foreign keys are required)
ASSIGN=$(curl -fsS -X POST "http://localhost:1338/api/v1/assignments/" \
  -H "Authorization: Bearer lh_your_api_token" \
  -H "Content-Type: application/json" \
  -d "{
    \"title\":\"Final project\",
    \"description\":\"Submit your final project.\",
    \"due_date\":\"2026-12-31\",
    \"grading_type\":\"PERCENTAGE\",
    \"published\":true,
    \"org_id\":1,
    \"course_id\":42,
    \"chapter_id\":7,
    \"activity_id\":$ACT_ID
  }")
ASSIGN_UUID=$(echo "$ASSIGN" | jq -r .assignment_uuid)

# 3. At least one task — without this the assignment renders without a submission UI
curl -fsS -X POST "http://localhost:1338/api/v1/assignments/$ASSIGN_UUID/tasks" \
  -H "Authorization: Bearer lh_your_api_token" \
  -H "Content-Type: application/json" \
  -d '{
    "title":"Submit your project file",
    "description":"Upload a PDF of your final project.",
    "hint":"Use a clear filename.",
    "assignment_type":"FILE_SUBMISSION",
    "contents":{},
    "max_grade_value":100
  }'
```

See [Activity Types Reference -- Assignments](/developers/migration/activity-types#assignments) for the full field list, supported `grading_type` values, and `assignment_type` task types (`FILE_SUBMISSION`, `QUIZ`, `FORM`, `CODE`, `SHORT_ANSWER`, `NUMBER_ANSWER`, `OTHER`).

## 4. (Optional) Add media blocks to a dynamic page

For `SUBTYPE_DYNAMIC_PAGE` activities, images / videos / PDFs / audio can be embedded inline. The recommended flow is:

1. Upload the file to a Block via `POST /api/v1/blocks/{image|video|pdf|audio}`.
2. Embed the returned `BlockRead` object as the `blockObject` attribute of a TipTap node inside the activity's `content`.
3. Persist the updated `content` via `PUT /api/v1/activities/{activity_uuid}`.

Upload an image block:

```bash
curl -X POST "http://localhost:1338/api/v1/blocks/image" \
  -H "Authorization: Bearer lh_your_api_token" \
  -F 'activity_uuid=activity_91c...' \
  -F 'file_object=@./diagram.png'
```

Response:

```json
{
  "id": 13,
  "block_uuid": "block_2a8...",
  "block_type": "BLOCK_IMAGE",
  "content": {
    "file_id": "90b8f12e-fb6b-4726-85ef-f6b511e319e5_block_2a8...",
    "file_format": "png",
    "file_name": "diagram.png",
    "file_size": 24576,
    "file_type": "image/png",
    "activity_uuid": "activity_91c..."
  },
  "org_id": 1,
  "course_id": 42,
  "chapter_id": null,
  "activity_id": 99,
  "creation_date": "...",
  "update_date": "..."
}
```

`content.file_id` is a compound identifier (a UUID, an underscore, then the block UUID). Treat it as opaque -- the renderer uses it as-is to fetch the asset from `/api/v1/content/...`.

You can then reference this block from a TipTap `blockImage` node inside the activity's `content`. See [Activity Types Reference -- Dynamic Page](/developers/migration/activity-types#dynamic-page-subtype_dynamic_page) for the exact node shape.

The four block endpoints are symmetric:

| Endpoint | Allowed file extensions | Resulting `block_type` |
| --- | --- | --- |
| `POST /api/v1/blocks/image` | `jpg, jpeg, png, gif, webp` | `BLOCK_IMAGE` |
| `POST /api/v1/blocks/video` | `mp4, webm` | `BLOCK_VIDEO` |
| `POST /api/v1/blocks/pdf` | `pdf` | `BLOCK_DOCUMENT_PDF` |
| `POST /api/v1/blocks/audio` | `mp3, wav, ogg, m4a` | `BLOCK_AUDIO` |

All four take the same form fields: `file_object` (the file) and `activity_uuid` (the parent activity).

## 5. Update an activity's content

After creating a dynamic-page activity (`content: {}`), upload any media blocks, then `PUT` the full TipTap document:

```bash
curl -X PUT "http://localhost:1338/api/v1/activities/activity_91c..." \
  -H "Authorization: Bearer lh_your_api_token" \
  -H "Content-Type: application/json" \
  -d '{
    "content": {
      "type": "doc",
      "content": [
        { "type": "heading", "attrs": { "level": 1 },
          "content": [{ "type": "text", "text": "Hello, world" }] },
        { "type": "paragraph",
          "content": [{ "type": "text", "text": "Welcome to the course." }] }
      ]
    }
  }'
```

The full list of valid TipTap node types is in [Activity Types Reference](/developers/migration/activity-types#valid-tiptap-block-types).

`ActivityUpdate` accepts a partial body -- only fields you set are changed. Updateable fields:

| Field | Type | Notes |
| --- | --- | --- |
| `name` | string | Activity title |
| `content` | object | Replaces the entire content document |
| `details` | object | Replaces the details object |
| `published` | boolean | Flip to `true` when ready to publish |
| `lock_type` | enum | Access control |
| `published_version` / `version` | int | Advanced versioning -- usually leave alone |

`activity_type` and `activity_sub_type` are technically updateable in the schema but should be treated as immutable in practice -- the persisted `content` shape will not match the new type.

## Reordering

Chapters and the activities inside them appear in the order they were created. To explicitly set ordering, call:

```bash
curl -X PUT "http://localhost:1338/api/v1/chapters/course/course_8e3.../order" \
  -H "Authorization: Bearer lh_your_api_token" \
  -H "Content-Type: application/json" \
  -d '{
    "chapter_order_by_ids": [
      { "chapter_id": 7,  "activities_order_by_ids": [{"activity_id": 99}, {"activity_id": 100}] },
      { "chapter_id": 8,  "activities_order_by_ids": [{"activity_id": 101}] }
    ]
  }'
```

The path takes the `course_uuid`.

**This endpoint is destructive.** It re-specifies the entire course tree -- every chapter you omit from `chapter_order_by_ids` is unlinked from the course, and every activity you omit from a chapter's `activities_order_by_ids` is unlinked from that chapter. The underlying Activity / Chapter rows are not deleted, but they are removed from the course's table of contents and learners will no longer see them.

Always:
- Fetch the current tree first via `GET /api/v1/courses/{course_uuid}/meta?with_unpublished_activities=true&slim=true`,
- Build the reorder payload from that tree (modifying only the order),
- Then `PUT` it back.

Sending an empty `activities_order_by_ids` for a chapter wipes that chapter's activities from the course.

## Publishing

When the migration is complete, flip the course and each activity to `published: true`:

```bash
# Publish the course
curl -X PUT "http://localhost:1338/api/v1/courses/course_8e3..." \
  -H "Authorization: Bearer lh_your_api_token" \
  -H "Content-Type: application/json" \
  -d '{ "published": true }'

# Publish an activity
curl -X PUT "http://localhost:1338/api/v1/activities/activity_91c..." \
  -H "Authorization: Bearer lh_your_api_token" \
  -H "Content-Type: application/json" \
  -d '{ "published": true }'
```

To preview unpublished work, fetch the course tree with the `with_unpublished_activities` flag:

```bash
curl "http://localhost:1338/api/v1/courses/course_8e3.../meta?with_unpublished_activities=true" \
  -H "Authorization: Bearer lh_your_api_token"
```

## End-to-end script (bash)

The script below creates a complete, public, published course with **one of every activity type** -- a thumbnail, three chapters, a TipTap dynamic page with an embedded image block, a remote-Markdown page, an iframe embed, a hosted MP4, a YouTube embed, a PDF, and a fully-functional assignment with one File Submission task. It is the same flow used to validate this documentation against a live instance.

Save the assets you want to use to a folder (the script expects `thumbnail.jpg`, `diagram.jpg`, `clip.mp4`, `doc.pdf`) and run it. Total runtime is under 10 seconds against a local dev instance.

**Pre-requisites:** `bash`, `curl`, `jq`, and `python3` (for one inline JSON-builder). The script uses the API-token-to-JWT swap so it works with either an `lh_*` API token (the recommended setup) or by replacing `TOKEN=...` with a JWT you already have.

```bash
#!/usr/bin/env bash
# build-demo-course.sh — create a complete course end-to-end via the LearnHouse API.
set -euo pipefail

# ── Config ───────────────────────────────────────────────────────────────────
API=http://localhost:1338/api/v1
API_TOKEN=lh_your_api_token        # Pro-plan API token
ORG_SLUG=default                   # your org slug
ORG_ID=1                           # your org id
USER_ID=1                          # which user the script acts as
ASSETS=./assets                    # folder containing thumbnail.jpg, diagram.jpg, clip.mp4, doc.pdf

# ── 0. Mint a user JWT from the API token ───────────────────────────────────
# (Most endpoints accept the API token directly, but the JWT path is universal
# — including the AI-assisted migration endpoints which reject API tokens.)
TOKEN=$(curl -fsS -X POST "$API/admin/$ORG_SLUG/auth/token" \
  -H "Authorization: Bearer $API_TOKEN" \
  -H 'Content-Type: application/json' \
  -d "{\"user_id\":$USER_ID}" | jq -r .access_token)

# Tiny helpers
post_json() { curl -fsS -X POST "$1" -H "Authorization: Bearer $TOKEN" -H 'Content-Type: application/json' -d "$2"; }
put_json()  { curl -fsS -X PUT  "$1" -H "Authorization: Bearer $TOKEN" -H 'Content-Type: application/json' -d "$2"; }

# ── 1. Course (multipart, with a real JPEG thumbnail) ───────────────────────
COURSE=$(curl -fsS -X POST "$API/courses/?org_id=$ORG_ID" \
  -H "Authorization: Bearer $TOKEN" \
  -F 'name=The Complete Demo Course' \
  -F 'description=One of every activity type, built via the API' \
  -F 'about=Created end-to-end by the LearnHouse migration quickstart script.' \
  -F 'public=true' \
  -F 'thumbnail_type=image' \
  -F "thumbnail=@$ASSETS/thumbnail.jpg;type=image/jpeg")
CID=$(echo "$COURSE" | jq -r .id)
CUUID=$(echo "$COURSE" | jq -r .course_uuid)
echo "→ course $CUUID (id=$CID)"

# ── 2. Three chapters ───────────────────────────────────────────────────────
CH1_ID=$(post_json "$API/chapters/" \
  "{\"name\":\"1. Dynamic content\",\"description\":\"Pages, embeds, markdown\",\"course_id\":$CID,\"org_id\":$ORG_ID}" | jq -r .id)
CH2_ID=$(post_json "$API/chapters/" \
  "{\"name\":\"2. Media\",\"description\":\"Hosted video, YouTube, PDF\",\"course_id\":$CID,\"org_id\":$ORG_ID}" | jq -r .id)
CH3_ID=$(post_json "$API/chapters/" \
  "{\"name\":\"3. Interactive\",\"description\":\"Assignment\",\"course_id\":$CID,\"org_id\":$ORG_ID}" | jq -r .id)

# ── 3a. Dynamic Page (TipTap content with an embedded image block) ──────────
# Create the activity with empty content first, then upload an image block,
# then PUT the full TipTap document referencing that block.
PAGE=$(post_json "$API/activities/" \
  "{\"name\":\"Welcome page\",\"chapter_id\":$CH1_ID,\"activity_type\":\"TYPE_DYNAMIC\",\"activity_sub_type\":\"SUBTYPE_DYNAMIC_PAGE\",\"content\":{},\"published\":true}")
PAGE_UUID=$(echo "$PAGE" | jq -r .activity_uuid)

BLOCK=$(curl -fsS -X POST "$API/blocks/image" \
  -H "Authorization: Bearer $TOKEN" \
  -F "activity_uuid=$PAGE_UUID" \
  -F "file_object=@$ASSETS/diagram.jpg;type=image/jpeg")
echo "$BLOCK" > /tmp/lh-block.json

# Build the TipTap document — the image block is embedded as a `blockImage`
# atom node whose `attrs.blockObject` carries the full BlockRead response.
TIPTAP=$(python3 - <<'PY'

block = json.load(open('/tmp/lh-block.json'))
doc = {
  "type": "doc",
  "content": [
    {"type":"heading","attrs":{"level":1},"content":[{"type":"text","text":"Welcome to the demo course"}]},
    {"type":"paragraph","content":[
      {"type":"text","text":"This page was created "},
      {"type":"text","text":"entirely via the API","marks":[{"type":"bold"}]},
      {"type":"text","text":". It uses TipTap blocks: paragraphs, headings, lists, code, and an image block."}
    ]},
    {"type":"heading","attrs":{"level":2},"content":[{"type":"text","text":"A figure"}]},
    {"type":"blockImage","attrs":{"blockObject": block, "size":{"width":500},"alignment":"center"}},
    {"type":"heading","attrs":{"level":2},"content":[{"type":"text","text":"What you will learn"}]},
    {"type":"bulletList","content":[
      {"type":"listItem","content":[{"type":"paragraph","content":[{"type":"text","text":"Programmatic course migration"}]}]},
      {"type":"listItem","content":[{"type":"paragraph","content":[{"type":"text","text":"Every activity type"}]}]},
      {"type":"listItem","content":[{"type":"paragraph","content":[{"type":"text","text":"TipTap content blocks"}]}]}
    ]},
    {"type":"heading","attrs":{"level":2},"content":[{"type":"text","text":"A code block"}]},
    {"type":"codeBlock","attrs":{"language":"python"},
     "content":[{"type":"text","text":"def hello():\n    print(\"Hello, world!\")\n\nhello()"}]}
  ]
}
print(json.dumps({"content": doc, "published": True}))
PY
)
put_json "$API/activities/$PAGE_UUID" "$TIPTAP" > /dev/null

# ── 3b. Dynamic Markdown (renders a remote .md URL) ─────────────────────────
post_json "$API/activities/" \
  "{\"name\":\"Markdown remote page\",\"chapter_id\":$CH1_ID,\"activity_type\":\"TYPE_DYNAMIC\",\"activity_sub_type\":\"SUBTYPE_DYNAMIC_MARKDOWN\",\"content\":{\"markdown_url\":\"https://raw.githubusercontent.com/anthropics/anthropic-cookbook/main/README.md\"},\"published\":true}" > /dev/null

# ── 3c. Dynamic Embed (iframe) ──────────────────────────────────────────────
post_json "$API/activities/" \
  "{\"name\":\"Embed example\",\"chapter_id\":$CH1_ID,\"activity_type\":\"TYPE_DYNAMIC\",\"activity_sub_type\":\"SUBTYPE_DYNAMIC_EMBED\",\"content\":{\"embed_url\":\"https://en.wikipedia.org/wiki/Special:Random\"},\"published\":true}" > /dev/null

# ── 4a. Hosted MP4 (multipart, then PUT to publish) ─────────────────────────
# /activities/video forces published=false on create; we flip it after.
VID=$(curl -fsS -X POST "$API/activities/video" \
  -H "Authorization: Bearer $TOKEN" \
  -F 'name=Hosted MP4 sample' \
  -F "chapter_id=$CH2_ID" \
  -F "video_file=@$ASSETS/clip.mp4;type=video/mp4" \
  -F 'details={"startTime":0,"endTime":null,"autoplay":false,"muted":false}')
put_json "$API/activities/$(echo "$VID" | jq -r .activity_uuid)" '{"published":true}' > /dev/null

# ── 4b. YouTube external video (JSON, then PUT to publish) ──────────────────
YT=$(post_json "$API/activities/external_video" \
  "{\"name\":\"YouTube embed\",\"uri\":\"https://www.youtube.com/watch?v=jNQXAC9IVRw\",\"type\":\"youtube\",\"chapter_id\":\"$CH2_ID\",\"details\":\"{\\\"startTime\\\":0,\\\"endTime\\\":null,\\\"autoplay\\\":false,\\\"muted\\\":false}\"}")
put_json "$API/activities/$(echo "$YT" | jq -r .activity_uuid)" '{"published":true}' > /dev/null

# ── 4c. PDF document (multipart, then PUT to publish) ───────────────────────
PDF=$(curl -fsS -X POST "$API/activities/documentpdf" \
  -H "Authorization: Bearer $TOKEN" \
  -F 'name=Sample PDF document' \
  -F "chapter_id=$CH2_ID" \
  -F "pdf_file=@$ASSETS/doc.pdf;type=application/pdf")
put_json "$API/activities/$(echo "$PDF" | jq -r .activity_uuid)" '{"published":true}' > /dev/null

# ── 5. Assignment (THREE-step: shell + record + at least one task) ──────────
ASSIGN_ACT=$(post_json "$API/activities/" \
  "{\"name\":\"Final assignment\",\"chapter_id\":$CH3_ID,\"activity_type\":\"TYPE_ASSIGNMENT\",\"activity_sub_type\":\"SUBTYPE_ASSIGNMENT_ANY\",\"content\":{},\"published\":true}")
ASSIGN_ACT_ID=$(echo "$ASSIGN_ACT" | jq -r .id)

ASSIGN=$(post_json "$API/assignments/" \
  "{\"title\":\"Final assignment\",\"description\":\"Submit your final project.\",\"due_date\":\"2026-12-31\",\"grading_type\":\"PERCENTAGE\",\"published\":true,\"org_id\":$ORG_ID,\"course_id\":$CID,\"chapter_id\":$CH3_ID,\"activity_id\":$ASSIGN_ACT_ID}")
ASSIGN_UUID=$(echo "$ASSIGN" | jq -r .assignment_uuid)

post_json "$API/assignments/$ASSIGN_UUID/tasks" \
  '{"title":"Submit your project file","description":"Upload a PDF of your final project.","hint":"Use a clear filename.","assignment_type":"FILE_SUBMISSION","contents":{},"max_grade_value":100}' > /dev/null

# ── 6. Publish the course ───────────────────────────────────────────────────
put_json "$API/courses/$CUUID" '{"published":true,"public":true}' > /dev/null

# ── 7. Verify ───────────────────────────────────────────────────────────────
echo ""
echo "Tree:"
curl -fsS "$API/courses/$CUUID/meta?with_unpublished_activities=true&slim=true" \
  -H "Authorization: Bearer $TOKEN" | jq -r '
    "course: \(.name) (public=\(.public), published=\(.published))",
    (.chapters[] | "  \(.name)",
      (.activities[] | "    - \(.name) [\(.activity_type)/\(.activity_sub_type)]"))'
echo ""
echo "View it at: http://localhost:3000/course/$(echo $CUUID | sed s/course_//)"
```

What you should see in the browser at the printed URL:

- **Course landing page** with the JPEG thumbnail, three chapters, "8 exciting activities" badge, and a "Start Course" button.
- **Welcome page** with the heading, bold paragraph, embedded image, bullet list, and Python-highlighted code block, plus a TOC sidebar generated from the headings.
- **Markdown remote page** rendering the GitHub README with full formatting.
- **Embed example** showing a Wikipedia article inside an iframe.
- **Hosted MP4 sample** in the LearnHouse video player.
- **YouTube embed** with the YouTube iframe player.
- **Sample PDF document** in the embedded PDF.js viewer with toolbar.
- **Final assignment** showing the description, due date, and File Submission widget. (Anonymous viewers see the structure but get a "Please sign in to upload files" prompt.)

## Verifying the result

After migration, fetch the full course tree and inspect it before announcing the course to learners:

```bash
curl "http://localhost:1338/api/v1/courses/$CUUID/meta?with_unpublished_activities=true&slim=true" \
  -H "Authorization: Bearer $TOKEN" | jq '
    {chapters: (.chapters | length),
     activities: (.chapters | map(.activities | length) | add)}'
```

`slim=true` omits the heavy `content` field from each activity, which is much faster when you only want to verify the structure.

If anything is wrong, every resource has a `DELETE` endpoint -- safest is to delete the course (`DELETE /api/v1/courses/{course_uuid}`), which cascades to its chapters, activities, and blocks, and then re-run the script.

```bash
curl -X DELETE "$API/courses/$CUUID" -H "Authorization: Bearer $TOKEN"
```

---

# 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 WorkOS (which brokers SAML, Okta, Azure AD, and more) or any OIDC-compatible provider via the Custom OIDC integration.
- **[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

| Provider | Status | Description |
|---|---|---|
| [WorkOS](/enterprise/sso/workos) | Available | Enterprise SSO with SAML and OIDC support, includes admin portal |
| [Custom OIDC](/enterprise/sso/custom-oidc) | Available | Connect any OpenID Connect provider (Azure AD, Okta, Google Workspace, Keycloak, etc.) |

The Custom OIDC provider lets you connect to virtually any modern identity provider that supports OpenID Connect, including Okta, Azure AD / Microsoft Entra ID, Google Workspace, and Keycloak.

## 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 automatically creates 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 `User` role).

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

## Configuration Options

| Option | Description |
|---|---|
| Provider | Which identity provider to use (WorkOS or Custom OIDC). |
| 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 | WorkOS offers an admin portal for managing the IdP connection directly. |

---

# Custom OIDC
URL: https://docs.learnhouse.app/enterprise/sso/custom-oidc

The Custom OIDC provider lets you connect LearnHouse directly to any OpenID Connect 1.0 compatible identity provider. This is ideal for organizations that want to use their existing IdP without going through a third-party broker.

## Compatible Providers

Any OIDC-compliant provider works, including:

- **Azure AD / Microsoft Entra ID**
- **Okta**
- **Google Workspace**
- **Keycloak**
- **Auth0**
- **OneLogin**
- **Ping Identity**

## Configuration

| Field | Required | Description |
|---|---|---|
| `issuer_url` | Yes | The OIDC Issuer URL. LearnHouse uses this to auto-discover endpoints via `/.well-known/openid-configuration`. |
| `client_id` | Yes | OAuth 2.0 Client ID from your identity provider. |
| `client_secret` | Yes | OAuth 2.0 Client Secret from your identity provider. |
| `scopes` | No | Space-separated OAuth scopes. Defaults to `openid email profile`. |

## Issuer URL Examples

| Provider | Issuer URL Format |
|---|---|
| Azure AD | `https://login.microsoftonline.com/{tenant-id}/v2.0` |
| Okta | `https://{your-domain}.okta.com` |
| Google Workspace | `https://accounts.google.com` |
| Keycloak | `https://{host}/realms/{realm}` |
| Auth0 | `https://{your-domain}.auth0.com` |

## Setup Steps

1. Register LearnHouse as an application in your identity provider and obtain a Client ID and Client Secret.
2. Set the callback/redirect URI in your IdP to your LearnHouse SSO callback URL.
3. In the organization settings, select **Custom OIDC** as the SSO provider.
4. Enter the Issuer URL, Client ID, and Client Secret.
5. Users with matching email domains can now log in via SSO.

LearnHouse uses OIDC Discovery to automatically find the authorization, token, and userinfo endpoints from the issuer URL. Make sure your IdP exposes a `/.well-known/openid-configuration` document.

---

# WorkOS
URL: https://docs.learnhouse.app/enterprise/sso/workos

WorkOS provides enterprise SSO through a unified API that supports both SAML and OIDC identity providers. It includes an admin portal that lets organization admins configure their identity provider without developer involvement.

Requires `WORKOS_API_KEY` and `WORKOS_CLIENT_ID` environment variables to be set.

## Features

- **Admin Portal** — WorkOS provides a hosted portal where organization admins can set up and manage their IdP connection directly.
- **SAML & OIDC** — Supports both protocols through a single integration.
- **Auto User Provisioning** — Automatically creates LearnHouse accounts from IdP profiles.
- **Domain Restrictions** — Restrict access to specific email domains.
- **Default Role Assignment** — Assign a default role to newly provisioned users.

## Configuration

| Field | Required | Description |
|---|---|---|
| `organization_id` | Yes (or `connection_id`) | WorkOS Organization ID, created automatically or via the Admin Portal. |
| `connection_id` | Yes (or `organization_id`) | WorkOS Connection ID, typically managed via the Admin Portal. |

You need either an `organization_id` (for organization-level SSO) or a `connection_id` (for a specific connection). In most cases, you'll use the `organization_id` and let admins configure the connection through the Admin Portal.

## Environment Variables

| Variable | Description |
|---|---|
| `WORKOS_API_KEY` | Your WorkOS API key. |
| `WORKOS_CLIENT_ID` | Your WorkOS Client ID. |

## Setup Steps

1. Create a [WorkOS account](https://workos.com) and obtain your API key and Client ID.
2. Set the `WORKOS_API_KEY` and `WORKOS_CLIENT_ID` environment variables in your LearnHouse deployment.
3. In the organization settings, select **WorkOS** as the SSO provider.
4. Use the Admin Portal link to configure the identity provider connection (SAML or OIDC).
5. Users with matching email domains can now log in via SSO.

---

# 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 self-host the core platform on your own infrastructure using the **LearnHouse CLI**. 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 with `learnhouse update`, which pulls the latest release from the [LearnHouse GitHub repository](https://github.com/learnhouse/learnhouse).

## 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)** — File-upload and quiz tasks with rubric-based grading and submissions.
- **[Code Execution](/platform/code-execution)** — Judge0-powered Code Playground blocks that run student code in 30 languages, with auto-graded test cases.
- **[Playgrounds](/platform/playgrounds)** — AI-generated interactive HTML experiences (distinct from Code Playground blocks).
- **[Discussions](/platform/discussions)** — Community discussion threads with comments, voting, and reactions.
- **[Boards](/platform/boards)** — Real-time collaborative canvases with sticky notes, drawings, frames, and embedded content.
- **[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.
- **[Automations](/platform/automations)** — Webhooks and the official Zapier app for connecting LearnHouse events to your own systems or 6,000+ no-code tools.

---

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

LearnHouse includes a context-aware AI assistant powered by **Google Gemini**. 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 a Google Gemini API key to be configured at the instance level via `LEARNHOUSE_GEMINI_API_KEY`. See [AI Setup](/self-hosting/configuration/ai-setup) 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 instance has a Google Gemini API key configured via `LEARNHOUSE_GEMINI_API_KEY` (see [AI Setup](/self-hosting/configuration/ai-setup)) and that AI is enabled for your organization.

---

# 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. Supported task types are **file uploads** and **quizzes**, with a generic `OTHER` fallback for custom submissions.

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 code exercises are built into course content via the **Code Playground** editor block, not assignment tasks.

---

# 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 (file upload or quiz).
2. Students complete each task and submit their work.
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.

## Grade Types

Each assignment can be graded using one of three scales:

- **Numeric** — raw number score (for example, 87 / 100).
- **Percentage** — score expressed as a percentage.
- **Alphabet** — letter grades (A, B, C, …).

## 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 moves through a clear set of states so teachers can see at a glance where every learner stands:

- **Not Submitted** — the student has not yet turned the task in.
- **Pending** — the student has saved work in progress.
- **Submitted** — the student has submitted and is awaiting a grade.
- **Late** — submitted after the deadline.
- **Graded** — the teacher has reviewed the submission and recorded a grade.

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

---

# Automations
URL: https://docs.learnhouse.app/platform/automations

LearnHouse pushes real-time events to your own systems and to no-code automation tools. Use these to sync learners into your CRM, notify a Slack channel on course completion, trigger certificate printing, or feed any downstream workflow.

Automations are available on the **Pro plan** or higher. Both webhooks and Zapier rely on API tokens scoped to a single organization.

## What's available

- **[Webhooks](/platform/automations/webhooks)** — Direct, signed HTTP `POST` deliveries to any URL you control. Best for custom backends and self-hosted services.
- **[Zapier](/platform/automations/zapier)** — Official Zapier app with triggers for every LearnHouse event and actions for enrolling users, completing activities, and looking up learners. Best for no-code workflows into Slack, Google Sheets, HubSpot, and 6,000+ other Zapier apps.
- **[Event Catalogue](/platform/automations/events)** — The canonical list of every event that can fire, with payload schemas.

## How it works

Every automation is powered by the same internal event bus:

1. Something happens inside LearnHouse (a learner completes a course, a user is invited, an assignment is graded, …).
2. The event is dispatched to every active subscriber for that organization — webhook endpoints you configured manually, and any Zapier REST Hook subscriptions created by your active Zaps.
3. Each endpoint receives the same JSON envelope with an event name, a delivery ID, an organization ID, and an event-specific `data` payload.

Signing, retries, delivery logs, and SSRF protection all work identically across both paths. Choosing between webhooks and Zapier is a question of where you want to handle the event, not whether you'll get a different payload.

## Choosing between webhooks and Zapier

| You want to… | Use |
| --- | --- |
| Call a custom backend you control | **Webhooks** |
| Route events into Slack, Google Sheets, HubSpot, Airtable, Notion, etc. | **Zapier** |
| Verify cryptographic signatures on payloads | **Webhooks** (Zapier handles its own auth internally) |
| Run a **LearnHouse action** from another app (e.g., enroll a user when a HubSpot form is submitted) | **Zapier** |
| Keep infrastructure dependencies to a minimum | **Webhooks** |

You can use both at the same time for the same events.

---

# Event Catalogue
URL: https://docs.learnhouse.app/platform/automations/events

Every event that can fire from LearnHouse, grouped by category. Each event delivers the same envelope (`event`, `delivery_id`, `timestamp`, `org_id`, `data`) — only the shape of `data` varies.

The event registry is the single source of truth. At runtime, dispatched payloads are validated against these schemas and any drift is logged as a warning. You can also fetch the live registry from your LearnHouse instance:
```http
GET /api/v1/{org_id}/webhooks/events
```

## System

### `ping`

Test event sent to verify endpoint connectivity. Fired by the **Send test event** button and the `POST /webhooks/{uuid}/test` endpoint.

```json
{ "message": "string" }
```

## Learning progress

### `course_completed`

Triggered when a user completes every activity in a course.

```json
{
  "user":   { "user_uuid": "string", "email": "string", "username": "string" },
  "course": { "course_uuid": "string", "name": "string" }
}
```

### `course_enrolled`

Triggered when a user enrols in a course.

```json
{
  "user":   { "user_uuid": "string", "email": "string", "username": "string" },
  "course": { "course_uuid": "string", "name": "string" }
}
```

### `activity_completed`

Triggered when a user completes an activity.

```json
{
  "user":     { "user_uuid": "string", "email": "string", "username": "string" },
  "activity": { "activity_uuid": "string", "activity_type": "string" },
  "course":   { "course_uuid": "string", "name": "string" }
}
```

### `assignment_submitted`

Triggered when a user submits an assignment.

```json
{
  "user":       { "user_uuid": "string", "email": "string", "username": "string" },
  "assignment": { "assignment_uuid": "string" },
  "course":     { "course_uuid": "string", "name": "string" }
}
```

### `assignment_graded`

Triggered when an instructor grades an assignment submission.

```json
{
  "user_id": "integer",
  "assignment_uuid": "string",
  "course_uuid": "string",
  "grade": "integer"
}
```

### `certificate_claimed`

Triggered when a user receives a certificate.

```json
{
  "user":        { "user_uuid": "string", "email": "string", "username": "string" },
  "course":      { "course_uuid": "string", "name": "string" },
  "certificate": { "user_certification_uuid": "string" }
}
```

## User & access

### `user_signed_up`

Triggered when a new user signs up for the organization.

```json
{
  "user": {
    "user_uuid": "string",
    "email": "string",
    "username": "string",
    "first_name": "string",
    "last_name": "string"
  },
  "signup_method": "string"
}
```

### `user_email_verified`

Triggered when a user verifies their email address.

```json
{ "user_uuid": "string", "email": "string" }
```

### `user_role_changed`

Triggered when a user's role is changed in the organization.

```json
{ "user_id": "integer", "org_id": "integer", "new_role_uuid": "string" }
```

### `user_invited_to_org`

Triggered when users are invited to the organization. A single event is fired per invite batch.

```json
{
  "org_id": "integer",
  "emails": "list[string]",
  "invite_code_uuid": "string",
  "invited_by": "string"
}
```

### `user_removed_from_org`

Triggered when a user is removed from the organization.

```json
{ "user_id": "integer", "org_id": "integer" }
```

## Course lifecycle

### `course_created`

Triggered when a new course is created.

```json
{ "course_uuid": "string", "name": "string", "org_id": "integer" }
```

### `course_published`

Triggered when a course is published or unpublished.

```json
{ "course_uuid": "string", "name": "string", "published": "boolean" }
```

### `course_deleted`

Triggered when a course is deleted.

```json
{ "course_uuid": "string", "name": "string" }
```

### `course_update_published`

Triggered when an announcement is posted to a course.

```json
{ "courseupdate_uuid": "string", "course_uuid": "string" }
```

## Content management

### `activity_version_created`

Triggered when an activity version snapshot is created.

```json
{ "activity_id": "integer", "version_number": "integer", "created_by_id": "integer" }
```

### `activity_version_restored`

Triggered when an activity is restored to a previous version.

```json
{
  "activity_uuid": "string",
  "restored_version_number": "integer",
  "new_version_number": "integer"
}
```

### `course_contributor_added`

Triggered when contributors are added to a course.

```json
{ "course_uuid": "string", "contributors": "list[object]" }
```

### `course_contributor_removed`

Triggered when contributors are removed from a course.

```json
{ "course_uuid": "string", "contributors": "list[object]" }
```

### `collection_created`

Triggered when a new course collection is created.

```json
{ "collection_uuid": "string", "name": "string" }
```

### `podcast_episode_created`

Triggered when a new podcast episode is added.

```json
{
  "episode_uuid": "string",
  "podcast_uuid": "string",
  "title": "string",
  "episode_number": "integer"
}
```

## Collaboration

### `board_created`

Triggered when a new whiteboard is created.

```json
{ "board_uuid": "string", "name": "string", "created_by": "integer" }
```

### `board_member_added`

Triggered when a member is added to a whiteboard.

```json
{ "board_uuid": "string", "user_id": "integer", "role": "string" }
```

### `playground_created`

Triggered when a new playground is created.

```json
{ "playground_uuid": "string", "name": "string", "created_by": "integer" }
```

## Community

### `discussion_posted`

Triggered when a user creates a discussion.

```json
{
  "user":       { "user_uuid": "string", "email": "string", "username": "string" },
  "discussion": { "discussion_uuid": "string", "title": "string" },
  "community":  { "community_uuid": "string" }
}
```

### `comment_created`

Triggered when a user posts a comment on a discussion.

```json
{
  "user":       { "user_uuid": "string", "email": "string", "username": "string" },
  "comment":    { "comment_uuid": "string" },
  "discussion": { "discussion_uuid": "string", "title": "string" },
  "community":  { "community_uuid": "string" }
}
```

### `discussion_pinned`

Triggered when a discussion is pinned or unpinned.

```json
{
  "discussion_uuid": "string",
  "title": "string",
  "is_pinned": "boolean",
  "community_uuid": "string"
}
```

### `discussion_locked`

Triggered when a discussion is locked or unlocked.

```json
{
  "discussion_uuid": "string",
  "title": "string",
  "is_locked": "boolean",
  "community_uuid": "string"
}
```

### `discussion_vote_cast`

Triggered when a user upvotes a discussion.

```json
{ "discussion_uuid": "string", "user_id": "integer", "upvote_count": "integer" }
```

## Groups

### `usergroup_created`

Triggered when a new user group is created.

```json
{ "usergroup_uuid": "string", "name": "string" }
```

### `usergroup_deleted`

Triggered when a user group is deleted.

```json
{ "usergroup_uuid": "string", "name": "string" }
```

### `usergroup_users_added`

Triggered when users are added to a user group.

```json
{
  "usergroup_id": "integer",
  "usergroup_uuid": "string",
  "user_ids": "list[integer]"
}
```

### `usergroup_resources_added`

Triggered when resources are assigned to a user group.

```json
{
  "usergroup_id": "integer",
  "usergroup_uuid": "string",
  "resource_uuids": "list[string]"
}
```

## Subscriptions

### `pack_activated`

Triggered when a subscription pack is activated.

```json
{
  "pack_id": "string",
  "pack_type": "string",
  "quantity": "integer",
  "platform_subscription_id": "string"
}
```

### `pack_deactivated`

Triggered when a subscription pack is cancelled.

```json
{
  "pack_id": "string",
  "pack_type": "string",
  "platform_subscription_id": "string"
}
```

## Organization

### `org_signup_method_changed`

Triggered when the organization signup method is changed.

```json
{ "signup_mechanism": "string" }
```

### `org_ai_config_changed`

Triggered when the organization AI configuration is updated.

```json
{ "ai_enabled": "boolean", "copilot_enabled": "boolean" }
```

### `org_payments_config_changed`

Triggered when the organization payments configuration is updated.

```json
{ "payments_enabled": "boolean" }
```

---

# Webhooks
URL: https://docs.learnhouse.app/platform/automations/webhooks

Webhooks deliver real-time event notifications to any HTTPS endpoint you control. When something happens in LearnHouse — a learner completes a course, a user signs up, an assignment is graded — LearnHouse sends a signed `POST` request with a JSON payload to every matching endpoint.

Webhooks are available on the **Pro plan** or higher. Manage endpoints under **Settings → Automations** in the organization dashboard, or via the [REST API](#api-reference) with an API token.

## Quick start

1. In the dashboard go to **Settings → Automations → Webhooks → New endpoint**.
2. Enter the target URL (must be HTTPS and publicly reachable).
3. Select the events you want to subscribe to — see the [Event Catalogue](/platform/automations/events) for the full list.
4. Click **Create**. The signing secret is shown **once** on this screen — copy it into your server's secret store immediately.
5. From the endpoint detail page, click **Send test event** to deliver a `ping` payload and confirm your server is reachable.

## Payload format

Every delivery has the same outer envelope:

```json
{
  "event": "course_completed",
  "delivery_id": "dlv_9f1e3c7b22a44f0d",
  "timestamp": "2026-04-19T14:31:02Z",
  "org_id": 1,
  "data": {
    "user": {
      "user_uuid": "user_abc",
      "email": "alice@example.com",
      "username": "alice"
    },
    "course": {
      "course_uuid": "course_xyz",
      "name": "Intro to Python"
    }
  }
}
```

The shape of `data` varies per event. See the [Event Catalogue](/platform/automations/events) for the canonical schema of every event.

### Headers

| Header | Value |
| --- | --- |
| `Content-Type` | `application/json` |
| `User-Agent` | `LearnHouse-Webhooks/1.0` |
| `X-Webhook-Event` | Event name (e.g. `course_completed`) |
| `X-Webhook-Delivery` | Unique delivery ID (matches `delivery_id` in the body) |
| `X-Webhook-Signature` | `sha256=<hex_digest>` — HMAC-SHA256 of the raw body |

## Verifying the signature

LearnHouse signs every payload with HMAC-SHA256, using the endpoint's signing secret. The signature covers the **raw request body** (exactly the bytes sent over the wire, before any JSON parsing) and is delivered in the `X-Webhook-Signature` header as `sha256=<hex_digest>` — the same convention used by GitHub and Stripe.

Always verify the signature before trusting a payload. Anyone who discovers your endpoint URL can send unsigned requests; the signature is the only thing that proves the request came from LearnHouse.

### Node.js

```js

function verifyWebhook(rawBody, signatureHeader, secret) {
  const expected = 'sha256=' + crypto
    .createHmac('sha256', secret)
    .update(rawBody)
    .digest('hex')

  // Constant-time compare to resist timing attacks
  const a = Buffer.from(signatureHeader)
  const b = Buffer.from(expected)
  return a.length === b.length && crypto.timingSafeEqual(a, b)
}
```

### Python

```python

def verify_webhook(raw_body: bytes, signature_header: str, secret: str) -> bool:
    expected = "sha256=" + hmac.new(
        secret.encode(), raw_body, hashlib.sha256
    ).hexdigest()
    return hmac.compare_digest(expected, signature_header)
```

If your framework parses the body into a dict before you see it (Express without `express.raw`, FastAPI without the raw bytes, etc.), you must re-read the raw body. Re-serialising the parsed JSON produces a different byte sequence and the signature will not match.

## Delivery and retries

- **Transport**: HTTPS `POST` with a 10-second timeout. Redirects are not followed.
- **Retries**: Up to **3 attempts** per event, with exponential backoff of **1 s, 4 s, 16 s**. Any non-2xx response, timeout, or network error triggers a retry.
- **Success**: A response with an HTTP status in `2xx` marks the delivery as successful and stops further retries.
- **Ordering**: Deliveries are fire-and-forget and may arrive slightly out of order under load. Use the `timestamp` field if you need strict ordering.
- **Delivery logs**: The most recent **200 attempts per endpoint** are retained. Each log entry records the HTTP status, a truncated response body (first 500 bytes), the attempt number, and any transport-level error.

Logs are visible from the endpoint detail page in the dashboard and via `GET /{org_id}/webhooks/{webhook_uuid}/deliveries`.

## Your endpoint: what to return

- **Respond quickly.** LearnHouse uses a 10 s per-attempt timeout; if your handler does heavy work, enqueue a job and return `200` immediately.
- **Respond with any 2xx status.** Body content is ignored (but captured in the delivery log for debugging).
- **Be idempotent.** Because of retries and rare duplicate deliveries, handle the same `delivery_id` arriving twice as a no-op.
- **Verify the signature.** Do this before any database write.

## Security

- **HTTPS only.** `http://` URLs are rejected at create time.
- **Private address protection (SSRF guard).** LearnHouse resolves every webhook URL to an IP before calling it and refuses to deliver to private ranges (`10.0.0.0/8`, `127.0.0.0/8`, `169.254.0.0/16`, `172.16.0.0/12`, `192.168.0.0/16`, `::1`, link-local, etc.). The same check is repeated **after** the connection is established to defeat DNS rebinding.
- **Signing secret at rest.** Secrets are stored encrypted (Fernet, key derived from the application's JWT secret) and are returned in plaintext **only** at creation and when you click **Regenerate**. LearnHouse cannot recover a lost secret — you can only rotate it.
- **Scope.** A webhook endpoint is scoped to a single organization. It can only subscribe to events fired for that org.

## Regenerating a secret

If a secret leaks, go to **Settings → Automations → Webhooks → *endpoint* → Regenerate secret**. The new secret is returned once and replaces the old one immediately. Every subsequent delivery will be signed with the new secret, so update your consumer before regenerating (or accept a brief window of rejected signatures while you roll out the change).

## API reference

All endpoints require authentication (session cookie or API token) and are scoped to `org_id`.

### List available events

```http
GET /api/v1/{org_id}/webhooks/events
```

Returns the full catalogue of event names, categories, descriptions, and data schemas. This is the same data shown in the Event Catalogue.

### Create an endpoint

```http
POST /api/v1/{org_id}/webhooks
Content-Type: application/json

{
  "url": "https://example.com/hooks/learnhouse",
  "description": "Main backend",
  "events": ["course_completed", "user_signed_up"]
}
```

Response (200):

```json
{
  "webhook_uuid": "webhook_b5f2…",
  "url": "https://example.com/hooks/learnhouse",
  "description": "Main backend",
  "events": ["course_completed", "user_signed_up"],
  "is_active": true,
  "secret": "whsec_…",
  "created_by_user_id": 1,
  "creation_date": "2026-04-19 14:31:02"
}
```

The `secret` is returned **only on this response**. Store it immediately — it cannot be retrieved again.

### List endpoints

```http
GET /api/v1/{org_id}/webhooks
```

### Get an endpoint

```http
GET /api/v1/{org_id}/webhooks/{webhook_uuid}
```

### Update an endpoint

```http
PUT /api/v1/{org_id}/webhooks/{webhook_uuid}
Content-Type: application/json

{
  "url": "https://example.com/hooks/v2",
  "events": ["course_completed"],
  "is_active": true
}
```

All fields are optional; omit to leave unchanged.

### Delete an endpoint

```http
DELETE /api/v1/{org_id}/webhooks/{webhook_uuid}
```

Deletes the endpoint **and** all of its delivery logs.

### Regenerate the signing secret

```http
POST /api/v1/{org_id}/webhooks/{webhook_uuid}/regenerate-secret
```

Returns a `WebhookEndpointCreatedResponse` with the fresh `secret`. Subsequent deliveries use the new secret immediately.

### Send a test event

```http
POST /api/v1/{org_id}/webhooks/{webhook_uuid}/test
```

Delivers a synthetic `ping` event:

```json
{
  "event": "ping",
  "delivery_id": "dlv_…",
  "timestamp": "2026-04-19T14:31:02Z",
  "org_id": 1,
  "data": { "message": "This is a test webhook event from LearnHouse." }
}
```

### List delivery logs

```http
GET /api/v1/{org_id}/webhooks/{webhook_uuid}/deliveries?limit=50
```

Returns up to `limit` of the most recent delivery attempts (capped at 200 retained per endpoint), each including HTTP status, truncated response body, attempt number, and error message when applicable.

---

# Zapier
URL: https://docs.learnhouse.app/platform/automations/zapier

The official LearnHouse Zapier app lets you build no-code workflows across Slack, Google Sheets, HubSpot, Notion, Airtable, Mailchimp, and every other Zapier app — without writing a webhook consumer yourself.

The Zapier integration is available on the **Pro plan** or higher. It is implemented on top of the same event system as [Webhooks](/platform/automations/webhooks), so the two can be used together.

## What you can do

### Triggers (LearnHouse → other apps)

Every event in the [Event Catalogue](/platform/automations/events) is available as a Zapier trigger. When that event fires in LearnHouse, the Zap runs and can push data into any of Zapier's supported apps.

Common patterns:

- **Course Completed → Slack**: post a celebration message to a channel when a learner finishes a course.
- **User Signed Up → HubSpot**: create or update a contact when someone signs up for your org.
- **Assignment Submitted → Google Sheets**: append a row for every submission.
- **Certificate Claimed → Mailchimp**: tag the contact in your newsletter audience.

### Actions (other apps → LearnHouse)

Actions run a LearnHouse operation from any step of a Zap. They call existing admin endpoints under `/api/v1/admin/{org_slug}/*` using the API token you connected.

| Action | What it does |
| --- | --- |
| **Enroll User** | Enrols an existing user in a course. |
| **Unenroll User** | Removes a user's enrolment from a course. |
| **Complete Activity** | Marks a specific activity complete for a user. |
| **Complete Course** | Marks an entire course complete for a user. |

### Searches

| Search | What it does |
| --- | --- |
| **Find User by Email** | Looks up a LearnHouse user by email — use the result to feed a user ID into a follow-up action. |

## Setup

### 1. Get a LearnHouse API token

1. In the LearnHouse dashboard open **Settings → API Access**.
2. Click **Create token** and give it a descriptive name (e.g., "Zapier").
3. Copy the `lh_…` token immediately. The token is scoped to your current organization.

API tokens are shown only once at creation. Store the value somewhere you can retrieve later; if you lose it, revoke the token and create a new one.

### 2. Connect the Zapier app

1. In Zapier, click **Create Zap** and search for **LearnHouse** as the trigger app.
2. Pick an event (e.g., **Course Completed**) and click **Continue**.
3. When prompted to sign in, paste your `lh_…` API token.
4. Zapier calls LearnHouse's `/integrations/zapier/me` endpoint to verify the token and then displays your organization name.

### 3. Configure the trigger

Pick the event, optionally filter by course or user group using the dynamic dropdowns Zapier populates from your org, and click **Test trigger**. Zapier pulls a recent sample payload so you can map fields into the action step.

### 4. Turn on the Zap

When you toggle the Zap on, Zapier calls `POST /integrations/zapier/subscriptions` on LearnHouse with its own callback URL. LearnHouse records the subscription (as a webhook endpoint tagged `source="zapier"`) and starts delivering the event to Zapier. Toggling the Zap off removes the subscription automatically.

## How it works under the hood

The Zapier integration is implemented on top of LearnHouse's webhook pipeline using the Zapier **REST Hooks** pattern:

1. Zapier calls LearnHouse endpoints under `/api/v1/integrations/zapier/*` — `/me` for auth verification, `/events` for the trigger catalogue, `/courses` / `/users` / `/usergroups` for dropdown sources, and `/subscriptions` for registering callbacks.
2. Each enabled Zap registers one subscription, which is stored as a webhook endpoint with `source = "zapier"`, a single event, and Zapier's callback URL.
3. When the event fires, the existing webhook dispatcher delivers the payload to Zapier using the same retries, SSRF guard, and delivery logging described in [Webhooks](/platform/automations/webhooks).

Subscriptions show up in the same **Settings → Automations** dashboard as manual webhooks, labelled with the Zap name Zapier provided at subscribe time. You can view delivery logs for a Zapier subscription the same way you do for a manual webhook.

Signatures are still computed and sent, but Zapier does not verify them — its REST Hook URL is protected by its own secret path. You don't need to do anything with the signature as an end user.

## Managing Zapier subscriptions

- The canonical place to enable / disable a Zap is the **Zapier UI**. Toggling a Zap on or off there adds or removes the corresponding LearnHouse subscription.
- Deleting a subscription from the LearnHouse dashboard will stop deliveries, but Zapier will not know the subscription is gone — the Zap will silently receive nothing. Prefer turning the Zap off from Zapier.
- If you revoke the underlying API token, every Zap that was connected with that token will fail to re-subscribe when Zapier next syncs. Create a new token and reconnect the account in Zapier.

## Zapier integration endpoints

These endpoints are called by the Zapier Platform on your organization's behalf — you typically won't call them directly, but they are documented here for completeness.

| Method | Endpoint | Purpose |
| --- | --- | --- |
| `GET` | `/api/v1/integrations/zapier/me` | Auth test; returns org and token identity |
| `GET` | `/api/v1/integrations/zapier/events` | Full event registry with schemas |
| `GET` | `/api/v1/integrations/zapier/courses` | Course list for dynamic dropdowns (max 500) |
| `GET` | `/api/v1/integrations/zapier/users` | User list for dynamic dropdowns (max 500) |
| `GET` | `/api/v1/integrations/zapier/usergroups` | User-group list for dynamic dropdowns (max 500) |
| `POST` | `/api/v1/integrations/zapier/subscriptions` | Called when a Zap is turned on |
| `GET` | `/api/v1/integrations/zapier/subscriptions` | Lists your org's Zap subscriptions |
| `DELETE` | `/api/v1/integrations/zapier/subscriptions/{id}` | Called when a Zap is turned off or deleted |

All Zapier endpoints require `Authorization: Bearer lh_…` — the org scope is carried by the token, so no `org_id` appears in the URL.

## Troubleshooting

- **"This endpoint requires an API token"** — You tried to connect with session-cookie auth instead of an `lh_…` token. Generate one in **Settings → API Access**.
- **"Zapier integration requires a Pro plan or higher"** — Upgrade the organization's plan; the Zapier endpoints are gated at Pro.
- **"Unknown event"** — The Zapier app was pushed with an event name that no longer exists in LearnHouse (or vice versa). Make sure the Zapier app and the LearnHouse instance are on compatible versions.
- **Zap runs but no data comes through** — Check **Settings → Automations** in LearnHouse; the subscription row shows recent delivery attempts, their status, and the response body Zapier returned.
- **SSRF block** — Zapier's callback URL is public, so this should not happen in production. If it does, check the delivery log's `error_message` — it'll explain which IP was blocked.

---

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

Boards are real-time collaborative **canvases** — a Miro / FigJam-style freeform workspace that multiple users can pan, zoom, and edit together. They are not document editors and do not reuse the course-activity block editor.

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

## How Boards Work

Each board is an infinite canvas backed by Yjs CRDTs, so concurrent edits merge without conflicts. The collaboration server (Hocuspocus) syncs changes in real time over WebSockets and persists document state to Redis and PostgreSQL.

## Key Features

- **Real-time collaboration** — Multiple users can edit a board at the same time with live presence and cursor tracking.
- **Role-based access** — Board members are assigned one of three roles: **Owner**, **Editor**, or **Viewer**.
- **Canvas tools** — Drawing strokes, sticky notes, to-do cards, frames, and freeform pan/zoom navigation.
- **Rich embeds** — Drop in webpages, YouTube videos, podcasts, activities, AI-generated playgrounds, and other LearnHouse resources as cards on the canvas.
- **Member management** — Board owners can invite members and manage their access levels.

## Use Cases

- **Group projects** — Students collaborate on shared boards for team assignments.
- **Planning and brainstorming** — Teachers and staff map ideas, lesson plans, or workflows visually.
- **Workshops** — Run live exercises where the whole class contributes to a single shared surface.

---

# 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](https://judge0.com/) to provide sandboxed code execution inside **Code Playground** blocks on Dynamic Page activities. Students can write and run code directly in the platform, and teachers can define test cases for automatic grading.

## Supported Languages

The Code Playground block supports 30 languages: Python 3, JavaScript (Node), TypeScript, Java, C, C++, Rust, Go, PHP, Ruby, Kotlin, C#, Swift, Scala, Perl, R, Dart, Haskell, Lua, Elixir, Clojure, SQL, Bash, Objective-C, Pascal, Fortran, Prolog, Common Lisp, PowerShell, and Assembly (NASM).

## How It Works

1. A teacher inserts a **Code Playground** block into a Dynamic Page activity and (optionally) defines test cases as input/output pairs.
2. Students write their solution in the built-in code editor embedded in the activity.
3. On submission, the code is executed against all test cases in a sandboxed Judge0 environment.
4. Results are reported per test case — pass/fail, execution time, and memory usage. Submissions are stored per `activity_uuid` + `block_id`.

Code execution is surfaced as an editor block inside course content — it is **not** a standalone assignment task type. If you want graded code exercises, insert a Code Playground block into a Dynamic Page activity.

## 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 blocks 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 (quizzes and code blocks can be embedded inline).
- **Videos** — Upload video files directly or embed from YouTube and other external sources.
- **Documents** — PDF documents displayed with a built-in viewer.
- **Assignments** — Gradable tasks such as file uploads and quizzes. See [Assignments](/platform/assignments).
- **SCORM** — SCORM 1.2 and SCORM 2004 learning packages (Enterprise Edition).
- **Custom** — Escape hatch for custom activity implementations.

## 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.

### Assignments

Assignment activities are gradable tasks — currently file uploads and quiz-style submissions. Teachers can grade submissions from the dashboard, and results are recorded in the student's [Trail](/platform/courses/trails). See [Assignments](/platform/assignments) for details on task types and grading.

### SCORM

SCORM activities embed SCORM 1.2 or SCORM 2004 learning packages. This activity type is part of the Enterprise Edition.

### Custom

An escape hatch for custom activity implementations maintained outside of the built-in types.

Quizzes are available two ways: as an inline **Quiz** editor block inside a Dynamic Page (ungraded, lightweight knowledge checks) and as an **Assignment task** (gradable, stored submissions).

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

Per-organization AI controls let admins:

- Enable or disable AI features for the organization
- Set a per-user request limit to cap usage
- Toggle individual AI surfaces (such as the admin copilot)

The Google Gemini API key itself is a global, instance-level setting (`LEARNHOUSE_GEMINI_API_KEY`) — it is configured once at deployment and shared across all organizations. See [AI Setup](/self-hosting/configuration/ai-setup) for details.

## 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.

## 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 **AI-generated interactive HTML experiences** that teachers can publish alongside their courses. They are not a multi-language code runner — for that, use the [Code Playground editor block](/platform/code-execution) instead.

Playgrounds must be enabled in your [Organization Settings](/platform/organizations/settings) to be available. AI must also be enabled on the instance (see [AI Setup](/self-hosting/configuration/ai-setup)).

## How Playgrounds Work

A playground is an interactive HTML/JS artifact generated by Google Gemini from a natural-language prompt. Teachers describe what they want — a visualization, a simulation, an interactive exercise — and LearnHouse stores the resulting HTML alongside the rest of the course material.

Each playground supports up to 10 iterative refinements, so teachers can tweak prompts and regenerate without starting over.

## Key Features

- **AI-driven generation** — Prompt Gemini to produce custom interactive HTML experiences.
- **Iteration** — Refine a playground up to 10 times; each version is tracked.
- **Access control** — Each playground has one of three access modes: `PUBLIC`, `AUTHENTICATED`, or `RESTRICTED` (limited to specific user groups).
- **Reactions** — Users can react to playgrounds to provide feedback.

## Use Cases

- **Custom simulations** — Generate physics, math, or chemistry visualizations on demand.
- **Interactive examples** — Ship hands-on widgets that reinforce reading material.
- **Prototype activities** — Quickly explore teaching ideas before building them into full activities.

## Playgrounds vs Code Playground (editor block)

These are two distinct features that share a name:

| Feature | Purpose | Engine |
| --- | --- | --- |
| **Playgrounds** (this page) | AI-generated interactive HTML experiences | Google Gemini |
| **Code Playground** editor block | Multi-language "run this code" block inside Dynamic Page activities | Judge0 (see [Code Execution](/platform/code-execution)) |

---

# 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.
- **RSS feed** — Every podcast exposes a standard RSS feed at `/podcast/{shortUuid}/feed` that you can submit manually to Apple Podcasts Connect, Spotify for Podcasters, and other directories. LearnHouse does not publish to these services on your behalf.
- **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** — LearnHouse seeds four default roles: **Admin**, **Maintainer**, **Instructor**, and **User**. Organizations can also define custom roles with their own permission matrix.
- **Authentication** — Users authenticate via email/password or Google OAuth.

## 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.

## Login Methods

- **Email and password** — the default authentication method for every LearnHouse instance.
- **Google OAuth** — the only third-party login provider currently supported outside of Enterprise SSO.

For enterprise deployments, SAML (via WorkOS) and Custom OIDC are available — see [Enterprise SSO](/enterprise/sso).

## Security

Logins are rate-limited per IP, and accounts are temporarily locked after repeated failed attempts. SaaS-mode deployments additionally require users to verify their email address before they can sign in.

## 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. Roles are stored as database rows with a per-resource permission matrix (courses, users, usergroups, collections, organizations, chapters, activities, roles, dashboard, communities, discussions, podcasts, boards, playgrounds), so organizations can customize permissions or create their own roles on top of the defaults.

Every new instance is seeded with four default global 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

## Maintainer

Maintainers are mid-level managers who can operate most of the organization day-to-day but cannot change platform-level settings. They can:

- Manage courses, collections, and published content
- Manage users within the organization
- Moderate community discussions and boards

## Instructor

Instructors focus on teaching and creating educational content. They can:

- Create and edit their own courses, chapters, and activities
- View learner progress for their courses
- Use the AI assistant for content creation
- Manage collections they own

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

## User

Users are the default learner role. They can:

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

Users cannot create or edit courses or access administrative features.

## Custom Roles

Admins can create additional roles (global or organization-scoped) and fine-tune each permission individually from the dashboard.

---

# 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, powered by **Google Gemini**. 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

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).

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

```bash
learnhouse stop
learnhouse start
```

AI features require a valid Gemini API key with sufficient quota. Usage costs are billed directly by Google based on the models and volume used.

## Models

LearnHouse uses Gemini models directly — the model names are managed by LearnHouse and are not configurable:

- `gemini-2.5-flash` — main assistant responses
- `gemini-2.0-flash-lite` — short tasks such as chat title generation and follow-up suggestions

## Per-Organization AI Configuration

Once AI is enabled on the instance, each organization can toggle AI on or off and set usage limits from its admin settings. The Gemini API key itself is set once at deployment via `LEARNHOUSE_GEMINI_API_KEY` and is shared across organizations.

## Usage Limits

You can configure a per-organization request limit to control API costs. When a user exceeds the limit, further AI requests are rejected until the window resets.

---

# 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 | `AIza...` |
| `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_...` |
| `LEARNHOUSE_STRIPE_WEBHOOK_STANDARD_SECRET` | Stripe webhook signing secret (standard account) | `whsec_...` |
| `LEARNHOUSE_STRIPE_WEBHOOK_CONNECT_SECRET` | Stripe webhook signing secret (Connect) | `whsec_...` |
| `LEARNHOUSE_STRIPE_CLIENT_ID` | Stripe OAuth client ID for Connect | `ca_...` |

## 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` |

## 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 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 or Caddy configuration files based on your choices.

```bash
learnhouse setup
```

Flags: `--ci`, `--name`, `--domain`, `--port`, `--admin-email`, `--admin-password`, `--channel <stable|dev>`, `--no-start`.

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
```

### `learnhouse env`

Interactively edit environment variables in your `.env` file (Domain & Hosting, Database & Redis, Security, AI, Email (Resend), S3 Storage, OAuth).

```bash
learnhouse env
```

The `env` command edits a curated set of variables only. SMTP credentials (`LEARNHOUSE_SMTP_*`) are not editable through this command — edit `.env` directly if you need them.

## 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 status`

Show the status of each LearnHouse service.

```bash
learnhouse status
```

### `learnhouse logs`

Stream container logs for all services.

```bash
learnhouse logs
```

### `learnhouse update`

Update LearnHouse to the latest release or a specific version. Pulls the target image, rewrites `docker-compose.yml`, restarts services, and prompts for database migrations.

```bash
learnhouse update
learnhouse update --version 1.4.2
learnhouse update --migrate       # auto-apply migrations
learnhouse update --no-migrate    # skip migrations
```

### `learnhouse dev`

Start a full development environment (PostgreSQL + Redis in Docker, API + web + collab run 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 health`

Run the CLI's health checks (PostgreSQL connection, Redis ping, HTTP health endpoint, disk, resources).

```bash
learnhouse health
```

### `learnhouse shell`

Open an interactive shell inside a running container for debugging.

```bash
learnhouse shell
```

## Infrastructure

### `learnhouse deployments`

Manage deployments and scale memory limits for your LearnHouse containers.

```bash
learnhouse deployments
```

## Backup and Restore

### `learnhouse backup`

Create a PostgreSQL dump archive of your instance's database (plus a copy of `.env`). Archives are written to `<installDir>/backups/`.

```bash
learnhouse backup
```

### `learnhouse restore`

Restore a database from a backup archive.

```bash
learnhouse restore <path/to/learnhouse-backup-<timestamp>.tar.gz>
```

## 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 update` | Update to latest or a specific version |
| `learnhouse status` | Show service status |
| `learnhouse health` | Run health checks |
| `learnhouse logs` | Stream container logs |
| `learnhouse config` | View current configuration |
| `learnhouse env` | Edit environment variables |
| `learnhouse backup` | Create a database backup archive |
| `learnhouse restore` | Restore the database from an archive |
| `learnhouse doctor` | Diagnose Docker, containers, ports, DNS, and disk |
| `learnhouse shell` | Open a shell in a running container |
| `learnhouse deployments` | Manage deployments and memory 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/apps/cli/install.sh | bash
```

**Windows (PowerShell):**
```powershell
irm https://raw.githubusercontent.com/learnhouse/learnhouse/main/apps/cli/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
npx 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 commands for the PostgreSQL database.

The built-in backup only covers the database and your `.env` file. Uploaded content (images, videos, documents) stored on the filesystem is **not** included. See [Filesystem Content](#filesystem-content) below for recommendations.

## Creating a Backup

Create a backup with a single command:

```bash
learnhouse backup
```

This creates a timestamped archive containing:

- **`database.sql`** — a `pg_dump` of the LearnHouse PostgreSQL database
- **`.env`** — a copy of your instance's environment file (if present)

Backups are written to `<installDir>/backups/learnhouse-backup-<timestamp>.tar.gz`. The CLI prints the absolute path when the backup completes.

`learnhouse backup` only works when PostgreSQL runs in a local Docker container managed by the CLI. If you use an external managed database, use that provider's native backup tools instead.

## Restoring from a Backup

To restore from a backup file:

```bash
learnhouse restore <installDir>/backups/learnhouse-backup-<timestamp>.tar.gz
```

The restore command replays `database.sql` into the running database container. It does **not** stop or restart services — restart them yourself if needed.

Restoring a backup overwrites the database. 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 accumulate over time and can consume significant disk space. Implement a retention policy to remove old backups. For example, keep the last 7 daily backups:

```bash
find <installDir>/backups -name "learnhouse-backup-*.tar.gz" -mtime +7 -delete
```

## Filesystem Content

When `LEARNHOUSE_CONTENT_DELIVERY_TYPE=filesystem`, uploaded files live on the host (or in a Docker volume) and are **not** captured by `learnhouse backup`. You are responsible for backing up this directory separately — for example with `rsync`, a volume snapshot, or a scheduled `tar` job.

When using `s3api` storage, rely on your S3 provider's versioning, lifecycle, or cross-region replication features 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

The CLI offers three complementary commands:

```bash
learnhouse status    # quick container status for each service
learnhouse health    # PostgreSQL, Redis, HTTP health endpoint, disk, resources
learnhouse doctor    # deep diagnostics (Docker, ports, DNS, env validation, logs)
```

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

Use the built-in `update` command. It pulls the target image, rewrites the image tag in `docker-compose.yml`, restarts the stack, and prompts for database migrations.

```bash
# Update to the latest version
learnhouse update

# Update to a specific version
learnhouse update --version 1.4.2
```

Flags:

| Flag | Description |
|---|---|
| `--version <tag>` | Pull a specific image tag from `ghcr.io/learnhouse/app`. Defaults to `latest`. |
| `--migrate` | Run database migrations without prompting. |
| `--no-migrate` | Skip database migrations without prompting. |

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. Run the update
learnhouse update

# 3. Verify all services are healthy
learnhouse doctor

# 4. 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 when you accept the prompt or pass `--migrate`)
- 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 latest backup:

```bash
learnhouse restore <archive.tar.gz>
```

Backups live under `<installDir>/backups/` and are named `learnhouse-backup-<timestamp>.tar.gz`. The restore command replays the database dump and optionally restores the `.env` file — uploaded files on the filesystem are **not** restored (they are not included in the backup).
