The dotenv call

Learn where the dotenv call goes in your program, when it runs, what it returns, and what happens when the file is missing

The dotenv call is the one line that connects a .env file to a running program. It reads the file, parses each line, and places the values into the process environment. Everything else in configuration depends on that line running first. A program that reads a value before the call sees nothing, a program that never makes the call never sees the file at all, and a program that handles the call's result badly hides its own mistakes.

Where This Fits in Configuration

A .env file on disk does nothing by itself. The loader does nothing until it is called. The program reads the environment through std::env::var, and the environment starts out holding only what the shell gave it. The dotenv call is the step that fills the gap between the file and the environment.

Think of it like switching on a light before reading a page. The page holds the words, the eyes do the reading, and the switch is the small action that makes the reading possible. The call is that switch. It belongs at the very start of the program, before any code that reads a setting.

The Smallest Working Call

The smallest program that loads a file and reads a value looks like this:

// src/main.rs
fn main() {
    dotenvy::dotenv().ok();

    let port = std::env::var("PORT").unwrap_or_else(|_| "3000".to_string());
    println!("Port is {}", port);
}
# .env
PORT=3000

Run it from the project root:

cargo run

The output is:

Port is 3000

Two lines do the work. The first line loads the file. The second line reads a value that the first line made available. Remove the first line and run again, and the program prints the fallback 3000 for a different reason: the value was never loaded, so the fallback fires. The output looks the same, which is why the order matters and why a program should say what it loaded while it is being set up.

Working Call:

If the program prints the value from the file, the call ran in the right place and the file was found. Change the value in the file, run again, and the output should change with it. If it does not change, the call is not running before the read.

Where the Call Goes

The call goes at the top of main, before any other code that reads the environment. In an Axum program, main is the function that builds the router, binds the listener, and starts the server. The dotenv call is the first statement inside it:

// src/main.rs
use axum::{routing::get, Router};

#[tokio::main]
async fn main() {
    dotenvy::dotenv().ok();

    let port = std::env::var("PORT").unwrap_or_else(|_| "3000".to_string());
    let address = format!("127.0.0.1:{}", port);

    let app = Router::new().route("/", get(|| async { "Hello!" }));
    let listener = tokio::net::TcpListener::bind(&address).await.unwrap();
    println!("Listening on http://{}", address);
    axum::serve(listener, app).await.unwrap();
}

The #[tokio::main] attribute above main starts the Tokio runtime, which is the async engine Axum needs. The dotenv call sits inside the function, after the attribute, as the first line of real code. It does not need to be async, and it does not need an .await, because reading a file from disk is a plain synchronous action. It runs once, at startup, and then the rest of the program carries on.

The call must come before the code that builds anything from settings. In the example above, the port is read on the line after the call, and the listener is bound with that port further down. If the call moved below the port read, the port would always be the fallback. If the call moved below the listener bind, the server would bind the fallback port and the file would load too late to matter.

A library function should not make the call. The call belongs in main, which is the one place that runs once at startup and controls the order of everything after it. A library that loads a file on its own surprises the program that uses it, because the load happens at a time and place the program did not choose.

What the Call Returns

dotenvy::dotenv() returns a Result<PathBuf>. A Result is Rust's way of holding either a success value or an error. Here the success value is a PathBuf, which is a file path, pointing at the .env file that was actually loaded. The error value is a dotenvy Error with three shapes:

  • Io for file problems, such as the file being missing or unreadable.
  • LineParse for a line in the file that does not follow the format. The error carries the line text and the position where parsing stopped.
  • EnvVar for a problem reading a variable from the environment.

The success path is useful for logging. A program that prints the returned path tells its user exactly which file supplied the settings, which matters in a project where several .env files exist at different levels of the directory tree:

// src/main.rs
fn main() {
    match dotenvy::dotenv() {
        Ok(path) => println!("Loaded settings from {:?}", path),
        Err(error) => println!("Settings file not loaded: {}", error),
    }
}

With a file in the project root, the output looks like:

Loaded settings from "/home/user/dotenv-demo/.env"

The path is absolute, because the loader resolves the file it found while walking up the directory tree. A program launched from a subdirectory prints the path of the parent file it found, not the subdirectory it started in. That detail was checked live: a program launched two folders below the file reported the file's real path.

