# Environment Variables

> **⚠️ BREAKING CHANGE - Tina4 v3.12.0**
>
> Every framework env var now requires the `TINA4_` prefix. The legacy un-prefixed names (`DATABASE_URL`, `SECRET`, `SMTP_HOST`, `HOST_NAME`, etc.) no longer work. Setting them at startup makes the framework refuse to boot with a list of renames.
>
> Run `tina4 env --migrate` to rewrite your existing `.env` automatically, or rename manually using the table below. The runtime guard prints the same mapping if it detects legacy names.
>
> **Conventional names stay un-prefixed:** `PORT`, `HOST`, `NODE_ENV`, `RACK_ENV`, `RUBY_ENV`, `ENVIRONMENT`. These are runtime/PaaS conventions, not framework config.

Tina4 is configured through environment variables, read from `.env` at the project root. Every variable has a sensible default; most projects set three or four values and leave the rest alone.

This chapter lists every variable the PHP framework reads, grouped by subsystem. Start with the minimum-config examples at the end, then come back here when you need to tune something specific.

---

## Core Server

| Variable | Default | Description |
|----------|---------|-------------|
| `HOST` | `0.0.0.0` | Bind address. `0.0.0.0` listens on every interface. `127.0.0.1` restricts to localhost. |
| `TINA4_HOST` | `0.0.0.0` | Tina4-specific bind override consulted by `App::serve()` and `Server` when no `$host` argument is passed. Wins over the conventional `HOST` for the framework's own server. |
| `PORT` | `7145` | HTTP server port. The Rust CLI prefers `TINA4_PORT` but falls back to `PORT`. |
| `TINA4_PORT` | _(inherits `PORT`)_ | Explicit Tina4-specific port override. Takes precedence over `PORT` when both are set. |
| `TINA4_WS_PORT` | _(inherits port)_ | Separate port for the WebSocket server. Leave unset to share the HTTP port. |
| `TINA4_HOST_NAME` | `localhost:7145` | Fully-qualified host used in generated absolute URLs (Swagger, OAuth redirects, emails). |
| `TINA4_DEBUG` | `false` | Master debug toggle. Enables Swagger UI, dev dashboard, live reload, template dump filter, error overlay. Never set to `true` in production. |
| `TINA4_STRICT_DISCOVER` | unset | Whether a file in `src/` that fails to load stops the app. Unset, outside debug `tina4 serve` exits naming the file, and under PHP-FPM, Apache or `php -S` every request answers 500; in debug the app carries on, so a typo never kills the dev server. `true` makes debug strict too; `false` serves without the broken file, as before 3.13.169 (ADR-0112). |
| `TINA4_LOG_LEVEL` | `ERROR` | Minimum message level shown when `TINA4_DEBUG=true`. Options: `DEBUG`, `INFO`, `WARNING`, `ERROR`, `ALL`. |
| `TINA4_NO_BROWSER` | `false` | Stops `tina4 serve` from opening your browser on every restart. Recommended during active development. |
| `TINA4_NO_RELOAD` | `false` | Disables the dev hot-reload signal from the Rust CLI. Use when you want a stable server for debugging. |
| `TINA4_SUPPRESS` | `false` | Hides the Tina4 startup banner. Useful in CI and systemd units where stdout is ingested. |
| `TINA4_VERSION` | _(framework)_ | Override the version string reported by `/__dev/api/system`. Mostly for testing. |
| `TINA4_CLI_SERVE` | _(none)_ | Set internally by the Rust CLI to signal managed mode. Do not set manually. |
| `TINA4_SHUTDOWN_TIMEOUT` | `30` | Seconds a graceful shutdown (SIGTERM or SIGINT) waits for in-flight requests, including the per-request processes the built-in server forks, before it force-closes them. An invalid value warns and keeps 30. |
| `TINA4_REQUEST_TIMEOUT` | `30` | Built-in server: seconds a client may stay silent. Partway through a request it gets 408; between two requests the idle keep-alive connection closes quietly. `0` switches the timer off. |
| `TINA4_PUBLIC_DIR` | _(empty)_ | Override directory served as static files at `/`. When unset, the static-file middleware searches `src/public/` and the framework's bundled public assets. |
| `TINA4_TEMPLATE_ROUTING` | `on` | Auto-routing of Twig templates from `src/templates/`. Set to `off`, `false`, `0`, `no`, or `disabled` to require explicit `Router::get()` for every URL. |
| `TINA4_ALLOW_LEGACY_ENV` | `false` | Bypass the v3.12 boot guard that rejects un-prefixed legacy env vars (`DATABASE_URL`, `SECRET`, `SMTP_HOST`, etc.). Use only in CI / migration scripts during the transition window. |
| `TINA4_ENV_FILE` | `.env` | Alternate path for the dotenv file loaded at boot. Resolved relative to the project root unless absolute. Useful for per-environment files (e.g. `.env.production`) without symlinking. |
| `TINA4_HEALTH_PATH` | `/__health` | Path the built-in liveness route registers under. `/health` is always registered as well, so setting this adds a path and never removes one. The body is `{status, uptime, framework}`, plus `version` when `TINA4_DEBUG=true`. |

