Skip to content
NestRS

Configuration

Typed, namespaced configuration loaded from environment variables — each field read under its own name, validated on the way in.

Configuration in nestrs is a typed struct, one file per concern, each field read from the <PREFIX>_<NAMESPACE>__<FIELD> environment variable its name spells. #[config] writes that mapping from the struct, the framework loads it once at boot, validates it, and registers Arc<MyConfig> into the container the moment a provider asks for it. Consumers inject it like any other provider.

The whole pipeline reads from environment variables and a small .env cascade the framework merges before any config is read. No TOML loader, no YAML, no remote source baked in — but a ConfigSource trait lets you ship one when you need Vault, K8s, or AWS Parameter Store.

Terminal window
cargo add nest-rs --features config

#[config] carries the Validate derive itself, so a config struct needs no validator entry and no version to keep aligned with the framework’s; a custom rule names its error through nest_rs::pipes::validator.

The common case is three short blocks: a range for what is bounded, the #[config] struct and its Default.

crates/features/src/posts/config.rs
use std::time::Duration;
use nest_rs::config::{Bound, CountBounds, DurationBounds, Floor, config};
const CACHE_TTL: DurationBounds = DurationBounds::secs(
Floor::Units(Bound::new(1, "a shorter lifetime caches nothing")),
Bound::new(3600, "past an hour a post edited meanwhile is served stale"),
);
const PAGE_SIZE: CountBounds = CountBounds::new(
Bound::new(1, "an empty page lists nothing"),
Bound::new(500, "past it one request reads more than a page is for"),
);
#[config(namespace = "posts")]
#[derive(Clone)]
pub struct PostsConfig {
#[config(bounds = PAGE_SIZE)]
pub page_size: u32,
#[validate(length(max = 20))]
pub featured_tags: Vec<String>,
#[config(bounds = CACHE_TTL)]
pub cache_ttl: Option<Duration>,
}
impl Default for PostsConfig {
fn default() -> Self {
Self {
page_size: 50,
featured_tags: Vec::new(),
cache_ttl: Some(Duration::from_secs(60)),
}
}
}

Three pieces do the heavy lifting:

  • #[config(namespace = "posts")] binds the struct to the <PREFIX>_POSTS__* scheme, and writes the mapping: page_size reads <PREFIX>_POSTS__PAGE_SIZE, featured_tags the comma-separated <PREFIX>_POSTS__FEATURED_TAGS, each field its own name in SCREAMING_SNAKE. The struct is the whole contract — a reviewer reading this file knows which variables exist and of which type — and no field can be reachable from code alone. A namespace belongs to one struct: a second #[config] declaring it fails the boot naming both, so a variable always names the one type that reads it.
  • impl Default is what a field keeps when its variable is unset and nothing is pinned at the call site. Defaults live here and nowhere else.
  • #[validate(...)] attributes run after the load — #[config] carries the Validate derive itself. A failure aborts boot naming the field. A rule the derive cannot express is the one case for a hand-written impl Validate — see Advanced configuration.

The field’s type chooses its reader. A number, a string, a path, an address or a UUID parses as itself, a bool accepts the usual spellings (1/true/yes/on and their negatives), an Option keeps its base when the variable is unset, a Vec reads a comma-separated list, a nest_rs::core::Secret holds what it reads out of every log, and a nest_rs::config::Surface, what a development run opens, reads a boolean as open or closed. A value that does not read fails the boot naming the variable, never quoting it — no silent fallback. A type of your own implements nest_rs::config::FromSetting, three lines saying what a refused value was expected to be.

A field says what its type cannot, with its own #[config(…)]:

Key Reads
bounds = RANGE A Duration, or an Option<Duration> whose None turns it off, held to the DurationBounds named — its variable the field’s name with the unit after it (CACHE_TTL_SECS) — or a usize, a u32 or an Option<usize> whose None is no limit, held to a CountBounds; bound to the field as PostsConfig::CACHE_TTL, the one place a sentence or a check reads its key and path
json A structured value — a list of records, a map — written as JSON
with = path Through a function of yours, fn(&ConfigService, Field, T) -> Result<T>, handed the field — its key and the path code pins it through, bound to the struct the way a range is — and its base

Every field is bound to the struct, as the associated constant named for it: a BoundedSetting for a bounded one (PostsConfig::CACHE_TTL), a nest_rs::config::Field for any other (PostsConfig::FEATURED_TAGS), its key() and its path(), and var(namespace) for the variable whole. A sentence naming a field reads them, so no sentence types a key or a path, and renaming the field moves them all. A constant of your own by that name is a compile error: rename it.