What Happens When the File Is Missing

A missing file is an error, not a silent no-op. The dotenv() function returns an Err when no .env file exists in the current directory or any parent directory. The error text is path not found, and the error answers true to a helper method called not_found(). A live run from an empty directory confirmed both the message and the helper:

dotenv Err: path not found not_found=true

The full error value in debug form is Io(Custom { kind: NotFound, error: "path not found" }), which shows the error is an Io error with the NotFound kind. A program can use not_found() to tell a missing file apart from a broken file, and that split drives the three ways of handling the result.

Ignoring the Error with ok

The .ok() method turns a Result into an Option, throwing the error away. The program carries on with shell values and fallbacks. This fits a program that can run without the file, such as a server that has a default port and a default log level:

// src/main.rs
fn main() {
    dotenvy::dotenv().ok();
    let port = std::env::var("PORT").unwrap_or_else(|_| "3000".to_string());
    println!("Port is {}", port);
}

The cost is silence. A missing file, a broken line, and a successful load all look identical. While a project is being set up, that silence hides the two most common problems. Once the file loads cleanly, .ok() is a reasonable choice for a program with a fallback for every value.

Stopping with expect

The expect method stops the program with a message when the result is an error. This fits a program that cannot run without its settings:

// src/main.rs
fn main() {
    dotenvy::dotenv().expect("failed to load .env file");
    let port = std::env::var("PORT").unwrap_or_else(|_| "3000".to_string());
    println!("Port is {}", port);
}

With no file present, the program stops and prints the message plus the error. The message should name the file, because the person reading it is usually the developer who forgot to create it. The danger is using expect in a deployed server, where no file exists by design and the settings come from the platform. That server would stop on every start.

Handling the Error with match

The match form gives the program a separate response for each situation. A missing file gets a calm message, a broken line gets the error text, and a successful load gets a confirmation:

// src/main.rs
fn main() {
    match dotenvy::dotenv() {
        Ok(path) => println!("Loaded settings from {:?}", path),
        Err(error) => {
            if error.not_found() {
                println!("No .env file found, using shell values and fallbacks");
            } else {
                println!("Problem loading .env file: {}", error);
            }
        }
    }

    let port = std::env::var("PORT").unwrap_or_else(|_| "3000".to_string());
    println!("Port is {}", port);
}

This form was run live in both states. With the file present it printed the loaded path and the value from the file. With the file removed it printed the calm message and the fallback value. It is the clearest form for a program that is still being set up, and it costs only a few lines.

Propagating the Error with the Question Mark

A main function that returns a Result can use the ? operator to pass the error up and stop the program:

// src/main.rs
fn main() -> Result<(), Box<dyn std::error::Error>> {
    dotenvy::dotenv()?;

    let port = std::env::var("PORT")?;
    println!("Port is {}", port);
    Ok(())
}

The ? operator returns early from the function with the error when the call fails. The Box<dyn std::error::Error> return type is Rust's way of saying the function can fail with any error type. This form fits a small tool that should stop when its settings are missing. It fits badly in an Axum main, because an async main with a Result return type and the Tokio attribute is awkward to combine, and because a server usually wants fallbacks rather than a hard stop.

Choosing Between the Four Forms:

The four forms answer four different situations. Use .ok() when every value has a fallback. Use expect when the program cannot run without the file. Use match when the program should explain what happened. Use ? when a small tool should stop on any failure. The choice is about what the program should do without the file, not about which form looks shortest.

When the Call Runs

The call runs once, at startup, in the order the code lists it. It does not run again when a value is read later, and it does not watch the file for changes. A value changed in the file while the program runs has no effect until the program restarts. A value set in the shell after startup has no effect either, because the environment is copied into the process when it starts.

This once-at-startup behaviour has a practical consequence for tests. A test that writes a .env file and then calls dotenv() loads the values into the test process, and those values stay set for every test that runs after it in the same process. Two tests that load different files with the same key will interfere with each other, because the second load does not overwrite the first. The testing section below shows how to avoid that.