---

## Routing

| Variable | Default | Description |
|----------|---------|-------------|
| `TINA4_TRAILING_SLASH_REDIRECT` | `false` | When truthy, any request path ending in `/` (other than the bare root) is 301-redirected to the slash-stripped form. The query string is preserved. Lets you normalise URLs without writing per-route handlers. |

---

## Secrets and Authentication

| Variable | Default | Description |
|----------|---------|-------------|
| `TINA4_SECRET` | _(empty)_ | JWT signing secret. Must be long, random, and unique per environment. **Never commit.** |
| `TINA4_JWT_ALGORITHM` | `HS256` | JWT signing algorithm. Supports `HS256`, `HS384`, `HS512`. |
| `TINA4_TOKEN_EXPIRES_IN` | `60` | Default JWT lifetime in minutes. Wins over `TINA4_TOKEN_LIMIT` when both are set. A value that isn't a positive whole number gives 60, with one warning. A lifetime argument of `0` (or less) also means this default. |
| `TINA4_TOKEN_LIMIT` | `60` | Older name for `TINA4_TOKEN_EXPIRES_IN`, read when that one is unset. |
| `TINA4_API_KEY` | _(empty)_ | Static API key. Sent as `Authorization: Bearer <key>` it opens secured routes with no user attached, so `role()`/`can()` routes answer 403, and CSRF doesn't apply. Read from the Bearer header only. Unset or blank means off. |

---

## Database

| Variable | Default | Description |
|----------|---------|-------------|
| `TINA4_DATABASE_URL` | `sqlite:///data/app.db` | Connection URL. Scheme selects the driver: `sqlite`, `postgres`, `mysql`, `mssql`, `sqlserver`, `firebird`. |
| `TINA4_DATABASE_USERNAME` | _(empty)_ | Overrides the username embedded in `TINA4_DATABASE_URL`. |
| `TINA4_DATABASE_PASSWORD` | _(empty)_ | Overrides the password embedded in `TINA4_DATABASE_URL`. |
| `TINA4_DATABASE_FIREBIRD_PATH` | _(empty)_ | Overrides the database path/alias parsed from `TINA4_DATABASE_URL` for Firebird. Useful for Windows backslash paths and split-config setups. |
| `TINA4_DATABASE_URL` | _(empty)_ | Legacy alias for `TINA4_DATABASE_URL`. Prefer `TINA4_DATABASE_URL` in new projects. |
| `TINA4_AUTOCOMMIT` | `true` | Standalone writes auto-commit on their own connection (durable + visible across a pool); explicit transactions stay atomic. Set `false` for strict manual-commit mode. |
| `TINA4_DB_CACHE` | `false` | Enables in-memory query-result caching for read queries. |
| `TINA4_DB_CACHE_TTL` | `60` | Query cache TTL in seconds when `TINA4_DB_CACHE=true`. |
| `TINA4_DB_POOL` | `0` | Default connection-pool size used when a caller constructs `Database` without passing `$pool`. `0` is one connection per process (a PHP process serves one request at a time); values above zero enable pooled adapters lazily. An explicit constructor argument always wins. |
| `TINA4_DB_RECONNECT_RETRY` | `true` | When the database connection drops, reconnect, replay the connect hooks, and run the failed statement once more. A statement is never re-run inside a transaction the server had open. Set `false` if each request keeps session state the hooks can't replay, such as row-level security set with `set_config` (ADR-0110). |
| `TINA4_MIGRATION_ID` | _(timestamp)_ | Override the migration ID used when recording applied migrations. |

---

## CORS

| Variable | Default | Description |
|----------|---------|-------------|
| `TINA4_CORS_ORIGINS` | _(empty)_ | Comma-separated allowed origins. Empty denies every cross-origin request; set the origins your front end is served from. `*` allows any origin and has to be set explicitly. |
| `TINA4_CORS_METHODS` | `GET,POST,PUT,PATCH,DELETE,OPTIONS` | Allowed request methods. |
| `TINA4_CORS_HEADERS` | `Content-Type,Authorization,X-Requested-With` | Allowed request headers. |
| `TINA4_CORS_CREDENTIALS` | `false` | Send `Access-Control-Allow-Credentials: true`. Required for cross-origin cookies. |
| `TINA4_CORS_MAX_AGE` | `600` | Preflight cache lifetime in seconds. |

