Skip to content
NestRS

Advanced configuration

When a field's type cannot say how it reads — a reader of your own, a rule spanning the whole struct, a hand-written overlay.

#[config] reads each field by its type, and a field’s own #[config(…)] covers a duration, a JSON value and a count. Three things push a config past them: a field whose reading only you can judge, a rule spanning the whole struct, and an overlay whose fields depend on each other — or a config generic over a type the app fills, which no derive can bound.

A field whose value is refused on a rule its type does not know names the function that reads it, with = path. The function is handed the reader, the field — field.key(), the key its name spells, and field.path(), the path code pins it through — and its base, the value pinned in code or the default, and answers the field. The throttler’s pseudonym key is one: a key shorter than HMAC’s own length is refused, from the environment or pinned in code alike, and never shown.

nest_rs::throttler::ThrottlerConfig (abridged)
#[config(namespace = "throttler")]
#[derive(Clone, Debug)]
pub struct ThrottlerConfig {
#[config(bounds = LIMIT)]
pub limit: u32,
#[config(bounds = WINDOW)]
pub window: Duration,
#[config(with = pseudonym_key)]
pub pseudonym_key: Option<Secret<String>>,
}
fn pseudonym_key(
env: &ConfigService,
field: Field,
base: Option<Secret<String>>,
) -> Result<Option<Secret<String>>> {
match env.setting(field.key())? {
Some(setting) if setting.value.len() < MIN_KEY_BYTES => Err(setting.refuse(SHORT_KEY)),
Some(setting) => Ok(Some(Secret::new(setting.value))),
None => match base {
Some(pinned) if pinned.expose_secret().len() < MIN_KEY_BYTES => {
Err(ConfigError::parse(
env.var_name(field.key()),
format!("`{}` set in code {SHORT_KEY}", field.path()),
))
}
pinned => Ok(pinned),
},
}
}

env.setting(field.key()) keeps which spelling the deployment used — the variable or its _FILE — so setting.refuse(reason) names that one, and reason says what was expected, never the value; a value set in code is refused naming field.path(), which the derive read off the struct. The derive binds that Field to the struct as well, ThrottlerConfig::PSEUDONYM_KEY, so a check of a value built in code outside the reader names the same key and path without typing either.

A rule spanning the whole struct, on a generic config

Section titled “A rule spanning the whole struct, on a generic config”

OAuthServerConfig<P> — the clients an authorization server registers, which the demo’s apps/auth issues tokens to — is generic over the payload each client carries, so it writes its overlay itself (from_env = "manual"), and its rules span every client, so it writes its Validate too (validate = "manual"). Its namespace is read off its path, as every config’s is: nest-rs-oauth-server/src/config.rs reads <PREFIX>_OAUTH__SERVER__*.

nest_rs::oauth::server::OAuthServerConfig (abridged)
#[config(namespace = "oauth__server", validate = "manual", from_env = "manual")]
#[derive(Clone, Debug)]
pub struct OAuthServerConfig<P> {
pub clients: Vec<RegisteredClient<P>>,
}
impl<P: DeserializeOwned + Clone + Send + Sync + 'static> Config for OAuthServerConfig<P> {
fn from_env(env: &ConfigService, base: Self) -> nest_rs_config::Result<Self> {
Ok(Self {
clients: env.json(Self::CLIENTS.key())?.unwrap_or(base.clients),
})
}
}
impl<P> Validate for OAuthServerConfig<P> {
fn validate(&self) -> Result<(), ValidationErrors> {
let mut errors = ValidationErrors::new();
if self.clients.is_empty() {
errors.add("clients", ValidationError::new("at_least_one_client"));
}
let mut seen = HashSet::new();
for client in &self.clients {
let mut refuse = |field: &str, code: &'static str| {
errors.errors_mut().insert(
format!("clients[{}].{field}", client.client_id).into(),
ValidationErrorsKind::Field(vec![ValidationError::new(code)]),
);
};
if client.client_id.is_empty() {
refuse("client_id", "required");
} else if !seen.insert(client.client_id.as_str()) {
refuse("client_id", "duplicate");
}
// … an empty secret, a client registered for no resource
}
errors.is_empty().ok_or(errors)
}
}
  • base supplies the fallback, even for the structured field. An unset <PREFIX>_OAUTH__SERVER__CLIENTS keeps base.clients rather than resetting to an empty list, so a registry a for_root pinned in code survives a deployment that sets nothing.
  • clients is a JSON array in a single variable. env.json(Self::CLIENTS.key()) decodes it as the field’s type, inline or through <PREFIX>_OAUTH__SERVER__CLIENTS_FILE — what #[config(json)] reads on a config that is not generic — and a value that does not decode fails the boot with ConfigError::Decode, naming whichever spelling was set, where the value failed, the kind of value found and the type expected — never the value, since a mistyped list of clients holds their secrets. Decoding it with serde_json in the overlay would quote it back. The element is RegisteredClient<P>; the app fills the generic payload — the demo’s ClientPayload, the org each client acts as and its roles — so the framework owns the credential shape and the app owns only what it authorizes on.
  • “At least one client” and “no id twice” are struct-level rules, so impl Validate is written by hand, building the same ValidationErrors the derive would, each named through nest_rs::pipes::validator. They run after the load and abort the boot exactly like a derived rule, naming each refusal by the client’s id, never its secret.