The call also runs before any handler, any middleware, and any background task. Those pieces all read the environment through code that runs after main has started, so they see the loaded values. A handler that reads std::env::var("APP_NAME") on a request gets the value from the file, even though the handler code never mentions the file. The load happened once at the top, and every later read benefits from it.

The Order Rule Inside One Call

The call loads the file from top to bottom, and the first value for a key wins. A file with DUP=first on one line and DUP=second on a later line sets DUP to first. The later line is read and then ignored, because the key is already set.

The same first-wins rule applies against the shell. A value already present in the environment before the call is left alone. A live run proved it: with PORT=9999 set in the shell and PORT=3000 in the file, the program printed 9999 after the call. The file lost to the shell.

A broken line stops the load in the middle. The lines before it are set, the broken line produces the error, and the lines after it never load. A live run showed this exactly: a file with a broken line in the middle loaded the first two values, returned a LineParse error, and left the rest unset. The program that ignores the result with .ok() then runs with half its settings and no warning, which is why the match form matters during setup.

dotenvy::dotenv() is called
        |
        v
search current directory, then parents, for .env
        |
        v
file found? no -> return Io error, not_found() is true
        |
        v yes
read the file line by line, top to bottom
        |
        v
bad line? yes -> stop, return LineParse error, later lines skipped
        |
        v no
set each value, skipping keys already in the environment
        |
        v
return Ok with the path of the file that was loaded

The Override Call

dotenvy::dotenv_override() is the same search and the same parse, with the precedence rules flipped. The file wins over the shell, and the last line for a key wins over earlier lines. A live run proved both flips at once: with PORT=9999 in the shell and PORT=3000 in the file, the override call printed 3000, and a file with DUP=first followed by DUP=second printed second.

// src/main.rs
fn main() {
    dotenvy::dotenv_override().ok();

    let port = std::env::var("PORT").unwrap_or_else(|_| "3000".to_string());
    println!("Port is {}", port);
}

The override call fits one situation: a run where the file must control every value, such as a test suite that needs a fixed environment regardless of what the machine running it has set. It does not fit a normal server run, because it takes away the shell's ability to override the file, and a deployment platform sets values through the shell. A program that calls the override version by default has usually picked the wrong tool for the job.

Override Mode Changes Two Rules at Once:

dotenv_override() flips both precedence rules: the file beats the shell, and the last line beats the first. A developer who switches to it to fix one value can be surprised by the other flip changing a different value. Switch only when both flips are wanted.

Loading a Different File

The plain call always looks for a file named .env. Two other functions load a different file, and each fits a different need.

from_path takes an exact path and loads that file only. It does not search parent directories, and it does not look for .env unless the path says so:

// src/main.rs
use std::path::Path;

fn main() {
    match dotenvy::from_path(Path::new("config/local.env")) {
        Ok(()) => println!("Settings loaded"),
        Err(error) => println!("Could not load settings: {}", error),
    }
}

The return type is Result<()>, which means success carries no value, only the fact that it worked. A live run against a missing path gave the error No such file or directory (os error 2) with not_found() returning true. The message differs from the plain call's path not found, because opening a named file fails differently from searching for one, but both are Io errors and both answer true to not_found().

from_filename takes a name and searches the current directory and its parents for that name, the same way the plain call searches for .env:

// src/main.rs
fn main() {
    dotenvy::from_filename("development.env").ok();
    let port = std::env::var("PORT").unwrap_or_else(|_| "3000".to_string());
    println!("Port is {}", port);
}

A project that keeps a file named development.env at its root can load it from any subdirectory with this call. The return type is Result<PathBuf>, like the plain call, holding the path of the file that was found.

The choice between the three is simple. The plain call fits the standard file in the standard place. from_filename fits a differently named file in the standard search. from_path fits a file in a known location that must be loaded exactly as given.

Reading Without Loading

dotenv_iter() parses the file and returns each key and value pair without putting anything into the environment. Each item is a Result of its own, so a bad line appears as an error item while the good lines still come through:

// src/main.rs
fn main() {
    match dotenvy::dotenv_iter() {
        Ok(pairs) => {
            for item in pairs {
                match item {
                    Ok((key, value)) => println!("{}={}", key, value),
                    Err(error) => println!("Bad line: {}", error),
                }
            }
        }
        Err(error) => println!("Could not find a .env file: {}", error),
    }
}

