App Config struct

Learn how to gather every server setting into one AppConfig struct, load it once from the environment, and pass it to the rest of the program

An AppConfig struct is one plain Rust struct that holds every setting the server needs to run. It has one field per setting: the database address, the address the server listens on, the log filter, and the signing secret. The program builds it once at startup, from environment variables, and then every other part of the program reads its settings from the struct instead of reading the environment again.

Where This Fits

So far the settings have lived in scattered places. The database address was read in main, the signing secret was read inside the login handler, and the listen address was written straight into the bind call as a fixed string. Each of those reads works on its own, but together they spread the same job across three files, and a change to any setting means hunting through the code to find where it is read.

The struct gathers all of that into one place. One file defines the fields, one function loads them, and the rest of the program receives the finished struct. Think of a toolbox with one labelled drawer per tool. The tools are the same as before, but now there is exactly one place to look for each one, and nothing is left lying on the bench.

The Smallest Working Version

Start with a project that has a config module and a main that prints what it loaded. The struct has four fields, and the loader reads four environment variables.

Cargo.toml
[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"
src/config.rs
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() -> AppConfig {
        let database_url = std::env::var("DATABASE_URL")
            .expect("DATABASE_URL must be set");
        let listen_address = std::env::var("LISTEN_ADDRESS")
            .unwrap_or_else(|_| "127.0.0.1:3000".to_string())
            .parse::<SocketAddr>()
            .expect("LISTEN_ADDRESS must look like 127.0.0.1:3000");
        let rust_log = std::env::var("RUST_LOG").unwrap_or_else(|_| "info".to_string());
        let jwt_secret = std::env::var("JWT_SECRET").expect("JWT_SECRET must be set");
        AppConfig {
            database_url,
            listen_address,
            rust_log,
            jwt_secret,
        }
    }
}
src/lib.rs
pub mod config;
src/main.rs
use axum_project::config::AppConfig;

fn main() {
    let _ = dotenvy::dotenv();
    let config = AppConfig::from_env();
    println!("listening on {}", config.listen_address);
    println!("log filter is {}", config.rust_log);
    println!(
        "database URL starts with postgres: {}",
        config.database_url.starts_with("postgres://")
    );
}

The file that supplies the values in development is a .env file in the project root, with one NAME=value pair per line. The dotenvy::dotenv() call at the top of main loads that file into the environment before anything reads it, so the loader finds the values even though they were never exported in the shell.

.env
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

Run it with cargo run and the program prints the loaded settings. The database URL is never printed in full, because it holds a password, and the secret is never printed at all. Only the safe fields appear, plus a yes-or-no check on the database URL.

listening on 127.0.0.1:3000
log filter is info
database URL starts with postgres: true

Working Setup:

If those three lines appear, the whole chain works. The .env file was found, the four variables were read, the listen address parsed into a socket address, and the struct holds all four values. Every later page builds on this exact struct and this exact loader.

Keep the Env File Out of Version Control:

The .env file holds a database password and a signing secret. Add .env to .gitignore before the first commit, and never push it to a shared repository. A secret that reaches version control has to be treated as known to everyone.

Understanding the Struct Field by Field

The four fields are the four settings the server cannot run without, and each one has a type that matches how the program uses it.

The database_url field is a String, plain text, because the database address is used as text. The pool takes the whole string and connects with it, and the program never needs to pick the string apart. A String is the right shape for a value that is passed along untouched.

The listen_address field is a SocketAddr, not a String. A SocketAddr is a standard library type that holds an IP address and a port number as two separate numbers, already checked. The difference matters at the point where the server binds: TcpListener::bind takes a socket address, so a field that already is one needs no further conversion. Storing the address as text and parsing it at every use would repeat the same work and the same failure in several places. Parsing once, while loading, means the bind call later cannot fail on a bad address, because a bad address never gets into the struct.

The rust_log field is a String, because the log filter is a string of filter rules, and the logging setup takes that string as it is. The jwt_secret field is also a String, because the signing code takes the secret as bytes made from that string. Both are text in, text out, so plain strings fit.

