How to Use .env Files in Rust (dotenvy crate)

Load environment variables from a .env file in Rust by adding the dotenvy crate and calling dotenvy::dotenv() at startup.

Add the dotenvy crate to your dependencies, create a .env file in your project root, and call dotenvy::dotenv() at the start of your main function to load variables into the environment.

use dotenvy::dotenv;
use std::env;

fn main() -> Result<(), dotenvy::Error> {
    dotenv()?;
    let db_url = env::var("DATABASE_URL").expect("DATABASE_URL must be set");
    println!("Connecting to: {}", db_url);
    Ok(())
}

Add this to Cargo.toml:

[dependencies]
dotenvy = "0.15"

Create a .env file in the project root:

DATABASE_URL=postgres://user:pass@localhost/mydb