---

## Security Headers

| Variable | Default | Description |
|----------|---------|-------------|
| `TINA4_CSP` | `default-src 'self'` | `Content-Security-Policy` header. |
| `TINA4_CSRF` | `false` | CSRF token validation on POST/PUT/PATCH/DELETE. Requires `_csrf` in the body or `X-CSRF-Token` header. |
| `TINA4_HSTS` | _(empty/off)_ | `Strict-Transport-Security` max-age in seconds. Set `31536000` in production with HTTPS. |
| `TINA4_FRAME_OPTIONS` | `DENY` | `X-Frame-Options` header. Set `SAMEORIGIN` if you embed your own app in an iframe. |
| `TINA4_REFERRER_POLICY` | `strict-origin-when-cross-origin` | `Referrer-Policy` header. |
| `TINA4_PERMISSIONS_POLICY` | _(empty)_ | `Permissions-Policy` header. Example: `geolocation=(), microphone=()`. |
| `TINA4_COOP` | `same-origin-allow-popups` | `Cross-Origin-Opener-Policy` header. The default keeps OAuth and payment popups working; set `same-origin` for a fully isolated context (pairs with a COEP header to unlock `SharedArrayBuffer`). |

---

## Proxies and SSRF protection

Behind a load balancer the real client IP rides in a forwarded header. Tina4 will only trust that header when the peer is a proxy you have listed in `TINA4_TRUSTED_PROXIES`. The outbound guard runs the other way: it will refuse a request aimed at a private address unless `TINA4_ALLOW_PRIVATE_REQUESTS` opts out.

| Variable | Default | Description |
|----------|---------|-------------|
| `TINA4_TRUSTED_PROXIES` | _(empty)_ | Comma-separated list of proxy IPs or Classless Inter-Domain Routing (CIDR) ranges whose `X-Forwarded-For` / `X-Forwarded-Proto` headers are believed. Empty means the direct peer is always treated as the client. Only a listed proxy's `X-Forwarded-Proto` sets the session cookies' `Secure` flag, HSTS and the CORS same-origin check, and the rate limiter tells clients apart only through a listed proxy. |
| `TINA4_ALLOW_PRIVATE_REQUESTS` | _(off)_ | Server-Side Request Forgery (SSRF) opt-out. Off by default, so outbound fetches to private, loopback and link-local addresses are refused. Set truthy only in a trusted internal deployment. |

---

## Rate Limiting

| Variable | Default | Description |
|----------|---------|-------------|
| `TINA4_RATE_LIMIT` | _(unset: off)_ | Maximum requests per window per IP. Setting it switches the global limiter on. `false`, `0`, `no` or `off` switches every limiter off (logged once). Any other value that isn't a positive whole number throws `RateLimitConfigError`: the built-in server doesn't start, and under a web server every request answers 500. |
| `TINA4_RATE_WINDOW` | `60` | Rate-limit window in seconds. Must be a positive whole number, or the start fails the same way. |

---

## Sessions

| Variable | Default | Description |
|----------|---------|-------------|
| `TINA4_SESSION_BACKEND` | `file` | Storage backend. Options: `file`, `redis`, `valkey`, `mongo`, `database`. |
| `TINA4_SESSION_HANDLER` | _(inherits `_BACKEND`)_ | Alternate handler class name. Overrides `TINA4_SESSION_BACKEND`. |
| `TINA4_SESSION_NAME` | `tina4_session` | Cookie name written by the framework session manager. Distinct from `TINA4_PHP_SESSION_NAME`, which controls the native PHP session cookie. A name that isn't a valid HTTP token is ignored with one logged error, and the cookie stays `tina4_session`. |
| `TINA4_SESSION_TTL` | `3600` | Session expiry in seconds of inactivity. `0` never expires, and the cookie lasts for the browser session. A negative, decimal or text value uses 3600 with one warning. |
| `TINA4_SESSION_SAMESITE` | `Lax` | SameSite cookie attribute. Options: `Strict`, `Lax`, `None`. |
| `TINA4_SESSION_HTTPONLY` | `true` | Emit the `HttpOnly` attribute on the session cookie. Leave on unless JavaScript genuinely needs to read the cookie. |
| `TINA4_SESSION_SECURE` | `false` | Emit the `Secure` attribute on the session cookie. Setting `TINA4_SESSION_SAMESITE=None` forces this to `true` regardless of the value here. Behind a TLS-terminating proxy, set it or list the proxy in `TINA4_TRUSTED_PROXIES`. |
| `TINA4_SESSION_PATH` | `data/sessions` | Filesystem path for the file backend. |
| `TINA4_PHP_SESSION_NAME` | `PHPSESSID` | Cookie name used by native PHP `$_SESSION` (separate from the framework session). |
| `TINA4_PHP_SESSION_PATH` | _(system temp)_ | `session.save_path` for native PHP sessions. The framework configures it before `session_start()` so the SAPI and the built-in server share session storage. |