Every field is pub, which means public: any module that holds an AppConfig can read each field by name. The struct itself is public too, so main and the handlers can name the type. The #[derive(Clone)] line gives the struct a clone method, which makes a second copy of the same settings. That matters because the config is handed to the router as shared state, and the server still needs its own copy for the bind call. Cloning a struct with four small fields is cheap.

The struct deliberately does not derive Debug. A derived Debug would print every field, including the database password and the signing secret, into any log line that prints the config. Two of these fields are secrets, so the struct has no debug printing at all for now. A safe version that hides the secrets is part of the secrets page, and until then the rule is simple: never print the whole struct.

Understanding the Loader Line by Line

The loader is the only function that touches the environment, and it runs once, at the start of main. Each line follows the same pattern with one difference: required settings stop the program when they are missing, and optional settings fall back to a safe value.

std::env::var("DATABASE_URL") reads one environment variable by name. It returns a Result, which is either the value or an error saying the variable is not set. The .expect("DATABASE_URL must be set") call turns a missing variable into a panic with that message. A panic stops the program at once, before the server starts, which is the correct outcome here: a server with no database address cannot do its job, and failing loudly at startup beats serving broken responses.

The listen address line has two extra steps. First, unwrap_or_else(|_| "127.0.0.1:3000".to_string()) supplies a default when the variable is not set. The closure, the |_| ... part, runs only in the missing case and returns the default string. Second, .parse::<SocketAddr>() turns the string into a socket address, and .expect(...) stops the program when the string is not a valid address. The default exists because the listen address is a convenience setting: the server has a sensible place to listen without any configuration, and a developer changes it only when they need a different port.

The rust_log line follows the same shape with a default of "info", because a server should log at a useful level even when nobody set the variable. The jwt_secret line is required, with no default. A signing secret must never have a fallback value written in code, because a fallback secret is a secret everyone can read, which is no secret at all. The two required fields and the two optional fields split exactly along that line: a setting with a safe default gets one, and a setting where a default would be dangerous does not.

A Default Is Only Safe When the Value Is Not a Secret:

LISTEN_ADDRESS and RUST_LOG have defaults because the worst thing a wrong default does is listen on the usual port or log at the usual level. DATABASE_URL and JWT_SECRET have no defaults because a wrong value there hands out access. If you ever add a field to this struct, ask first whether a default value could ever cause harm, and leave the field required when the answer is yes.

The Concept Behind One Struct for All Settings

A setting is a value the program needs but the code should not decide. The database address, the listen address, the log level, and the secret all change between machines and between runs, while the code stays the same. The environment is where those values live, because it belongs to the machine, not to the repository. The struct is the bridge between the two: it reads the machine's values once and gives the code one typed object to use.

The key idea is that loading happens exactly once. After from_env returns, no code reads the environment again. That single read has three effects. First, the program fails fast: a missing or malformed setting stops startup, before any request is served. Second, the program is consistent: every part sees the same values, because they all read the same struct. Third, the program is testable: a test can build an AppConfig by hand with test values and pass it to the code under test, without setting environment variables at all.

Beginners sometimes picture the struct as a bag of strings. A closer picture is a checklist filled in at the door. The program walks in, fills in every line of the checklist from the environment, and only then starts work. Nothing inside the building has to ask the door again, because the checklist travels with it.

Why a Struct Beats Reading Variables Wherever They Are Needed

The scattered version has a failure that shows up late. A handler that reads JWT_SECRET itself works fine in development, and then fails in production on the first login, because the variable was never set on that machine and nobody noticed until a user tried to log in. The struct version fails at startup, on the first line of main, with a message that names the missing variable. The failure moves from the worst possible moment to the best one.

The struct version is also easier to change. Adding a setting means adding one field, one read in the loader, and one use where it is needed. The scattered version means adding a read wherever the setting is used, and remembering every place that needs it. Removing a setting is the same story in reverse: one field disappears from the struct, and the compiler points at every use that must go with it. With scattered reads, a removed variable leaves dead reads behind, and nothing points at them.