A duration is a Duration; None is off and nothing else. A field never names its unit — the key does, through its bounds — and its default sits in Default, never behind a None the code would read as “the default”. A field named ttl_secs, or a Duration with no bounds, is a compile error saying so. Whether 0 turns it off is the field’s type alone: an Option<Duration> reads 0 as None and refuses a pinned zero, a Duration holds 0 to the floor, so one range serves both. A count follows the same rule, on a CountBounds: a plain number with its default in Default, or an Option<usize> whose None is no limit, 0 from the environment and a pinned Some(0) refused.

Every field a module’s config exposes is reachable two ways — pinned in code through Module::for_root(cfg), and from the <PREFIX>_<NS>__<FIELD> variable its name spells — and the two compose per field, the real environment overlaying a pin. Pinning a config is the precedence chain and the one seam each module offers.

A consumer injects Arc<PostsConfig> like any provider — the type is the token, and the injection is the whole wiring: the boot sees a provider of an imported module asking for a #[config] and loads it, environment over Default, before anything is built.

crates/features/src/posts/service.rs
use std::sync::Arc;
use nest_rs::core::injectable;
use nest_rs::seaorm::ServiceError;
use super::config::PostsConfig;
use super::entity::Post;
#[injectable]
pub struct PostsService {
#[inject]
config: Arc<PostsConfig>,
}
impl PostsService {
pub async fn list(&self) -> Result<Vec<Post>, ServiceError> {
let page = self.config.page_size;
// ...
}
}
crates/features/src/posts/module.rs
use nest_rs::core::module;
use super::service::PostsService;
#[module(providers = [PostsService])]
pub struct PostsModule;
apps/api/src/module.rs
use nest_rs::core::module;
use features::posts::PostsHttpModule;
#[module(
imports = [
PostsHttpModule,
],
)]
pub struct ApiModule;
  • The injection loads the config. Once every module has collected, the boot queues a factory for each #[config] a provider of an imported module requires, unless a for_root pinned it already. The factory reads every field over C::default(), then validates; on failure the boot aborts with the variable named. A config only an unimported module asks for is never read, and a test that seeds the config (App::builder().provide(cfg)) wins over the factory.
  • The first config the boot loads registers Arc<Environment> — the active profile, read from <PREFIX>_ENV — so a provider can inject it and branch, with no import of its own, and a test overrides it like any provider (App::builder().override_value(Environment::Test)); a process that declares none says so once, at info. It writes nothing to the process environment. What puts the .env cascade in the process environment is #[nest_rs::main], before your main runs; see alternative sources.

A bad value fails the boot before any port opens, and the first line names the variable you set:

Terminal window
$ NESTRS_POSTS__PAGE_SIZE=lots nestrs run dev api
Error: invalid value for NESTRS_POSTS__PAGE_SIZE: does not parse as u32

A violated #[validate] rule aborts the same way after the load, naming each field with the variable that sets it — the value may come from a for_root pin as well, so both are there.

A line per variable written by hand looks explicit, but it is a second copy of the struct: a forgotten line leaves a field settable from code alone, and a key retyped apart from its field renames the variable without a word. Reading each key off its field keeps the contract where the fields are:

  • The full env contract of a feature is one struct, in one file — the field’s name is the variable, its type the reader.
  • A missing variable falls back to the base — the pinned value, or the config’s own Default — for every field alike.
  • An unreadable value fails loudly, naming the variable, never quoting it.
  • What a type cannot say is said on the field, in one of three keys, and a config whose fields depend on each other, or a generic config, whose bounds the derive does not write, writes its overlay itself — Advanced configuration.

It is no serde deserializer over the environment either: that would read neither a <KEY>_FILE secret, nor the tiers a pin narrows, and its errors quote the value they refuse.

NESTRS is a default: NESTRS_ENV_PREFIX=ACME, set on the process, renames every framework variable — ACME_HTTP__PORT, ACME_SEAORM__URL. Each value may come from a file (<PREFIX>_<NS>__KEY_FILE), and is refused without being quoted: Variables is how a name is built and a value read.

A reader of your own (with = path), a rule spanning the whole struct and a hand-written overlay (from_env = "manual") are covered on Advanced configuration, with the real OAuthServerConfig as the worked example; what a development run opens, a Surface, on Development surfaces.

  • Pinning a config — the dual-path rule, the precedence chain, and for_root, the one seam a module offers.
  • Variables — your own prefix, how a namespace is named, and how ConfigService reads a value.
  • The .env cascade — which files load, in what order, and how the active Environment selects them.
  • crates/features/src/sign_in/config.rs — a product config whose overlay is derived and whose validation is written by hand.
  • crates/nest-rs-config/ — #[config], Config, ConfigService, ConfigModule, the .env cascade.
  • Modules — where for_root(...) sits in a composition root.
  • HTTP configuration — the largest config struct the framework ships, dual-path like every other.
  • CLI — nestrs run loads the cascade before it starts an app.