# Configuration and Settings

The most important runtime settings, accepted host and CSRF origin entries, startup validation, and how they shape development and production behavior.

Source: https://flasgo.dev/reference/configuration-and-settings/

Flasgo applications are configured through the `Settings` dataclass. You can pass a mapping, settings object, importable settings module, or an existing `Settings` instance to the app; unknown keys are retained for application-specific use.

## Common settings

| Setting | Default | Typical use |
| --- | --- | --- |
| `DEBUG` | `False` | Enables debug-mode behavior and controls default CLI reload |
| `SECRET_KEY` | Random URL-safe token | Signs sessions and other sensitive values |
| `ALLOWED_HOSTS` | `{"127.0.0.1", "localhost"}` | Restricts valid host headers to listed hostnames, IP addresses, or `.suffix` patterns |
| `ENFORCE_ALLOWED_HOSTS` | `True` | Enables host-header rejection |
| `CSRF_ENABLED` | `True` | Controls CSRF enforcement for unsafe methods |
| `CSRF_COOKIE_NAME` | `"flasgo-csrf"` | Sets the CSRF cookie name |
| `CSRF_HEADER_NAME` | `"x-csrf-token"` | Sets the header used for the double-submit token |
| `CSRF_TRUSTED_ORIGINS` | `set()` | Trusts exact origins, `https://*.example.com` wildcards, bare hosts, or `.suffix` patterns for unsafe requests |
| `CSRF_CHECK_ORIGIN` | `True` | Requires Origin/Referer validation for unsafe methods |
| `CSRF_REQUIRE_ORIGIN` | `True` | Rejects unsafe requests that omit Origin and Referer |
| `CSRF_COOKIE_SECURE` | `True` | Restricts CSRF cookies to HTTPS |
| `SESSION_COOKIE_NAME` | `"flasgo-session"` | Sets the session cookie name |
| `SESSION_COOKIE_MAX_AGE` | `604800` | Sets session lifetime as a positive integer number of seconds |
| `SESSION_COOKIE_SECURE` | `True` | Restricts session cookies to HTTPS |
| `SESSION_COOKIE_HTTP_ONLY` | `True` | Prevents client-side JavaScript access to session cookies |
| `SESSION_COOKIE_SAME_SITE` | `"Lax"` | Sets the session cookie SameSite value |
| `ENFORCE_NO_STORE_CACHE` | `True` | Forces no-store cache headers unless a response allows public cache |
| `MAX_REQUEST_BODY_BYTES` | `1048576` | Caps request body size |
| `MAX_REQUEST_HEAD_BYTES` | `16384` | Caps the HTTP/WebSocket request head before tracing, routing, or session loading |
| `REQUEST_READ_TIMEOUT_SECONDS` | `10.0` | Bounds request body read time |
| `MAX_MULTIPART_PARTS` | `1000` | Caps multipart parts before full parsing |
| `MAX_FORM_FIELDS` | `1000` | Caps query, URL-encoded, and multipart text fields |
| `MAX_VALIDATION_DEPTH` | `64` | Caps recursive request and response model/collection depth |
| `MAX_VALIDATION_WORK` | `10000` | Caps validation work separately for request binding and response contracts |
| `MAX_VALIDATION_ISSUES` | `100` | Caps collected validation issues; rejected output is not returned to clients |
| `SECURITY_FAILURE_RATE_LIMIT` | `50` | Caps repeated host, CSRF, and authentication/authorization failures per client window |
| `SECURITY_FAILURE_WINDOW_SECONDS` | `60` | Sets the security-failure rate-limit window |
| `LOG_SECURITY_EVENTS` | `True` | Logs security denials and unexpected failures |
| `TRUST_INCOMING_REQUEST_ID` | `False` | Accepts a strictly validated upstream `x-request-id` when a trusted proxy overwrites it |
| `LOG_FORMAT` | `"text"` | Selects bounded text or JSON framework logs |
| `LOG_LEVEL` | `"INFO"` | Sets the `flasgo` logger level; standard level names are case-insensitive |
| `WEBSOCKET_ENFORCE_ORIGIN` | `True` | Enforces same-origin or exact allowlist WebSocket handshakes |
| `WEBSOCKET_ALLOWED_ORIGINS` | `set()` | Allows exact cross-origin WebSocket origins |
| `WEBSOCKET_ALLOW_MISSING_ORIGIN` | `False` | Permits missing WebSocket origins for deliberate non-browser clients |
| `WEBSOCKET_MAX_MESSAGE_BYTES` | `65536` | Caps each WebSocket message |
| `WEBSOCKET_MAX_MESSAGES_PER_MINUTE` | `120` | Caps messages per connection and minute |
| `SERVER_LIMIT_CONCURRENCY` | `1000` | Bounds concurrent work in the built-in server |
| `METRICS_ENABLED` | `False` | Enables the optional protected Prometheus endpoint |
| `METRICS_PATH` | `"/metrics"` | Sets the metrics endpoint path |
| `METRICS_BEARER_TOKEN` | `None` | Authenticates metrics scrapes; at least 32 characters when enabled |
| `METRICS_EVENT_LOOP_ENABLED` | `True` | Samples event-loop lag after lifespan startup when metrics are enabled |
| `METRICS_EVENT_LOOP_INTERVAL_SECONDS` | `0.1` | Sets the lag sampling interval; finite numeric values from `0.01` through `60` |
| `OTEL_ENABLED` | `False` | Enables optional HTTP and WebSocket tracing |
| `OTEL_SERVICE_NAME` | `"flasgo"` | Sets the OpenTelemetry service name |
| `OTEL_SERVICE_VERSION` | `None` | Adds the deployed service version to telemetry resources |
| `OTEL_TRACE_SAMPLE_RATIO` | `1.0` | Sets the parent-based trace sampling ratio from `0.0` to `1.0` |
| `OTEL_EXCLUDED_PATHS` | `set()` | Excludes exact paths or route templates from tracing |
| `OTEL_SET_GLOBAL_PROVIDER` | `True` | Registers a Flasgo-built tracer provider as process-global |
| `ENABLE_DOCS` | `False` | Enables the built-in Swagger UI and OpenAPI JSON endpoints |
| `DOCS_AUTH_BACKEND` | `None` | Protects both documentation endpoints with a registered auth backend |
| `DOCS_PATH` | `"/docs"` | Controls the Swagger UI path |
| `OPENAPI_PATH` | `"/openapi.json"` | Controls the OpenAPI JSON path |
| `API_TITLE` | `"Flasgo API"` | Sets the OpenAPI title |
| `API_VERSION` | `"0.11.0"` | Sets the OpenAPI info version; use your application's own version when appropriate |
| `API_DESCRIPTION` | `""` | Sets the OpenAPI description |
| `API_SERVERS` | `[]` | Declares root OpenAPI server URLs |
| `SSRF_ENABLED` | `True` | Enables outbound URL validation helpers |
| `SSRF_ALLOWED_SCHEMES` | `{"http", "https"}` | Limits outbound URL schemes |
| `SSRF_ALLOWED_HOSTS` | `set()` | Optionally restricts outbound URL hosts |
| `SSRF_ALLOW_PRIVATE_NETWORKS` | `False` | Allows private-network outbound targets when explicitly needed |
| `SSRF_ALLOW_USERINFO` | `False` | Allows outbound URLs containing credentials |
| `SSRF_ALLOW_UNRESOLVABLE_HOSTS` | `False` | Allows unresolved outbound hosts |
| `SSRF_RESOLUTION_TIMEOUT_SECONDS` | `5.0` | Bounds async outbound DNS resolution; `None` disables the timeout |
| `SECURITY_HEADERS` | Secure header map | Sets response headers applied by default |