There is a testing benefit too. A handler that reads the environment directly cannot be tested without setting process-wide variables, and tests share one process, so one test's variables leak into another's. A handler that receives the config as a value can be tested with any values the test chooses, including values that would be awkward to set in the environment, such as an invalid address or an empty secret.

A Richer Version with Honest Errors

The smallest loader panics on a missing variable, which is acceptable for learning but blunt. A panic message names the variable, and that is often enough, but the message is fixed and the program cannot distinguish one failure from another. The richer version returns a Result instead, so main can print a clear message and stop with exit code 1, the standard code that means the program failed.

src/config.rs
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())?;
        Ok(AppConfig {
            database_url,
            listen_address,
            rust_log,
            jwt_secret,
        })
    }
}

The shape is the same as before, with one change per line: .expect(...) becomes .map_err(|_| ...)?. The map_err call turns the environment error into a readable String, and the ? returns that string from the function at once, so the rest of the loader never runs with a missing value. The error type is a plain String here, which keeps the example small; a larger program would use its own error type, but the loading logic would look the same.

main now handles the Result instead of receiving a finished struct:

src/main.rs
use axum_project::config::AppConfig;

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!("listening on {}", config.listen_address);
    println!("log filter is {}", config.rust_log);
}

The match has two arms. The success arm keeps the config and carries on. The failure arm prints the message to stderr, the terminal's error stream, and stops the program with exit code 1. A script or a service manager watching the process sees that code and knows the program failed, rather than guessing from the output. Run it without the database variable set, with the .env file moved aside, and the output is exactly the message from the loader, with no server starting afterwards.

Configuration error: DATABASE_URL must be set, for example postgres://axumdocs:axumdocs@127.0.0.1:5432/ch21_config

This Result form is the version every later page builds on. The loader keeps the same fields, the same variable names, and the same defaults, and the only thing that changes from here on is what is checked inside it.

Expect or Result:

The expect form and the Result form load the same values. The expect form is shorter and fits a first example, and the Result form gives main control over the failure message and the exit code. Use the Result form in real code, because a server that fails at startup should say why in its own words, and a panic message is the compiler's words, not yours.

Passing the Config to the Server

A struct that only main can see is not useful. The rest of the program needs it too, and the way it travels is shared state. Axum state holds one value that every handler can ask for, so the config is passed to the router with with_state, and a handler receives it with the State extractor.

src/main.rs
use axum::{Json, extract::State, routing::get, Router};
use axum_project::config::AppConfig;
use serde::Serialize;

#[derive(Serialize)]
struct Status {
    listen_address: String,
    rust_log: String,
}

async fn status(State(config): State<AppConfig>) -> Json<Status> {
    Json(Status {
        listen_address: config.listen_address.to_string(),
        rust_log: config.rust_log.clone(),
    })
}

#[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);
        }
    };
    let app = Router::new()
        .route("/", get(status))
        .with_state(config.clone());
    let listener = tokio::net::TcpListener::bind(config.listen_address)
        .await
        .unwrap();
    println!("Listening on http://{}", config.listen_address);
    axum::serve(listener, app).await.unwrap();
}

The status handler takes State<AppConfig> and returns the two safe fields as JSON. It never touches the database URL or the secret, and the response type proves it: the Status struct has only the two safe fields, so there is no way for the secret to leak through this route by accident. The config.clone() in main makes the copy the router holds, while the original stays in main for the bind call. That is the one place the Clone derive earns its keep.

Run the server and request the route, and the response shows the loaded values.

curl http://127.0.0.1:3000/
{"listen_address":"127.0.0.1:3000","rust_log":"info"}

The dependencies for this version add Axum and serde, because the example now serves a route and returns JSON. The config module itself needs nothing beyond dotenvy and the standard library.

Cargo.toml
[package]
name = "axum-project"
version = "0.1.0"
edition = "2021"

[dependencies]
axum = "=0.8.9"
tokio = { version = "=1.54.1", features = ["full"] }
serde = { version = "1", features = ["derive"] }
serde_json = "1"
dotenvy = "=0.15.7"