The app imports its module with the payload type it owns; SignInService injects its own SignInConfig, which that injection loads:

crates/features/src/sign_in/module.rs (from the demo)
use nest_rs::core::module;
use nest_rs::oauth::server::OAuthServerModule;
use nest_rs::social::SocialModule;
use super::config::ClientPayload;
use super::service::SignInService;
use crate::users::UsersModule;
#[module(
imports = [
nest_rs::authn::AuthnModule,
OAuthServerModule::<ClientPayload>,
UsersModule,
SocialModule,
],
providers = [SignInService],
)]
pub struct SignInModule;

SignInConfig is the product’s own — the resources a sign-in may ask for, the org a first social sign-in joins and the client its tokens are issued to — read from <PREFIX>_SIGN_IN__*, the feature’s own word: a product stem never takes a family’s (oauth), whose first level is the framework members’. Its overlay is derived, and its rules are #[validate] lines:

crates/features/src/sign_in/config.rs (from the demo, abridged)
#[config(namespace = "sign_in")]
#[derive(Clone)]
pub struct SignInConfig {
#[validate(length(min = 1, code = "at_least_one_resource"))]
pub resources: Vec<String>,
pub default_org_id: Uuid,
#[validate(length(min = 1, code = "required"))]
pub client_id: String,
}
Terminal window
$ NESTRS_OAUTH__SERVER__CLIENTS='[{"client_id":"web","client_secret":"...","payload":{"org_id":"00000000-0000-0000-0000-000000000000","roles":["user"]},"scopes":["posts:read"],"resources":["http://localhost:3003"]}]' \
nestrs run dev auth
2026-06-03T10:42:11Z INFO nest_rs::routes: mounted host="SignInController" method="token" verb="POST" path="/token"

A bad value fails the boot before any port opens, naming the variable:

Terminal window
$ NESTRS_SIGN_IN__DEFAULT_ORG_ID=not-a-uuid nestrs run dev auth
Error: invalid value for NESTRS_SIGN_IN__DEFAULT_ORG_ID: is not a UUID

A failed validation runs after the load, each field beside the variable that sets it — for anything inside a field read whole as JSON, that field’s own:

Terminal window
$ nestrs run dev auth # no clients configured
Error: configuration validation failed for `NESTRS_OAUTH__SERVER__*`
- clients (NESTRS_OAUTH__SERVER__CLIENTS): at_least_one_client

What only the product knows — a registered scope outside the set its rules gate on, a client id a UUID parses, which would read as a user — it refuses from its service’s module-init hook, in the same words:

Terminal window
$ NESTRS_OAUTH__SERVER__CLIENTS='[{"client_id":"web",…,"scopes":["admin"]}]' nestrs run dev auth
Error: …
configuration validation failed for `NESTRS_OAUTH__SERVER__*`
- clients[web].scopes (NESTRS_OAUTH__SERVER__CLIENTS): unknown_scope

A refusal line says the field and the rule’s code, never the rule’s parameters, so it names the client and not the accepted set. That set is authz::constants::ALL — posts:read, posts:write and audio:transcode, the scopes the app’s rules gate on — and the demo’s apps/auth/.env.development lists it beside the variable.