This is the right tool for inspecting a file. A small command that prints what a file contains, or a test that checks a file parses, uses the iterator form. It is the wrong tool for loading settings, because nothing it returns reaches the environment, and a program that reads a value after iterating will find nothing new.

The var and vars functions are a different shortcut. dotenvy::var("PORT") loads the file once, the first time it is called, and then reads one variable. dotenvy::vars() does the same and lists every variable. The load happens silently and only once per process. A program can use var without any explicit call at all, but the explicit call at the top of main is clearer. It says in plain sight that a file is being loaded, and it says exactly when.

A Richer Complete Example

The example below is a small Axum server that loads its settings, reports what it found, and serves the app name on its root route. It was run live with dotenvy 0.15.7, axum 0.8.9, and tokio 1.54.1:

// src/main.rs
use axum::{routing::get, Router};

#[tokio::main]
async fn main() {
    match dotenvy::dotenv() {
        Ok(path) => println!("Loaded settings from {:?}", path),
        Err(error) => {
            if error.not_found() {
                println!("No .env file found, using shell values and fallbacks");
            } else {
                println!("Problem loading .env file: {}", error);
            }
        }
    }

    let app_name = std::env::var("APP_NAME").unwrap_or_else(|_| "unnamed app".to_string());
    let port = std::env::var("PORT").unwrap_or_else(|_| "3000".to_string());
    let address = format!("127.0.0.1:{}", port);

    let app = Router::new()
        .route("/", get(move || async move { format!("Hello from {}!", app_name) }));

    let listener = tokio::net::TcpListener::bind(&address).await.unwrap();
    println!("Listening on http://{}", address);
    axum::serve(listener, app).await.unwrap();
}
# Cargo.toml
[package]
name = "dotenv-demo"
version = "0.1.0"
edition = "2021"

[dependencies]
axum = "0.8"
dotenvy = "0.15"
tokio = { version = "1", features = ["full"] }
# .env
APP_NAME=dotenv-demo
PORT=3000

Running cargo run printed Loaded settings from ".../.env" and Listening on http://127.0.0.1:3000, and opening that address showed Hello from dotenv-demo!. Running it again with PORT=4001 cargo run printed Listening on http://127.0.0.1:4001 while still showing the app name from the file. The shell won the port, the file supplied the name, and the startup message said which file was loaded. A third run from a directory with no file, using PORT=4002, printed the calm missing-file message and still served on port 4002, because the fallback covered the missing value.

The move keyword on the route closure is worth a sentence. The closure captures app_name from the surrounding function, and move tells Rust the closure takes ownership of that value instead of borrowing it. The server owns the closure for as long as it runs, so a borrow of a local variable would not live long enough.

Testing the Call

A test for the call should use from_path with a file the test writes itself, rather than dotenv() with whatever file happens to sit in the working directory. The test below writes a file, loads it, checks the values, and also checks the missing-file error:

// tests/dotenv_call.rs
use std::io::Write;

#[test]
fn test_dotenv_call_loads_file_and_reports_missing_file() {
    let dir = std::env::temp_dir().join("dotenvy-call-test");
    std::fs::create_dir_all(&dir).unwrap();

    let path = dir.join("test.env");
    let mut file = std::fs::File::create(&path).unwrap();
    writeln!(file, "TEST_CALL_APP=call-test-app").unwrap();
    writeln!(file, "TEST_CALL_PORT=4321").unwrap();
    drop(file);

    dotenvy::from_path(&path).unwrap();
    assert_eq!(std::env::var("TEST_CALL_APP").unwrap(), "call-test-app");
    assert_eq!(std::env::var("TEST_CALL_PORT").unwrap(), "4321");

    let missing = dotenvy::from_path(dir.join("no-such-file.env"));
    assert!(missing.is_err());
    assert!(missing.unwrap_err().not_found());

    std::fs::remove_file(&path).unwrap();
}

Run it with:

cargo test