### Redis/Valkey session backend

| Variable | Default | Description |
|----------|---------|-------------|
| `TINA4_SESSION_REDIS_HOST` | `localhost` | Redis host. |
| `TINA4_SESSION_REDIS_PORT` | `6379` | Redis port. |
| `TINA4_SESSION_REDIS_PASSWORD` | _(none)_ | Redis auth password. |
| `TINA4_SESSION_REDIS_DB` | `0` | Redis database number. |
| `TINA4_SESSION_REDIS_URL` | _(none)_ | Full `redis://` URL. Overrides the individual fields when set. |
| `TINA4_SESSION_VALKEY_HOST` | `localhost` | Valkey host. |
| `TINA4_SESSION_VALKEY_PORT` | `6379` | Valkey port. |
| `TINA4_SESSION_VALKEY_PASSWORD` | _(none)_ | Valkey auth password. |
| `TINA4_SESSION_VALKEY_DB` | `0` | Valkey database number. |

### MongoDB session backend

| Variable | Default | Description |
|----------|---------|-------------|
| `TINA4_SESSION_MONGO_URI` | `mongodb://localhost:27017` | MongoDB connection string. `TINA4_SESSION_MONGO_URL` is accepted as a legacy alias. |
| `TINA4_SESSION_MONGO_DB` | `tina4` | MongoDB database name. |
| `TINA4_SESSION_MONGO_COLLECTION` | `sessions` | Collection that holds the sessions. |
| `TINA4_SESSION_MONGO_USERNAME` | _(none)_ | Login user, for a server that requires one. |
| `TINA4_SESSION_MONGO_PASSWORD` | _(none)_ | Login password. |

With credentials set (here or in the URI), the store logs in through the official driver only: ext-mongodb and `composer require mongodb/mongodb`. Without them each session operation fails with an error naming both. With no credentials the built-in client needs nothing installed.

### Memcached session backend

| Variable | Default | Description |
|----------|---------|-------------|
| `TINA4_SESSION_MEMCACHED_HOST` | `localhost` | Memcached host. |
| `TINA4_SESSION_MEMCACHED_PORT` | `11211` | Memcached port. |
| `TINA4_SESSION_MEMCACHED_PREFIX` | `tina4:session:` | Key prefix for session entries, so one Memcached instance can serve several apps. |

---

## Templates

| Variable | Default | Description |
|----------|---------|-------------|
| `TINA4_TEMPLATE_CACHE_TTL` | `0` | Lifetime of compiled Frond templates in production, in seconds. `0` means cache forever (no filesystem checks per render); a positive value re-reads and re-tokenises a template once it has been cached for that long. Ignored when `TINA4_DEBUG=true`; debug mode always re-reads. |

---

## Cache

| Variable | Default | Description |
|----------|---------|-------------|
| `TINA4_CACHE_BACKEND` | `memory` | Response cache backend. Options: `memory`, `file`, `redis`, `valkey`, `memcached`, `mongodb`, `database`. Falls back to `file` if the configured backend is unreachable. |
| `TINA4_CACHE_DIR` | `data/cache` | Cache directory for the file backend. |
| `TINA4_CACHE_TTL` | `60` | Default cache TTL in seconds. |
| `TINA4_CACHE_MAX_ENTRIES` | `1000` | Maximum cache entries. Oldest entries evicted first. |
| `TINA4_CACHE_URL` | _(none)_ | Connection URL for remote cache backends (e.g. `redis://localhost:6379`). For `database`, falls back to `TINA4_DATABASE_URL` when unset. |
| `TINA4_CACHE_USERNAME` | _(none)_ | Username for the cache backend. May also be embedded in `TINA4_CACHE_URL`. |
| `TINA4_CACHE_PASSWORD` | _(none)_ | Password for the cache backend. May also be embedded in `TINA4_CACHE_URL` (e.g. `redis://:pass@host`). Memcached is unauthenticated. |

---

## Queues

| Variable | Default | Description |
|----------|---------|-------------|
| `TINA4_QUEUE_BACKEND` | `file` | Queue backend. Options: `file`, `kafka`, `rabbitmq`, `mongo`, `database`. |
| `TINA4_QUEUE_PATH` | `data/queue` | Filesystem path for the file backend. |
| `TINA4_QUEUE_URL` | _(none)_ | Connection URL for remote backends. |

### Kafka queue backend

