Validation at startup
Learn how to check every config field once before the server starts, with a clear message for each failure, so a bad setting stops startup instead of breaking the first request
Validation at startup is the habit of checking every field of AppConfig once, in one method, before the server does anything else. The loader already reads the values and turns them into typed fields. Validation goes one step further: it asks whether the values make sense. Is the database address shaped like a Postgres address? Is the log filter a filter the logging library can parse? Is the port a real port? Is the secret long enough to be a secret? A value that fails any of those checks stops the program at startup, with a message naming the field and the problem, and the server never binds, never connects, and never serves a request with a bad setting.
Where This Fits
The struct page built the loader, and the four field pages each taught one setting and what it is used for. This page adds the check that runs after loading and before serving. The loader's job is to read values and turn them into types. The validator's job is to judge values. That split is what keeps both functions small: the loader never decides whether a value is good, and the validator never reads the environment. One method, named validate, holds every check, and from_env calls it as its last step, so no AppConfig can exist in the program without having passed every check.
Think of a pilot's pre-flight checklist. Reading the fuel gauge is loading. Checking that the fuel is enough for the flight is validation. A gauge that reads zero is a fact, and the decision that zero is not enough is a separate step, done before takeoff, not discovered halfway to the destination.
The Smallest Working Version
Start with the struct, the loader, and a validate method that checks all four fields. The method returns a Result, so the loader can return the first problem it finds as the error.
use std::net::SocketAddr;
#[derive(Clone)]
pub struct AppConfig {
pub database_url: String,
pub listen_address: SocketAddr,
pub rust_log: String,
pub jwt_secret: String,
}
impl AppConfig {
pub fn from_env() -> Result<AppConfig, String> {
let database_url = std::env::var("DATABASE_URL").map_err(|_| {
"DATABASE_URL must be set, for example \
postgres://axumdocs:axumdocs@127.0.0.1:5432/ch21_config"
.to_string()
})?;
let listen_address = std::env::var("LISTEN_ADDRESS")
.unwrap_or_else(|_| "127.0.0.1:3000".to_string())
.parse::<SocketAddr>()
.map_err(|_| {
"LISTEN_ADDRESS must be an address like 127.0.0.1:3000".to_string()
})?;
let rust_log = std::env::var("RUST_LOG").unwrap_or_else(|_| "info".to_string());
let jwt_secret =
std::env::var("JWT_SECRET").map_err(|_| "JWT_SECRET must be set".to_string())?;
let config = AppConfig {
database_url,
listen_address,
rust_log,
jwt_secret,
};
config.validate()?;
Ok(config)
}
pub fn validate(&self) -> Result<(), String> {
if self.database_url.trim().is_empty() {
return Err("DATABASE_URL must not be empty".to_string());
}
if !self.database_url.starts_with("postgres://") {
return Err("DATABASE_URL must start with postgres://".to_string());
}
if self.rust_log.trim().is_empty() {
return Err("RUST_LOG must not be empty".to_string());
}
if tracing_subscriber::EnvFilter::try_new(&self.rust_log).is_err() {
return Err(format!("RUST_LOG {:?} is not a valid log filter", self.rust_log));
}
if self.listen_address.port() == 0 {
return Err("LISTEN_ADDRESS must not use port 0".to_string());
}
if self.jwt_secret.len() < 32 {
return Err("JWT_SECRET must be at least 32 characters long".to_string());
}
Ok(())
}
}
The one new line in from_env is config.validate()?;, placed after the struct is built and before it is returned. The ? returns the first validation error as the loader's error, so main prints it and stops with exit code 1, exactly as it already does for a missing variable. Nothing in main changes: the same match handles both kinds of failure, because both are String errors from the same function.
use axum_project::config::AppConfig;
#[tokio::main]
async fn main() {
let _ = dotenvy::dotenv();
let config = match AppConfig::from_env() {
Ok(config) => config,
Err(error) => {
eprintln!("Configuration error: {error}");
std::process::exit(1);
}
};
println!("Configuration is valid");
}
Run it with a short secret, and the program stops before printing anything else.
$ DATABASE_URL=postgres://axumdocs:axumdocs@127.0.0.1:5432/ch21_config LISTEN_ADDRESS=127.0.0.1:3000 RUST_LOG=info JWT_SECRET=short cargo run
Configuration error: JWT_SECRET must be at least 32 characters long
Run it with a MySQL address, and the scheme check fires instead.
$ DATABASE_URL=mysql://root@127.0.0.1:3306/app LISTEN_ADDRESS=127.0.0.1:3000 RUST_LOG=info JWT_SECRET=test-secret-only-for-local-development cargo run
Configuration error: DATABASE_URL must start with postgres://
Run it with a filter string that has spaces around the equals sign, and the filter check fires.
$ DATABASE_URL=postgres://axumdocs:axumdocs@127.0.0.1:5432/ch21_config LISTEN_ADDRESS=127.0.0.1:3000 RUST_LOG="info, hyper = debug" JWT_SECRET=test-secret-only-for-local-development cargo run
Configuration error: RUST_LOG "info, hyper = debug" is not a valid log filter
All three runs were checked directly. Each one stops at startup, prints one line naming the field and the problem, and exits with code 1. No port is bound, no pool is opened, and no request is served.
Working Setup:
If a bad value produces one clear line and no server, validation works. If a good value produces the Configuration is valid line, the checks pass. The two behaviours together are the whole test: bad values fail loudly, good values pass quietly.
Understanding Each Check
The six checks fall into three kinds, and each kind catches a different class of mistake.
The emptiness checks catch values that are set but blank. std::env::var returns Ok("") for a variable set to an empty string, so a present-but-empty DATABASE_URL would sail through the loader and fail later in the pool with a confusing error. The .trim().is_empty() check catches it at load time, with a message that says the field must not be empty. The same check guards rust_log, because an empty filter string would leave the logging setup with nothing to parse.
The shape checks catch values that are present and non-empty but wrong for their job. The database URL must start with postgres://, because this program only speaks Postgres, and a MySQL address would fail in the pool with an error about the driver, far from the place where the address was set. The listen address port must not be zero, because port 0 means the operating system picks a port, and a server whose port changes on every run is a server nobody can find. The port check works because the loader already parsed the address: the field is a SocketAddr, so .port() returns the number directly, with no string splitting.
The parse check catches a log filter the logging library cannot use. EnvFilter::try_new(&self.rust_log) parses the string the same way the subscriber setup will, and .is_err() turns a parse failure into a validation error that quotes the value. The message includes the value with {:?}, the debug format, so the exact string is visible, quotes and spaces included. That matters for this check more than for the others, because the common failure is invisible whitespace: info, hyper = debug looks right at a glance, and the quoted value in the message shows the spaces that broke it.
The length check catches a secret too short to be a secret. Thirty-two characters is the floor used here, and it is a floor, not a target: longer random secrets are better, and the test secret passes it because it is 39 characters long. A secret of "short" fails at load time, which is far better than failing at the first forged token, which is where a short secret would otherwise be discovered.
Validation Checks Shape, Not Reachability:
These checks prove the values are shaped correctly. They do not prove the database answers, the port is free, or the secret matches the one that minted the existing tokens. Only the pool can prove the database answers, and only the bind call can prove the port is free. Validation catches the mistakes that can be caught without the network, and it leaves the rest to the code that actually uses the value.
Why One Method for All Checks
The alternative is to scatter the checks where each value is used: the pool checks the scheme, the logging setup checks the filter, the token code checks the secret length. That version fails late and inconsistently. A bad secret would pass startup, pass the pool, pass the bind, and fail on the first login, which is the worst moment to discover it. A bad filter would silently fall back to info in the logging setup, and the developer would never know the value they set is not the filter that runs.
One method fixes both problems. Every check runs before anything else, so the first failure stops the program at the same place, with the same shape of message, no matter which field is wrong. And the checks are easy to find: a developer who wants to know what a valid configuration looks like reads one method, not four modules. Adding a fifth field later means adding its checks to the same method, and the habit of checking everything in one place carries forward.
There is a second benefit. A method on the struct can be called on any AppConfig, including one built by hand in a test, without touching the environment. That makes the checks testable in isolation: a test constructs a struct with one bad field, calls validate, and asserts the error. No environment variables, no process-wide state, no test interference.
The Concept Behind Checking Before Serving
A server that starts with a bad setting has two bad options. It can fail on the first request that touches the setting, which means the failure is discovered by a user, at an unknown time, with an error that names the request, not the setting. Or it can run with a silent fallback, which means the failure is never discovered at all, and the program behaves differently from what its configuration says. Validation removes both options by moving the failure to the one moment when it costs nothing: startup, before any user is involved, with a message that names the field.
Beginners sometimes picture validation as extra work the program does for its own sake. A closer picture is the gate at the entrance of a building. Everyone passes through the gate once, and the gate checks the ticket before anyone is inside. Checking tickets inside the hall, one room at a time, would let people without tickets wander the corridors first. The gate is not extra work; it is the work done in the right place.
Checking in Tests Without the Environment
Because validate takes &self and returns a Result, tests can build a config by hand and check each rule directly. The helper below builds a good config and then changes one field at a time, so each test proves one check and nothing else.
use std::net::SocketAddr;
use axum_project::config::AppConfig;
fn good_config() -> AppConfig {
AppConfig {
database_url: "postgres://axumdocs:axumdocs@127.0.0.1:5432/ch21_config".to_string(),
listen_address: "127.0.0.1:3000".parse::<SocketAddr>().unwrap(),
rust_log: "info".to_string(),
jwt_secret: "test-secret-only-for-local-development".to_string(),
}
}
#[test]
fn good_config_passes() {
assert!(good_config().validate().is_ok());
}
#[test]
fn short_secret_fails() {
let mut config = good_config();
config.jwt_secret = "short".to_string();
let error = config.validate().unwrap_err();
assert!(error.contains("at least 32"), "{error}");
}
#[test]
fn mysql_scheme_fails() {
let mut config = good_config();
config.database_url = "mysql://root@127.0.0.1:3306/app".to_string();
let error = config.validate().unwrap_err();
assert!(error.contains("postgres://"), "{error}");
}
#[test]
fn filter_with_spaces_fails() {
let mut config = good_config();
config.rust_log = "info, hyper = debug".to_string();
let error = config.validate().unwrap_err();
assert!(error.contains("RUST_LOG"), "{error}");
}
#[test]
fn port_zero_fails() {
let mut config = good_config();
config.listen_address = "127.0.0.1:0".parse::<SocketAddr>().unwrap();
let error = config.validate().unwrap_err();
assert!(error.contains("port 0"), "{error}");
}
Run them with:
cargo test --test validate_test
All five pass, and none of them touches the environment. The fields are pub, so the tests can set them directly, and the struct is built with a literal, so the tests run in any order and in parallel. That is the payoff for keeping validation in a method on the struct instead of in the loader: the loader needs the environment, and the validator needs only a struct.
Reporting Every Problem at Once
The validate method above returns the first problem it finds. That is the simplest shape, and it is enough for most programs, because the operator fixes the one problem, restarts, and finds the next one if there is one. A program with many settings sometimes wants the other shape: report every problem at once, so one restart fixes all of them. The method below collects the errors into a list and returns the whole list.
impl AppConfig {
pub fn validate_all(&self) -> Result<(), Vec<String>> {
let mut errors = Vec::new();
if self.database_url.trim().is_empty() {
errors.push("DATABASE_URL must not be empty".to_string());
}
if !self.database_url.starts_with("postgres://") {
errors.push("DATABASE_URL must start with postgres://".to_string());
}
if self.rust_log.trim().is_empty() {
errors.push("RUST_LOG must not be empty".to_string());
}
if tracing_subscriber::EnvFilter::try_new(&self.rust_log).is_err() {
errors.push(format!("RUST_LOG {:?} is not a valid log filter", self.rust_log));
}
if self.listen_address.port() == 0 {
errors.push("LISTEN_ADDRESS must not use port 0".to_string());
}
if self.jwt_secret.len() < 32 {
errors.push("JWT_SECRET must be at least 32 characters long".to_string());
}
if errors.is_empty() {
Ok(())
} else {
Err(errors)
}
}
}
The checks are the same, and only the shape of the result changes: a list of strings instead of one string. main prints each one on its own line when it fails.
let config = match AppConfig::from_env() {
Ok(config) => config,
Err(error) => {
eprintln!("Configuration error: {error}");
std::process::exit(1);
}
};
That main works with the first-error form. For the collect-all form, the loader returns Result<AppConfig, Vec<String>> instead, and main loops over the list. A config with both a MySQL address and a short secret then reports both problems in one run, which was checked directly: the list held two errors, one naming the scheme and one naming the length. Use the first-error form while the struct is small, and reach for the list form when the struct grows enough that fixing one error at a time becomes slow.
How Validation Fits in Startup
Validation sits between loading and using, and it is the gate that nothing passes without clearing.
dotenvy::dotenv() loads the .env file
|
v
from_env reads four variables into AppConfig
|
v
validate checks every field once
|
v
valid: pool, logging, bind, serve
|
v
invalid: one clear message, exit code 1, nothing starts
A failure before the gate is a loading failure: a missing variable or an unparsable address. A failure at the gate is a validation failure: a present value with the wrong shape. A failure after the gate is a runtime failure: a database that does not answer or a port that is taken. The three kinds fail in different places with different messages, and the gate is what keeps them apart.
Common Beginner Mistakes
Validating where the value is used
// Wrong - the secret is checked on the first login, long after startup
async fn login(State(config): State<AppConfig>) -> String {
if config.jwt_secret.len() < 32 {
panic!("JWT_SECRET is too short");
}
create_token(1, "user", &config.jwt_secret).unwrap()
}
A check inside a handler runs only when that handler runs, so a bad secret sits unnoticed until a user logs in. The fix is the validate method, called in from_env, so the check runs before any request exists.
Checking only some fields
// Wrong - the database URL and the secret are checked, the rest are not
pub fn validate(&self) -> Result<(), String> {
if self.jwt_secret.len() < 32 {
return Err("JWT_SECRET must be at least 32 characters long".to_string());
}
Ok(())
}
A partial validator gives false confidence: the program starts, and then the unchecked field fails later. The fix is one check per field, in the same method, so the method's name means what it says.
An error message that does not name the field
// Wrong - the operator cannot tell which value is bad
return Err("configuration is invalid".to_string());
A message that names no field sends the operator hunting through four values to find the bad one. The fix is a message that names the field and the rule, such as DATABASE_URL must start with postgres://, so the fix is visible in the error itself.
Panicking inside validate
// Wrong - a panic inside validate hides the message in a backtrace
pub fn validate(&self) {
assert!(self.jwt_secret.len() >= 32, "secret too short");
}
A panic prints the message plus a backtrace note and a thread line, which buries the useful part. The fix is returning the error, so main prints exactly one line in its own words and stops with exit code 1.
A Passing Check Is Not a Working Server:
Validation proves the values are shaped correctly. It does not prove the database is up, the port is free, or the secret is the one that minted the live tokens. A server can pass every check and still fail to connect, and that failure belongs to the pool or the bind call, not to the validator. Do not add network checks to validate: a check that needs the network is slow, flaky, and belongs where the value is used.
Final Complete Example
Everything on this page put together is one project: the config module with the loader and the validator, the server that prints when the config is valid, and the tests that prove each check.
[package]
name = "axum-project"
version = "0.1.0"
edition = "2021"
[dependencies]
axum = "=0.8.9"
tokio = { version = "=1.54.1", features = ["full"] }
dotenvy = "=0.15.7"
tracing = "=0.1.44"
tracing-subscriber = { version = "=0.3.23", features = ["env-filter"] }
[dev-dependencies]
tower = { version = "0.5", features = ["util"] }
DATABASE_URL=postgres://axumdocs:axumdocs@127.0.0.1:5432/ch21_config
LISTEN_ADDRESS=127.0.0.1:3000
RUST_LOG=info
JWT_SECRET=test-secret-only-for-local-development
use std::net::SocketAddr;
#[derive(Clone)]
pub struct AppConfig {
pub database_url: String,
pub listen_address: SocketAddr,
pub rust_log: String,
pub jwt_secret: String,
}
impl AppConfig {
pub fn from_env() -> Result<AppConfig, String> {
let database_url = std::env::var("DATABASE_URL").map_err(|_| {
"DATABASE_URL must be set, for example \
postgres://axumdocs:axumdocs@127.0.0.1:5432/ch21_config"
.to_string()
})?;
let listen_address = std::env::var("LISTEN_ADDRESS")
.unwrap_or_else(|_| "127.0.0.1:3000".to_string())
.parse::<SocketAddr>()
.map_err(|_| {
"LISTEN_ADDRESS must be an address like 127.0.0.1:3000".to_string()
})?;
let rust_log = std::env::var("RUST_LOG").unwrap_or_else(|_| "info".to_string());
let jwt_secret =
std::env::var("JWT_SECRET").map_err(|_| "JWT_SECRET must be set".to_string())?;
let config = AppConfig {
database_url,
listen_address,
rust_log,
jwt_secret,
};
config.validate()?;
Ok(config)
}
pub fn validate(&self) -> Result<(), String> {
if self.database_url.trim().is_empty() {
return Err("DATABASE_URL must not be empty".to_string());
}
if !self.database_url.starts_with("postgres://") {
return Err("DATABASE_URL must start with postgres://".to_string());
}
if self.rust_log.trim().is_empty() {
return Err("RUST_LOG must not be empty".to_string());
}
if tracing_subscriber::EnvFilter::try_new(&self.rust_log).is_err() {
return Err(format!("RUST_LOG {:?} is not a valid log filter", self.rust_log));
}
if self.listen_address.port() == 0 {
return Err("LISTEN_ADDRESS must not use port 0".to_string());
}
if self.jwt_secret.len() < 32 {
return Err("JWT_SECRET must be at least 32 characters long".to_string());
}
Ok(())
}
}
pub mod config;
use axum_project::config::AppConfig;
#[tokio::main]
async fn main() {
let _ = dotenvy::dotenv();
let config = match AppConfig::from_env() {
Ok(config) => config,
Err(error) => {
eprintln!("Configuration error: {error}");
std::process::exit(1);
}
};
println!("Configuration is valid");
let _ = config;
}
Run the checks with these commands:
cargo check
cargo test --test validate_test
cargo run
Then break one value at a time and watch the message change: a short secret, a MySQL address, a filter with spaces. Each one stops the program before anything starts, and each message names the field to fix.
Summary
Validation is the gate between loading and serving, and its value is measured in when failures happen, not in how many checks it holds. A bad value caught at startup costs one restart and one line of output. The same value caught on the first request costs a user-facing failure, a confusing error, and a search through the code for the place the value was set. The checks themselves are small, one rule per field, and the discipline is in where they live: one method, called once, before anything else.
The decision framework for adding a check is short. If the rule can be decided from the value alone, without the network, it belongs in validate. If the rule needs the network, such as whether the database answers, it belongs where the value is used. And if the rule is about whether the value exists at all, it belongs in the loader, where the read happens. With those three homes, every failure has one place to live, and the operator reading the message always knows which one to fix.