The key names start with TEST_CALL_ so they cannot collide with real settings. The missing-file check uses not_found() rather than matching the error text, because the text can differ between the search and the direct open, while not_found() is true for both. One caution applies across the whole test suite: environment variables are shared by the entire test process, so two tests that load the same key interfere with each other. Unique key names per test avoid that.

Common Beginner Mistakes

Reading a Value Before the Call

// Wrong - the read happens before the file is loaded
fn main() {
    let port = std::env::var("PORT").unwrap_or_else(|_| "3000".to_string());
    dotenvy::dotenv().ok();
    println!("Port is {}", port);
}

The port read runs first and always sees the fallback. The fix is order: the dotenv call is the first statement in main, before any std::env::var call.

Calling dotenv in a Handler

// Wrong - loads the file on every request
async fn handler() -> String {
    dotenvy::dotenv().ok();
    std::env::var("APP_NAME").unwrap_or_default()
}

The file is read from disk on every request, which is slow and pointless, since the values do not change while the program runs. The fix is to load once in main and read the value in the handler. A handler reads the environment. It never loads the file.

Expecting the Call to Watch the File

Editing the .env file while the server runs changes nothing until the server restarts. The call runs once at startup and never again. A developer who edits the port in the file and refreshes the browser without restarting will see the old port and conclude the file is broken. The file is fine. The program needs a restart.

Using expect in a Deployed Server

// Wrong for a server that gets settings from its platform
dotenvy::dotenv().expect("failed to load .env file");

A deployed server has no .env file by design, so this line stops it on every start. The fix is .ok() with fallbacks, or the match form that carries on when the file is absent. expect belongs in a local tool that truly cannot run without the file.

The Call Must Come First:

Every mistake in this section has the same root: the call ran in the wrong place, at the wrong time, or not at all. Put the call first in main, run it once, and read values only after it.

Final Complete Example

The final example gathers the call, the error handling, and the server startup into one program. It reports what it loaded, falls back cleanly when the file is absent, and serves the loaded values:

// src/main.rs
use axum::{routing::get, Router};

#[tokio::main]
async fn main() {
    match dotenvy::dotenv() {
        Ok(path) => println!("Loaded settings from {:?}", path),
        Err(error) => {
            if error.not_found() {
                println!("No .env file found, using shell values and fallbacks");
            } else {
                println!("Problem loading .env file: {}", error);
            }
        }
    }

    let app_name = std::env::var("APP_NAME").unwrap_or_else(|_| "unnamed app".to_string());
    let port = std::env::var("PORT").unwrap_or_else(|_| "3000".to_string());
    let address = format!("127.0.0.1:{}", port);

    let app = Router::new()
        .route("/", get(move || async move { format!("Hello from {}!", app_name) }));

    let listener = tokio::net::TcpListener::bind(&address).await.unwrap();
    println!("Listening on http://{}", address);
    axum::serve(listener, app).await.unwrap();
}
# Cargo.toml
[package]
name = "dotenv-demo"
version = "0.1.0"
edition = "2021"

[dependencies]
axum = "0.8"
dotenvy = "0.15"
tokio = { version = "1", features = ["full"] }
# .env
APP_NAME=dotenv-demo
PORT=3000

With the file present, the startup output is:

Loaded settings from "/home/user/dotenv-demo/.env"
Listening on http://127.0.0.1:3000

With the file absent, the startup output is:

No .env file found, using shell values and fallbacks
Listening on http://127.0.0.1:3000

The server starts in both cases. The difference is only in what the startup message says and where the values came from. That is the behaviour a program should aim for: it tells the truth about its settings, and it keeps working when the file is not there.

Summary

The dotenv call is small, but its placement and its result handling decide how the whole program behaves. First in main, once, before any value is read. A missing file is a normal situation for a program with fallbacks and an error for a program without them, and the code should say which one it is instead of hiding the difference behind .ok(). The shell beats the file, the first line beats later lines, and a broken line stops the load halfway, so the error text is the first place to look when a value is missing.

The decision framework fits in one sentence. If the program can run without the file, use .ok() or the match form with fallbacks. If it cannot run without the file, use expect and say so in the message. If the file must win over the shell, use the override call and accept that both precedence rules flip. And if the file is not named .env or not in the usual place, reach for from_filename or from_path instead of fighting the default search.