| Variable | Default | Description |
|----------|---------|-------------|
| `TINA4_KAFKA_BROKERS` | `localhost:9092` | Comma-separated broker list. |
| `TINA4_KAFKA_GROUP_ID` | `tina4_consumer_group` | Kafka consumer group ID. |
| `TINA4_KAFKA_AUTO_OFFSET_RESET` | `earliest` | Where a NEW Kafka consumer group (no committed offset) starts: `earliest` (replay the backlog) or `latest` (skip it). Falls back to the bare `KAFKA_AUTO_OFFSET_RESET`. |

### RabbitMQ queue backend

| Variable | Default | Description |
|----------|---------|-------------|
| `TINA4_RABBITMQ_HOST` | `localhost` | RabbitMQ host. |
| `TINA4_RABBITMQ_PORT` | `5672` | RabbitMQ port. |
| `TINA4_RABBITMQ_USERNAME` | `guest` | RabbitMQ username. |
| `TINA4_RABBITMQ_PASSWORD` | `guest` | RabbitMQ password. |
| `TINA4_RABBITMQ_VHOST` | `/` | RabbitMQ virtual host. |

### MongoDB queue backend

| Variable | Default | Description |
|----------|---------|-------------|
| `TINA4_MONGO_URI` | _(none)_ | Full MongoDB connection string. Overrides host/port when set. |
| `TINA4_MONGO_HOST` | `localhost` | MongoDB host. |
| `TINA4_MONGO_PORT` | `27017` | MongoDB port. |
| `TINA4_MONGO_USERNAME` | _(none)_ | MongoDB username. |
| `TINA4_MONGO_PASSWORD` | _(none)_ | MongoDB password. |
| `TINA4_MONGO_DB` | `tina4` | MongoDB database name. |
| `TINA4_MONGO_COLLECTION` | `tina4_queue` | MongoDB collection name for jobs. |

---

## WebSocket Backplane

| Variable | Default | Description |
|----------|---------|-------------|
| `TINA4_WS_BACKPLANE` | _(none)_ | Backplane type. Set `redis` for multi-instance broadcasts. |
| `TINA4_WS_BACKPLANE_URL` | `redis://localhost:6379` | Connection URL for the backplane. |
| `TINA4_WS_MAX_CONNECTIONS` | `10000` | Open WebSocket connections a server holds. The next upgrade is answered `503 Service Unavailable` before the handshake; a closed connection frees its slot. In a `TINA4_SERVE_WORKERS` pool the cap applies per worker. |
| `TINA4_WS_MAX_FRAME_SIZE` | `1048576` | Largest WebSocket frame payload a server accepts, in bytes (1 MiB). A frame declaring more is refused on its header: a warning is logged and that connection is closed. |

---

## Email

| Variable | Default | Description |
|----------|---------|-------------|
| `TINA4_MAIL_HOST` | _(none)_ | SMTP server hostname. |
| `TINA4_MAIL_PORT` | `587` | SMTP server port. |
| `TINA4_MAIL_USERNAME` | _(none)_ | SMTP authentication username. |
| `TINA4_MAIL_PASSWORD` | _(none)_ | SMTP authentication password. |
| `TINA4_MAIL_FROM` | _(none)_ | Default sender email address. |
| `TINA4_MAIL_FROM_NAME` | _(none)_ | Default sender display name. |
| `TINA4_MAIL_ENCRYPTION` | `tls` | Connection encryption. Options: `tls`, `ssl`, `none`. |
| `TINA4_MAIL_IMAP_HOST` | _(none)_ | IMAP server for inbound mail. |
| `TINA4_MAIL_IMAP_PORT` | `993` | IMAP server port. |
| `TINA4_MAIL_IMAP_USERNAME` | _(none)_ | IMAP authentication username. |
| `TINA4_MAIL_IMAP_PASSWORD` | _(none)_ | IMAP authentication password. |
| `TINA4_MAIL_IMAP_ENCRYPTION` | `tls` | IMAP transport encryption. Accepts `tls`, `starttls`, or `none`; any other value is silently coerced back to `tls`. Independent of `TINA4_MAIL_ENCRYPTION` so Gmail-style setups can use IMAPS on 993 alongside SMTP STARTTLS on 587. |
| `TINA4_MAIL_CAPTURE` | `false` | Force local DevMailbox capture and skip SMTP, even when an SMTP host exists. A missing host also captures. |
| `TINA4_MAIL_REDIRECT_TO` | _(none)_ | Comma-separated safety recipients for real SMTP delivery. Replaces To, Cc, and Bcc. |
| `TINA4_MAILBOX_DIR` | `data/mailbox` | Storage directory for captured mail. This setting does not enable or disable capture. |