`DOCS_PATH`, `OPENAPI_PATH`, `METRICS_PATH`, and `OTEL_EXCLUDED_PATHS` are matched against the path relative to the application's mount point. When an ASGI server sets a `root_path`, do not include that prefix in these settings; see [Mounted applications](/guides/blueprints-and-url-generation/#mounted-applications).

CORS is configured with the `CORSConfig` object passed to `Flasgo(cors=...)` or an individual route's `cors=` argument rather than through `Settings`. It is disabled by default.

## Object and constructor configuration

These options are supplied as objects or constructor arguments rather than additional `Settings` keys:

| API | Configuration |
| --- | --- |
| `Flasgo(rate_limiter=...)` | Supply `RedisRateLimiter(store, max_keys=10000)` for shared route quotas |
| `Flasgo(session_backend=...)` | Supply `ServerSideSessions(store, max_bytes=65536)` for opaque-cookie sessions |
| `RedisStore.from_url(...)` | `namespace="flasgo"`, `timeout=2`, `max_value_bytes=65536`; owned pool capped at 100 connections |
| `RedisStore(client, ...)` | Wrap an application-owned client; also accepts `max_value_bytes=65536` |
| `Depends(...)` | `scope="request"` or `scope="function"`, with `use_cache=True` by default |
| HTTP routes | `public=False`, `response_model=None`, and `dependencies=()` |
| Streaming constructors | `max_chunk_bytes=65536`, `send_timeout=10`, `idle_timeout=60`, `max_duration=3600`, `cleanup_timeout=10` |
| `EventSourceResponse(...)` | Also accepts `heartbeat=15` and `item_model=` |
| `NDJSONResponse(...)` | Also accepts `item_model=` |

`SESSION_COOKIE_MAX_AGE` also controls server-side session TTL; modified saves refresh it. Ordinary response contracts use the configured validation limits, while SSE/NDJSON use independent bounded per-item validation budgets. CORS can also be configured on a blueprint, inherited when omitted, replaced explicitly, or disabled with `cors=False`.

See [Shared Quotas and Sessions](/guides/shared-storage/), [Streaming Responses](/guides/streaming-responses/), and [Response Contracts](/guides/response-contracts/) for setup, limits, and failure behavior.

## Development defaults

