# How do I load settings from a file and environment variables in Rust?
Source: https://ruststudio.org/community/t/14/how-do-i-load-settings-from-a-file-and-environment-variables-in-rust
Author: Ruststudio Team (staff) | Published: 2026-12-05 | Updated: 2026-12-05 | Checked with: rustc 1.93.0, toml 0.8, serde 1, Windows 11
Category: Help and questions | Kind: FAQ | Tags: configuration, serde, deployment | Views: 0

## Short answer
Define a settings struct that derives Deserialize, read a TOML file into it with the toml crate, give optional fields defaults with serde, then let environment variables override the file. The order is defaults, then file, then environment, so one build runs unchanged on a laptop and on a server.

## Answer
## Answer
Keep settings out of the source: a file holds the normal values, and environment variables override them per machine (for example a port or a database URL set by the host). Deserialize the file into a struct so a wrong type is an error at start-up.

```toml title=Cargo.toml
[dependencies]
serde = { version = "1", features = ["derive"] }
toml = "0.8"
```

```rust title=src/main.rs
use serde::Deserialize;
use std::path::Path;

#[derive(Debug, Deserialize)]
struct Settings {
    site_url: String,
    #[serde(default = "default_port")]
    port: u16,
    database_url: Option<String>,
}

fn default_port() -> u16 {
    8080
}

/// Order of precedence: environment variables win over the settings file, which wins over the defaults.
fn load(file: &Path, env: impl Fn(&str) -> Option<String>) -> Result<Settings, String> {
    let text = std::fs::read_to_string(file).map_err(|e| format!("cannot read {}: {e}", file.display()))?;
    let mut s: Settings = toml::from_str(&text).map_err(|e| format!("{} is not valid: {e}", file.display()))?;
    if let Some(v) = env("SITE_URL") {
        s.site_url = v;
    }
    if let Some(p) = env("PORT").and_then(|p| p.parse().ok()) {
        s.port = p;
    }
    if let Some(v) = env("DATABASE_URL") {
        s.database_url = Some(v);
    }
    Ok(s)
}

fn main() {
    let dir = std::env::temp_dir().join("settings-demo");
    std::fs::create_dir_all(&dir).unwrap();
    let file = dir.join("settings.toml");
    std::fs::write(&file, "site_url = \"https://example.test\"\n").unwrap();

    println!("{:?}", load(&file, |_| None));
    println!("{:?}", load(&file, |k| (k == "PORT").then(|| "9000".to_string())));
    println!("{:?}", load(&dir.join("missing.toml"), |_| None).unwrap_err().contains("cannot read"));
    std::fs::write(&file, "port = \"high\"\n").unwrap();
    println!("{}", load(&file, |_| None).is_err());
}
```

```text
Ok(Settings { site_url: "https://example.test", port: 8080, database_url: None })
Ok(Settings { site_url: "https://example.test", port: 9000, database_url: None })
true
true
```

Line one uses the default port, line two shows the environment overriding it, line three a missing file, and line four a file of the wrong shape (`port` as text, and `site_url` missing).

## Common mistakes
- Putting passwords in the file that is committed to Git. Keep secrets in environment variables or a file outside the repository.
- Silently ignoring a bad value. Print which setting was rejected.
- Reading environment variables all over the program. Read them once, at start-up, into the struct.

## Related questions
### Why not use JSON for settings?
JSON has no comments, which settings files need. TOML or a similar format is easier to maintain by hand.

### Is there a crate that does the layering for me?
Yes, crates such as `config` and `figment` layer files and environment variables; the code above shows what they do, with no extra dependency.

## Sources
- toml crate: https://docs.rs/toml/
- serde field attributes: https://serde.rs/field-attrs.html