> `TINA4_DEBUG` does not suppress email. On staging, set `TINA4_MAIL_CAPTURE=true` to keep every message local, or set `TINA4_MAIL_REDIRECT_TO=qa@example.com,product@example.com` to exercise SMTP without reaching original recipients. Capture takes precedence when both are set.

> `TINA4_MAIL_HOST`, `TINA4_MAIL_PORT`, `TINA4_MAIL_USERNAME`, `TINA4_MAIL_PASSWORD` are also accepted as aliases for the `TINA4_MAIL_*` equivalents. New projects should use the `TINA4_MAIL_*` names.

---

## Logging

| Variable | Default | Description |
|----------|---------|-------------|
| `TINA4_LOG_LEVEL` | `ERROR` | Minimum log level written to files. Options: `ALL`, `DEBUG`, `INFO`, `WARNING`, `ERROR`. |
| `TINA4_LOG_DEBUG` | `0` | Numeric flag for debug-level messages. Used internally by `Debug::message()`. |
| `TINA4_LOG_INFO` | `1` | Numeric flag for info-level messages. |
| `TINA4_LOG_ERROR` | `3` | Numeric flag for error-level messages. |
| `TINA4_LOG_MAX_SIZE` | `10485760` | Per-file log size limit in bytes (10 MB). Rotated when exceeded. |
| `TINA4_LOG_KEEP` | `5` | Number of rotated log files to retain. |

### Log pipeline (sink, format, rotation)

Logs default to stdout. Set `TINA4_LOG_OUTPUT=file` plus `TINA4_LOG_FILE=app.log` to write to disk; the framework rotates at `TINA4_LOG_ROTATE_SIZE` bytes and keeps `TINA4_LOG_ROTATE_KEEP` backups.

| Variable | Default | Description |
|----------|---------|-------------|
| `TINA4_LOG_FILE` | _(empty = stdout only)_ | Primary log filename. A relative value is joined with `TINA4_LOG_DIR`; an absolute path overrides both directory and filename. Leave empty to skip file output entirely. |
| `TINA4_LOG_DIR` | `logs` | Directory log files are written into when `TINA4_LOG_OUTPUT` includes `file`. Created on first write if missing. |
| `TINA4_LOG_FORMAT` | `text` | Wire format for emitted lines. `text` is human-readable; `json` emits one structured object per line for ingestion by Loki, ELK, etc. |
| `TINA4_LOG_OUTPUT` | `stdout` | Where lines are sent. `stdout` writes to the process stream (great for systemd / containers), `file` writes only to `TINA4_LOG_FILE`, `both` does both. |
| `TINA4_LOG_CRITICAL` | `false` | Enable `Log::critical()` emission. Off by default so security-relevant criticals can be intentionally surfaced rather than buried in routine output. |
| `TINA4_LOG_ROTATE_SIZE` | `10485760` | Rotation threshold in bytes (10 MB default). Set `0` to disable rotation entirely, useful when an external tool (logrotate, Docker driver) owns the file. |
| `TINA4_LOG_ROTATE_KEEP` | `5` | Number of rotated backups to retain. Older files are pruned on rotation. |

---

## Uploads

| Variable | Default | Description |
|----------|---------|-------------|
| `TINA4_MAX_UPLOAD_SIZE` | `10485760` | Maximum multipart upload size in bytes (10 MB). |

---

## Localisation

| Variable | Default | Description |
|----------|---------|-------------|
| `TINA4_LOCALE` | `en` | Default locale for `I18n`. |
| `TINA4_LOCALE_DIR` | `src/locale` | Directory containing locale JSON files. |

---

## Services (background tasks)

| Variable | Default | Description |
|----------|---------|-------------|
| `TINA4_SERVICE_DIR` | `src/services` | Directory scanned for service classes. |
| `TINA4_SERVICE_SLEEP` | `1` | Default tick interval (seconds) when a service does not specify one. |

---

## Application AI Client and Developer AI Tools

The app-facing `Ai` client and the developer dashboard share the `TINA4_AI_*` namespace. The client supports local OpenAI-compatible servers, OpenAI, and Anthropic. See [Chapter 40: AI Client](40-ai-client.md) for code examples.