Local development examples keep secure behavior visible while allowing fast iteration. Typical settings include `DEBUG=True`, localhost host allowlists, and non-secure cookies for local HTTP use.

## Production baseline

Production settings should move in the opposite direction:

- `DEBUG=False`
- `SECRET_KEY` loaded from the environment
- `ALLOWED_HOSTS` set to real domains
- `SESSION_COOKIE_SECURE=True`
- `CSRF_COOKIE_SECURE=True`
- `SESSION_COOKIE_HTTP_ONLY=True`

## Example

```python
import os
from flasgo import Flasgo

app = Flasgo(
    settings={
        "DEBUG": False,
        "SECRET_KEY": os.environ["FLASGO_SECRET_KEY"],
        "ALLOWED_HOSTS": {"api.example.com"},
        "CSRF_ENABLED": True,
        "SESSION_COOKIE_SECURE": True,
        "CSRF_COOKIE_SECURE": True,
        "SESSION_COOKIE_HTTP_ONLY": True,
        "ENABLE_DOCS": False,
    }
)
```

## Loading settings

For larger apps, settings can come from an object or module with uppercase attributes:

```python
from flasgo import Flasgo

app = Flasgo(settings="myproject.settings")
```

Known framework settings populate the typed settings object. Extra keys remain available through `settings.get(key, default)` for application code; `get()` returns framework settings fields and extra keys, never methods of the `Settings` class.

Boolean fields in `Settings` and `SecurityConfig` require actual `True` or `False` values. Strings such as `"false"`, integers such as `0` or `1`, and `None` raise `TypeError` during construction, loading, or later assignment. Parse environment strings explicitly before passing them to Flasgo; Python's `bool("false")` is `True`.

`SESSION_COOKIE_NAME` and `CSRF_COOKIE_NAME` must be non-empty ASCII HTTP tokens and are validated when the application is initialized. The event-loop sampling interval rejects booleans, non-finite values, and values outside `0.01` to `60`, even when metrics are disabled. See the [Metrics Reference](/reference/metrics/) for sampler lifecycle and metric meanings.

Flasgo validates important startup settings: `SECRET_KEY` must be present and at least 32 characters in every mode; `SESSION_COOKIE_SAME_SITE` must be `Lax`, `Strict`, or `None`, with `None` requiring secure session cookies; `SESSION_COOKIE_MAX_AGE` must be a positive integer; `ALLOWED_HOSTS` and `CSRF_TRUSTED_ORIGINS` entries must use a supported form (see [Host and origin entries](#host-and-origin-entries)); request, multipart, form, validation, WebSocket, and server limits must be positive; WebSocket origins must be exact `http://` or `https://` origins; OpenTelemetry sampling must be between `0.0` and `1.0` and excluded paths must be absolute; SSRF schemes cannot be empty and the async resolution timeout must be positive or `None`; internal endpoint paths must be distinct absolute paths; and enabled metrics require a bounded bearer-safe ASCII token of at least 32 characters. `DOCS_AUTH_BACKEND` must name a registered backend when the docs endpoints are used, while every `API_SERVERS` entry must be a non-empty URL string. `LOG_FORMAT` must be `text` or `json`, and `LOG_LEVEL` must be a standard Python logging level name in any case, such as `"info"` or `"WARNING"`.

### Host and origin entries

`ALLOWED_HOSTS` accepts hostnames (`api.example.com`), IPv4 or IPv6 addresses (`127.0.0.1`, `::1`), and `.suffix` patterns (`.example.com`). A suffix pattern matches subdomains such as `api.example.com`, not the apex `example.com`; list the apex separately when it is served. Matching is case-insensitive and ignores the port. Wildcards such as `"*"` and `"*.example.com"` are rejected at startup; `"*"` never matched any host in earlier releases. Request `Host` values must be DNS names or IP literals, so URL delimiters, spaces, and bracketed IPv6 values with a zone ID are rejected, and suffix patterns never match IPv6 literals.

`CSRF_TRUSTED_ORIGINS` accepts:

| Entry | Trusts |
| --- | --- |
| `https://partner.example` | That exact scheme, host, and port |
| `https://*.example.com` | Subdomains of `example.com` over that scheme and port |
| `partner.example` | That host over the request's own scheme |
| `.example.com` | Subdomains of `example.com` over the request's own scheme |

Origins are compared in canonical form, so `https://partner.example/` and `https://partner.example:443` are the same entry. Bare host and suffix entries never let an HTTPS application trust a plain-HTTP origin. Non-HTTP(S) schemes such as `chrome-extension://`, and origins with a path, query, or credentials, raise `ValueError` at startup because they could never match.

For the typed binding model controlled by the validation limits, see [Request Data and Dependencies](/guides/request-data-and-dependencies/). For tracing behavior, see [Observability](/guides/observability/).

Sources:

- [README.md](https://github.com/L1ghtn1ng/flasgo/blob/main/README.md)
- [`flasgo/__init__.py`](https://github.com/L1ghtn1ng/flasgo/blob/main/flasgo/__init__.py)
