# Environment Configuration

Complete reference for all environment variables in Mosaic Stack.

## Configuration File

All environment variables are defined in `.env` at the project root.

```bash
# Copy template
cp .env.example .env

# Edit configuration
nano .env
```

## Core Settings

### Database

```bash
# PostgreSQL connection string
DATABASE_URL=postgresql://user:password@host:port/database

# Examples:
# Local: postgresql://mosaic:mosaic_dev_password@localhost:5432/mosaic
# Docker: postgresql://mosaic:mosaic_dev_password@postgres:5432/mosaic
# Production: postgresql://user:pass@prod-host:5432/mosaic

# Docker-specific variables
POSTGRES_USER=mosaic
POSTGRES_PASSWORD=mosaic_dev_password
POSTGRES_DB=mosaic
POSTGRES_PORT=5432

# PostgreSQL Performance Tuning (Optional)
POSTGRES_SHARED_BUFFERS=256MB
POSTGRES_EFFECTIVE_CACHE_SIZE=1GB
POSTGRES_MAX_CONNECTIONS=100
```

**Format:** `postgresql://[user[:password]@][host][:port][/database][?options]`

### Application URLs

```bash
# Frontend URL (used for CORS and redirects)
NEXT_PUBLIC_APP_URL=http://localhost:3000

# API URL (if different from default)
API_URL=http://localhost:3001
```

### Node Environment

```bash
# Development, production, or test
NODE_ENV=development

# API port (default: 3001)
PORT=3001
```

## Authentication

### JWT Session Management

```bash
# Secret key for signing JWT tokens (REQUIRED)
# Generate with: openssl rand -base64 32
JWT_SECRET=your-secret-key-here

# Token expiration time
JWT_EXPIRATION=24h

# Accepted formats: 60 (seconds), 60s, 5m, 2h, 7d
```

**⚠️ Security Warning:** Never commit `JWT_SECRET` to version control. Use a strong, randomly generated secret in production.

### Authentik OIDC (Optional)

```bash
# Authentik instance URL with application path
OIDC_ISSUER=https://auth.example.com/application/o/mosaic-stack/

# OAuth2 client credentials
OIDC_CLIENT_ID=your-client-id
OIDC_CLIENT_SECRET=your-client-secret

# Callback URL (must match Authentik configuration)
OIDC_REDIRECT_URI=http://localhost:3001/auth/oauth2/callback/authentik
```

See [Authentik Setup](2-authentik.md) for complete OIDC configuration.

## Cache and Storage

### Valkey (Redis-compatible)

```bash
# Valkey connection string
VALKEY_URL=redis://localhost:6379

# With password
VALKEY_URL=redis://:password@localhost:6379

# Docker internal networking
VALKEY_URL=redis://valkey:6379

# Docker-specific variables
VALKEY_PORT=6379
VALKEY_MAXMEMORY=256mb
```

### File Storage (Future)

```bash
# Local file storage path
FILE_STORAGE_PATH=./storage/uploads

# S3-compatible storage
S3_ENDPOINT=https://s3.amazonaws.com
S3_BUCKET=mosaic-uploads
S3_ACCESS_KEY=your-access-key
S3_SECRET_KEY=your-secret-key
```

## AI Features (Optional)

### Ollama

```bash
# Local or remote Ollama instance
OLLAMA_MODE=local  # or 'remote'

# Ollama API endpoint
OLLAMA_ENDPOINT=http://localhost:11434

# Default model for text generation
OLLAMA_MODEL=llama2

# Default model for embeddings
OLLAMA_EMBEDDING_MODEL=nomic-embed-text
```

## Logging and Monitoring

### Log Level

```bash
# Log verbosity: error, warn, info, debug, verbose
LOG_LEVEL=info

# Production recommended: warn
# Development recommended: debug
```

### Sentry (Optional)

```bash
# Sentry DSN for error tracking
SENTRY_DSN=https://your-sentry-dsn@sentry.io/project-id

# Environment name
SENTRY_ENVIRONMENT=production

# Release version
SENTRY_RELEASE=v0.0.1
```