| Variable | Default | Description |
|----------|---------|-------------|
| `TINA4_AI_PROVIDER` | `local` | Provider used by the app-facing client: `local`, `openai`, or `anthropic`. |
| `TINA4_AI_URL` | Provider-specific | Base URL or full endpoint. Local defaults to `http://localhost:11437`; OpenAI and Anthropic use their public API bases. |
| `TINA4_AI_MODEL` | Provider-specific | Default model. Local uses `llama3.2`, OpenAI uses `gpt-4o-mini`, and Anthropic uses `claude-3-5-haiku-latest`. |
| `TINA4_AI_KEY` | _(none)_ | Required before an OpenAI or Anthropic request. Local requests need no key. |
| `TINA4_AI_TIMEOUT` | `60` | Total request deadline in seconds, including retries and response reads. |
| `TINA4_AI_CONNECT_TIMEOUT` | `10` | Connection-establishment deadline in seconds. |
| `TINA4_AI_MAX_RETRIES` | `2` | Retries before output for connection failures, HTTP 429, and HTTP 5xx. |
| `TINA4_EMBED_URL` | _(inherits `TINA4_AI_URL`)_ | Optional embedding base URL or full endpoint. |
| `TINA4_RAG_URL` | `http://localhost:11438` | RAG service used by the developer dashboard. |
| `TINA4_VISION_URL` | `http://localhost:11437/api/chat` | Vision endpoint used by developer tools, not the app-facing AI client. |
| `TINA4_IMAGE_URL` | `http://localhost:11437/api/generate` | Image endpoint used by developer tools, not the app-facing AI client. |
| `TINA4_SUPERVISOR_URL` | `http://localhost:9999` | Rust supervisor URL used by developer tools. |
| `TINA4_MCP_REMOTE` | `false` | Allows MCP to bind beyond localhost. Do not enable it on a public production interface. |
| `TINA4_NO_AI_PORT` | `false` | Disables the developer AI port listener. |
| `TINA4_OVERRIDE_CLIENT` | `false` | Lets the framework start without the Rust client in containers and CI. |

---

## Swagger / OpenAPI

| Variable | Default | Description |
|----------|---------|-------------|
| `TINA4_SWAGGER_TITLE` | `Tina4 API` | OpenAPI spec title shown in the Swagger UI. |
| `TINA4_SWAGGER_DESCRIPTION` | `Auto-generated from Tina4 routes` | OpenAPI spec description. |
| `TINA4_SWAGGER_VERSION` | `1.0.0` | OpenAPI spec version. |
| `TINA4_SWAGGER_ENABLED` | _(inherits `TINA4_DEBUG`)_ | Master switch for Swagger UI and the `/swagger` and `/swagger/openapi.json` routes. When unset, follows `TINA4_DEBUG` so Swagger is on in dev and off in prod automatically. Set explicitly to expose docs in production. |
| `TINA4_SWAGGER_CONTACT_EMAIL` | _(empty)_ | Contact email written into the generated OpenAPI `info.contact` block. |
| `TINA4_SWAGGER_LICENSE` | _(empty)_ | License name written into the generated OpenAPI `info.license` block. |
| `TINA4_SWAGGER_CONTACT_TEAM` | _(empty)_ | Contact name rendered in the OpenAPI spec's `info.contact.name` field. |
| `TINA4_SWAGGER_CONTACT_URL` | _(empty)_ | Contact URL rendered in the OpenAPI spec's `info.contact.url` field. |

---

## GraphQL

| Variable | Default | Description |
|----------|---------|-------------|
| `TINA4_GRAPHQL_ENDPOINT` | `/graphql` | URL path the framework binds the GraphQL handler to. The same value is used when generating `__schema` links and the dev-dashboard query console URL. |
| `TINA4_GRAPHQL_AUTO_SCHEMA` | `true` | Auto-generate the GraphQL schema from registered ORM models. Set to `false` to skip introspection scaffolding when you supply a hand-written schema. |
| `TINA4_GRAPHQL_MAX_NODES` | `1000` | Maximum nodes a single query may request before the handler rejects it. Caps query cost against a deeply nested or aliased request. Set `0` to disable the limit. |

---

## HTTP Status Constants

For use in route handlers instead of raw integers:

```php
return $response->json($data, \Tina4\HTTP_CREATED);
return $response("<error/>", \Tina4\HTTP_BAD_REQUEST, \Tina4\APPLICATION_XML);
```