The Order of Startup Steps

Loading the config is the first of several startup steps, and the order is fixed. The file must load before the config reads, the config must load before anything that uses a setting, and the server must bind only after the config is known to be good.

1

Step 1: Load the env file

Call dotenvy::dotenv() so values from the .env file enter the environment. Without this step the loader sees only variables exported in the shell.

let _ = dotenvy::dotenv();
2

Step 2: Load the config

Call AppConfig::from_env() and handle the error. A failure here stops the program before anything else starts.

let config = match AppConfig::from_env() {
    Ok(config) => config,
    Err(error) => {
        eprintln!("Configuration error: {error}");
        std::process::exit(1);
    }
};
3

Step 3: Build the router with the config

Pass the config into the router as state, so handlers can read it.

let app = Router::new()
    .route("/", get(status))
    .with_state(config.clone());
4

Step 4: Bind and serve

Bind the listener to the address from the config, then serve. The bind uses config.listen_address, never a fixed string.

let listener = tokio::net::TcpListener::bind(config.listen_address)
    .await
    .unwrap();
axum::serve(listener, app).await.unwrap();

Skipping step 1 does not produce an error, which is what makes it easy to miss: the loader simply finds nothing in the environment and fails on the first required variable, or falls back to defaults for the optional ones. A server that starts on the default port with the default log level when a .env file is sitting right there is almost always a missing load call, not a missing file.

How the Pieces Connect

The flow from file to handler runs in one direction, and no step reads backwards.

.env file on disk
        |
        v
dotenvy::dotenv() loads values into the environment
        |
        v
AppConfig::from_env() reads four variables once
        |
        v
AppConfig holds database_url, listen_address, rust_log, jwt_secret
        |
        v
main uses listen_address to bind, passes the rest as state
        |
        v
handlers read the fields they need from State<AppConfig>

The struct sits in the middle of that flow, and it is the only object that knows all four values at once. Everything before it is about getting values in, and everything after it is about using values that are already checked.

Testing the Loader

The loader is easy to test because it is a plain function: set the variables, call it, and check the fields. The tests set variables with std::env::set_var, which changes the environment of the test process itself. Tests in one file share that process, so these tests run one at a time with --test-threads=1, or one test's variables would leak into the next test's reads.

tests/config_test.rs
use axum_project::config::AppConfig;

fn set_full_env() {
    std::env::set_var(
        "DATABASE_URL",
        "postgres://axumdocs:axumdocs@127.0.0.1:5432/ch21_config",
    );
    std::env::set_var("LISTEN_ADDRESS", "127.0.0.1:3000");
    std::env::set_var("RUST_LOG", "info");
    std::env::set_var("JWT_SECRET", "test-secret-only-for-local-development");
}

#[test]
fn full_env_loads() {
    set_full_env();
    let config = AppConfig::from_env().unwrap();
    assert_eq!(config.listen_address.to_string(), "127.0.0.1:3000");
    assert_eq!(config.rust_log, "info");
}

#[test]
fn missing_database_url_fails() {
    set_full_env();
    std::env::remove_var("DATABASE_URL");
    let error = match AppConfig::from_env() {
        Ok(_) => panic!("expected from_env to fail without DATABASE_URL"),
        Err(error) => error,
    };
    assert!(error.contains("DATABASE_URL"), "{error}");
}

#[test]
fn defaults_apply_when_optional_vars_missing() {
    set_full_env();
    std::env::remove_var("LISTEN_ADDRESS");
    std::env::remove_var("RUST_LOG");
    let config = AppConfig::from_env().unwrap();
    assert_eq!(config.listen_address.to_string(), "127.0.0.1:3000");
    assert_eq!(config.rust_log, "info");
}

Run them with:

cargo test --test config_test -- --test-threads=1

All three pass. The first proves a full environment loads, the second proves a missing required variable fails with a message naming it, and the third proves the two defaults appear when their variables are absent. The --test-threads=1 flag is not optional here: without it, the tests run in parallel threads of one process, and the remove_var in one test can run while another test is reading, which makes failures appear and disappear between runs.