## Testing

```bash
# Test database (separate from development)
TEST_DATABASE_URL=postgresql://mosaic:mosaic@localhost:5432/mosaic_test

# Disable external services during testing
SKIP_EXTERNAL_SERVICES=true
```

## Development Tools

### Prisma

```bash
# Prisma Studio port (default: 5555)
PRISMA_STUDIO_PORT=5555

# Enable query logging
PRISMA_LOG_QUERIES=true
```

### Hot Reload

```bash
# Disable hot reload (if causing issues)
NO_WATCH=true

# Polling interval for file watching (ms)
WATCH_POLL_INTERVAL=1000
```

## Complete Example

**.env.example:**

```bash
# ======================
# Core Settings
# ======================
NODE_ENV=development
PORT=3001
NEXT_PUBLIC_APP_URL=http://localhost:3000

# ======================
# Database
# ======================
DATABASE_URL=postgresql://mosaic:mosaic@localhost:5432/mosaic
TEST_DATABASE_URL=postgresql://mosaic:mosaic@localhost:5432/mosaic_test

# ======================
# Authentication
# ======================
JWT_SECRET=change-this-to-a-random-secret-in-production
JWT_EXPIRATION=24h

# Authentik OIDC (Optional)
OIDC_ISSUER=https://auth.example.com/application/o/mosaic-stack/
OIDC_CLIENT_ID=your-client-id
OIDC_CLIENT_SECRET=your-client-secret
OIDC_REDIRECT_URI=http://localhost:3001/auth/oauth2/callback/authentik

# ======================
# Cache
# ======================
REDIS_URL=redis://localhost:6379

# ======================
# AI Features (Optional)
# ======================
OLLAMA_MODE=local
OLLAMA_ENDPOINT=http://localhost:11434
OLLAMA_MODEL=llama2
OLLAMA_EMBEDDING_MODEL=nomic-embed-text

# ======================
# Logging
# ======================
LOG_LEVEL=info

# ======================
# Development
# ======================
PRISMA_STUDIO_PORT=5555
PRISMA_LOG_QUERIES=false
```

## Validation

Environment variables are validated at application startup. Missing required variables will cause the application to fail with a clear error message.

**Required variables:**

- `DATABASE_URL`
- `JWT_SECRET`
- `NEXT_PUBLIC_APP_URL`

**Optional variables:**

- All OIDC settings (if using Authentik)
- All Ollama settings (if using AI features)
- Logging and monitoring settings

## Security Best Practices

1. **Never commit secrets** to version control
2. **Use strong JWT secrets** (min 32 characters, randomly generated)
3. **Rotate secrets regularly** in production
4. **Use different secrets per environment** (dev, staging, prod)
5. **Restrict database user permissions** in production
6. **Enable SSL for database connections** in production
7. **Use environment-specific .env files** (`.env.local`, `.env.production`)

## Troubleshooting

### Application Won't Start

```bash
# Check for syntax errors in .env
cat .env

# Ensure no quotes around values (unless they contain spaces)
# ✅ Good: JWT_SECRET=abc123
# ❌ Bad: JWT_SECRET="abc123"
```

### Database Connection Failed

```bash
# Test connection string
psql "postgresql://mosaic:mosaic@localhost:5432/mosaic"

# Check if PostgreSQL is running
sudo systemctl status postgresql
```

### OIDC Authentication Fails

```bash
# Verify OIDC_ISSUER ends with /
# ✅ Good: https://auth.example.com/application/o/mosaic-stack/
# ❌ Bad: https://auth.example.com/application/o/mosaic-stack

# Check OIDC_REDIRECT_URI matches Authentik configuration exactly
```

## Next Steps

- **Configure Authentik** — [Authentik Setup](2-authentik.md)
- **Review Database Schema** — [Development → Database](../../2-development/2-database/1-schema.md)
- **Start Development** — [Development → Workflow](../../2-development/1-workflow/1-branching.md)