See [Chapter 3: Request and Response](./03-request-response.md#http-status-constants) for the full table.

---

## Log-Level Constants

Passed to `Debug::message()` to tag severity:

| Constant | Description |
|----------|-------------|
| `TINA4_LOG_DEBUG` | Verbose developer messages. |
| `TINA4_LOG_INFO` | Normal operational messages. |
| `TINA4_LOG_WARNING` | Non-fatal anomalies. |
| `TINA4_LOG_ERROR` | Recoverable errors. |
| `TINA4_LOG_CRITICAL` | Fatal or security-relevant events. |

```php
\Tina4\Debug::message("User " . $id . " missed the cache", TINA4_LOG_INFO);
```

---

## Configuration Recipes

The tables above list every knob. These are the setups most apps actually reach for, ready to paste into `.env`. Each block sets only what the feature needs. Everything else keeps its default.

### PostgreSQL in production

One URL points the ORM, the migrations, and the query builder at Postgres. Credentials can ride in the URL or sit in their own variables, which keeps the password out of your shell history.

```bash
TINA4_DATABASE_URL=postgresql://localhost:5432/myapp
TINA4_DATABASE_USERNAME=myapp
TINA4_DATABASE_PASSWORD=changeme
TINA4_DB_POOL=4
```

`TINA4_DB_POOL=4` gives each process a pool of up to four connections. Leave it at `0` (one connection per process) unless the app runs requests concurrently inside one process.

### A shared cache on Redis

The response cache and the cross-request query cache both speak to the same Redis. Point them at it and every instance shares one cache, invalidated globally on every write.

```bash
TINA4_CACHE_BACKEND=redis
TINA4_CACHE_URL=redis://localhost:6379
TINA4_DB_CACHE=true
TINA4_DB_CACHE_BACKEND=redis
TINA4_DB_CACHE_URL=redis://localhost:6379
```

If Redis is down or the driver is missing, the cache logs a warning and falls back to the file backend. It never silently stops caching.

### Sessions that survive more than one box

The file backend is fine for a single server. Move sessions to Redis the moment you run more than one instance, so a user stays logged in whichever instance answers the next request.

```bash
TINA4_SESSION_BACKEND=redis
TINA4_SESSION_REDIS_HOST=localhost
TINA4_SESSION_REDIS_PORT=6379
TINA4_SESSION_SECURE=true
TINA4_SESSION_SAMESITE=Strict
```

`TINA4_SESSION_SECURE=true` keeps the cookie off plain HTTP. Turn it on once you have TLS.

### A queue on RabbitMQ or Kafka

One URL is enough for RabbitMQ; the per-field variables only exist for split configs. The queue API stays identical whichever backend you pick.

```bash
TINA4_QUEUE_BACKEND=rabbitmq
TINA4_QUEUE_URL=amqp://guest:guest@localhost:5672/
```

Kafka reads a broker list instead:

```bash
TINA4_QUEUE_BACKEND=kafka
TINA4_KAFKA_BROKERS=localhost:9092
TINA4_KAFKA_GROUP_ID=myapp_workers
```

### WebSocket broadcasts across instances

A single server broadcasts in memory. Add a backplane and a message sent on one instance reaches clients connected to every other instance.

```bash
TINA4_WS_BACKPLANE=redis
TINA4_WS_BACKPLANE_URL=redis://localhost:6379
TINA4_WS_ALLOWED_ORIGINS=https://myapp.com
```

Set the origin allow-list in production. Empty allows every origin, which is fine in dev and risky on the public internet.

### Locked-down production headers

The defaults are already safe. These four tighten the screws for a public site on HTTPS.

```bash
TINA4_CORS_ORIGINS=https://myapp.com,https://www.myapp.com
TINA4_HSTS=31536000
TINA4_FRAME_OPTIONS=DENY
TINA4_SESSION_SECURE=true
```

Never pair `TINA4_CORS_CREDENTIALS=true` with `TINA4_CORS_ORIGINS=*`. Name your real origins instead.

### The dev dashboard AI, kept local

The dashboard AI talks to a local model through Ollama by default, so nothing leaves your machine. Point the URLs elsewhere only when you run the hosted Tina4 AI services.

```bash
TINA4_AI_URL=http://localhost:11437/api/chat
TINA4_AI_MODEL=qwen2.5-coder:14b
TINA4_RAG_URL=http://localhost:11438
```

---

## Minimal `.env` for Development

```bash
TINA4_DEBUG=true
TINA4_LOG_LEVEL=DEBUG
TINA4_NO_BROWSER=true
```

That is it. Debug mode lights up the Swagger UI, the dev dashboard, detailed error pages, and live reload. Keeping the browser flag on stops a new tab opening every time you save a file.

---

## Minimal `.env` for Production

```bash
TINA4_SECRET=your-long-random-secret-here
TINA4_DATABASE_URL=postgresql://user:password@db-host:5432/myapp
TINA4_CORS_ORIGINS=https://myapp.com,https://www.myapp.com
TINA4_HSTS=31536000
TINA4_MAIL_HOST=smtp.example.com
TINA4_MAIL_PORT=587
TINA4_MAIL_USERNAME=noreply@myapp.com
TINA4_MAIL_PASSWORD=your-smtp-password
TINA4_MAIL_FROM=noreply@myapp.com
```

No `TINA4_DEBUG`. It defaults to `false`, which is what you want in production. Set a real secret, a real database, locked-down CORS origins, HSTS, and SMTP credentials if you send email. Everything else has a production-appropriate default.
