Ricky Moony and Lucy, a moon shaped mascot for Dream with the star shaped mascot for Gleam, each with cute cartoon eyes and a smile

Type-safe configuration management for Gleam applications


Hex Package Latest Release HexDocs Coverage MIT License Gleam

What is dream_config?

A standalone module for loading configuration from environment variables and .env files. It is built with the same quality standards as Dream, but it is completely independent. Use it in any Gleam project.

Features

Installation

gleam add dream_config

Quick Start

Read your settings into a record. Each error names the variable:

Read the settings into a record Tested snippet Guide: Load your app's settings at startup

import dream_config/loader.{type ConfigError} as config
import gleam/result

pub type Settings {
  Settings(database_url: String, port: Int, debug_mode: Bool, api_key: String)
}

pub fn load_settings() -> Result(Settings, ConfigError) {
  // Required: the error names the variable that is not set, empty or wrong
  use database_url <- result.try(config.get_required("DATABASE_URL"))
  use port <- result.try(config.get_required_int("PORT"))

  // Optional, with defaults
  let debug_mode = config.get_bool("DEBUG")
  let api_key = config.get("API_KEY") |> result.unwrap("default-key")

  Ok(Settings(database_url:, port:, debug_mode:, api_key:))
}

Then load the .env file and the settings one time at startup, and stop with the reason when one is missing or wrong:

Start the app or stop with the reason Tested snippet Guide: Load your app's settings at startup

import dream_config/loader as config
import gleam/int
import gleam/io
import gleam/result
import snippets/readme_quick_start.{type Settings, load_settings}

pub fn main() -> Nil {
  case start() {
    Ok(message) -> io.println(message)
    Error(reason) -> {
      io.println_error("Cannot start: " <> reason)
      halt(1)
    }
  }
}

pub fn start() -> Result(String, String) {
  // Local values. A variable that is already set keeps its value.
  use _ <- result.try(
    config.load_dotenv() |> result.map_error(config.describe_load_error),
  )
  use settings <- result.try(
    load_settings() |> result.map_error(config.describe),
  )
  Ok(serve(settings))
}

fn serve(settings: Settings) -> String {
  "Listening on port " <> int.to_string(settings.port)
}

@external(erlang, "erlang", "halt")
fn halt(status: Int) -> Nil

Guides

API Reference

The full API reference is on HexDocs.

Design Principles

dream_config follows Dream's design principles and contributing guide.

About Dream

This module was originally built for the Dream web toolkit, but it's completely standalone and can be used in any Gleam project. It follows Dream's design principles and will be maintained as part of the Dream ecosystem.

Contributing

See the Contributing Guide. The coding and testing standards are Dream's: see Dream's contributing guide.


License

MIT — see LICENSE.md


Built in Gleam, on the BEAM, by the Dream Team ❤️