Common Beginner Mistakes

Reading variables inside handlers

// Wrong - the handler reads the environment itself
async fn login() -> String {
    let secret = std::env::var("JWT_SECRET").expect("JWT_SECRET must be set");
    create_token(1, "user", &secret).unwrap()
}

A handler that reads the environment works until the day the variable is missing, and then it fails on the first request that reaches it, long after startup. The fix is to read the secret once in the loader and pass the config into the handler as state, so a missing secret fails at startup instead.

Loading the config twice

// Wrong - two loads that can disagree
let config = AppConfig::from_env().unwrap();
let pool = create_pool(&config.database_url).await.unwrap();
let config2 = AppConfig::from_env().unwrap();

Two loads read the environment twice, and the environment can change between them, so the two structs can hold different values. The fix is to load once, keep the one struct, and clone it where a second copy is needed.

Printing the config to check it loaded

// Wrong - a debug print would show the password and the secret
let config = AppConfig::from_env().unwrap();
println!("{config:?}");

This does not compile, because the struct has no Debug implementation, and that is deliberate. Adding #[derive(Debug)] to make it compile would print the database password and the signing secret into the logs. The fix is to print only the safe fields, as the smallest example does, and to use a hand-written Debug that hides the secrets, which the secrets page shows in full.

Forgetting the dotenv call

// Wrong - the .env file exists, but nothing loads it
fn main() {
    let config = AppConfig::from_env().unwrap();
}

Without the dotenvy::dotenv() call, the loader sees only variables exported in the shell. The .env file sits unread, the required variables look missing, and the program fails at startup with a confusing message. The fix is the one line at the top of main, before the loader runs.

Final Complete Example

Everything on this page put together is one project: the config module with the Result loader, the server that serves its own settings, the .env file that feeds it, and the tests that prove the loader behaves.

Cargo.toml
[package]
name = "axum-project"
version = "0.1.0"
edition = "2021"

[dependencies]
axum = "=0.8.9"
tokio = { version = "=1.54.1", features = ["full"] }
serde = { version = "1", features = ["derive"] }
serde_json = "1"
dotenvy = "=0.15.7"

[dev-dependencies]
tower = { version = "0.5", features = ["util"] }
.env
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
src/config.rs
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())?;
        Ok(AppConfig {
            database_url,
            listen_address,
            rust_log,
            jwt_secret,
        })
    }
}
src/lib.rs
pub mod config;
src/main.rs
use axum::{Json, extract::State, routing::get, Router};
use axum_project::config::AppConfig;
use serde::Serialize;

#[derive(Serialize)]
struct Status {
    listen_address: String,
    rust_log: String,
}

async fn status(State(config): State<AppConfig>) -> Json<Status> {
    Json(Status {
        listen_address: config.listen_address.to_string(),
        rust_log: config.rust_log.clone(),
    })
}

#[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);
        }
    };
    let app = Router::new()
        .route("/", get(status))
        .with_state(config.clone());
    let listener = tokio::net::TcpListener::bind(config.listen_address)
        .await
        .unwrap();
    println!("Listening on http://{}", config.listen_address);
    axum::serve(listener, app).await.unwrap();
}

Run the checks with these commands:

cargo check
cargo test --test config_test -- --test-threads=1
cargo run

Then request the route:

curl http://127.0.0.1:3000/

The response shows the two safe settings, and the server keeps running until it is stopped.

Summary

The struct is a boundary between the machine and the code. The machine owns the values, the code owns the types, and the loader is the one place where the two meet. That boundary is what makes the rest of the work possible: each field page can now teach one setting in depth without re-explaining where settings live, and the validation page can check all four fields in one method because they are already gathered in one struct.

The decision framework for growing the struct is short. A value that changes between machines belongs in the struct and in the environment, never in the code. A value with a safe default gets one in the loader, and a value where a default would be dangerous stays required. And a field that holds a secret never gets a debug print, a log line, or a response field. With those three rules, the struct stays small, the settings stay in one place, and the server fails at startup, in plain words, whenever a setting is wrong.