Load Environment Variables From ".env" Files In Your Rust Program
A good practice in software development is to separate the “secrets” — such as API Tokens — from your source code. Otherwise, people, when visualizing the code could take those secrets, and that represents a security breach.
Today, I was working on setting up a newsletter on my website, that’s open source, and had the need MAILCOACH_API_TOKEN
to interact with the mailcoach.app. Now, because my website is built on Rust, I’ve used the dotenv crate to collect environment variables from a “.env” file.
So, first I’ve used cargo
to add the dotenv to my project:
cargo add dotenv
After, I’ve created a .env
file in the root of my project, and inserted the necessary API TOKEN there:
MAILCOACH_API_TOKEN=my_api_token_here
Next, I’ve changed the entry point of my Rust program src/bin/server.rs
to load these environment variables when my program starts:
use dotenv::dotenv;
fn main() {
dotenv().ok(); // This line loads the environment variables from the ".env" file.
// ..
}
Finally, I’ve adjusted the code to collect the Mailcoach API Token when necessary using the standard library:
let mailcoach_api_token = std::env::var("MAILCOACH_API_TOKEN").expect("MAILCOACH_API_TOKEN must be set.");
I hope you have enjoyed this article. If yes, please consider supporting my work — my mission is to spend more time maintaining the dozens of projects that I've written/collaborated on over the years and continue developing new projects to make PHP development more productive and enjoyable.