Skip to main content

Crate env_required

Crate env_required 

Source
Expand description

§env-required

Ultra-lightweight required environment variable validation for Rust.

  • Zero dependencies (std-only)
  • One macro: required!
  • Helpful panic messages (designed for backend/CLI/server startup)
  • Optional FromStr parsing

If you want your program to fail fast with a clear message when configuration is missing, this crate is for you.

§Installation

[dependencies]
env-required = "0.1"

§Quick Start (single env)

use env_required::required;

fn main() {
    let database_url = required!("DATABASE_URL");
    println!("db={database_url}");
}

§Validate Many (startup check)

use env_required::required;

fn main() {
    required!(["DATABASE_URL", "PORT", "RUST_LOG"]);

    // ...start your app
}

§Type Conversion (FromStr)

use env_required::required;

fn main() {
    let port: u16 = required!("PORT" => u16);
    let workers: usize = required!("WORKERS" => _); // `_` lets the compiler infer the type.

    println!("port={port} workers={workers}");
}

§Custom Message

use env_required::required;

fn main() {
    let token = required!("API_TOKEN", "API_TOKEN is required to call Example API");
    required!(["DATABASE_URL", "PORT"], "missing configuration for my-service");
    println!("token_len={}", token.len());
}

§Why a macro?

required! is a macro because:

  1. It gives a single, memorable entry point without importing multiple helpers.
  2. We can provide syntax-level guidance (and compile_error! for misuses).
  3. It keeps call sites short and consistent in binaries and libraries.

Internally, the macro expands to small std::env helpers. There is no hidden magic.

§FAQ

§Why panic instead of returning Result?

This crate targets startup configuration validation.

If required configuration is missing, continuing is usually incorrect and leads to harder-to-debug failures later. Fail-fast panics produce a single, clear error early.

If you need a Result-based API (e.g. for a long-running library), consider implementing a thin wrapper around this macro, or see the “Alternative API” idea in the crate documentation.

§Does it load .env files?

No.

This crate intentionally does not include a .env loader to stay dependency-free. If you want .env support, use a loader in your binary (e.g. dotenvy) and then call required!.

§Is an empty string considered missing?

By default, yes (KEY="" is treated as missing).

Enable feature allow-empty to treat empty strings as present:

[dependencies]
env-required = { version = "0.1", features = ["allow-empty"] }

§MSRV

Rust 1.56 (Edition 2021).

§License

MIT OR Apache-2.0

Macros§

required
Read and validate required environment variables.