Skip to content

Environment variable management and configuration for ReScript applications

License

Unknown, Unknown licenses found

Licenses found

Unknown
LICENCE
Unknown
LICENSE
Notifications You must be signed in to change notification settings

hyperpolymath/rescript-env

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

7 Commits
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 

rescript-env

ReScript Deno License RSR Tier 1 Ecosystem

Type-safe environment variable access for ReScript with automatic runtime detection.

Part of the ReScript Full Stack ecosystem.

Part of the ReScript Full Stack ecosystem.

rescript-env provides a type-safe, cross-runtime API for accessing environment variables in ReScript applications. It automatically detects whether your code is running in Deno, Bun, or Node.js and uses the appropriate APIs.

1. Why rescript-env?

Problem Solution

Environment variables are stringly-typed

Returns option<string> for safe handling

No built-in type coercion

getInt, getFloat, getBool with validation

Runtime differences (Deno vs Node)

Automatic runtime detection and API selection

Missing required config crashes apps

getExn with descriptive MissingEnvVar exception

Boilerplate for dev/prod checks

Built-in isDevelopment, isProduction, isTest

2. Installation

deno add jsr:@hyperpolymath/rescript-env

2.2. Using npm (for Node.js projects)

# Not yet published - use git submodule or copy src/

3. Quick Start

// Required configuration - throws if missing
let databaseUrl = Env.getExn("DATABASE_URL")

// Optional with default
let port = Env.getOr("PORT", "3000")

// Type-safe coercion
let maxConnections = Env.getInt("MAX_CONNECTIONS")  // option<int>
let debugMode = Env.getBool("DEBUG")                // option<bool>
let timeout = Env.getFloat("TIMEOUT_SECONDS")       // option<float>

// Environment detection
if Env.isDevelopment() {
  Console.log("Running in development mode")
}

// Check existence
if Env.has("API_KEY") {
  // API key is configured
}

4. API Reference

4.1. Basic Access

4.1.1. get

let get: string => option<string>

Returns Some(value) if the environment variable is set, None otherwise.

switch Env.get("API_KEY") {
| Some(key) => authenticateWith(key)
| None => Console.log("No API key configured")
}

4.1.2. getOr

let getOr: (string, string) => string

Returns the environment variable value or the provided default.

let host = Env.getOr("HOST", "localhost")
let port = Env.getOr("PORT", "8080")

4.1.3. getExn

let getExn: string => string

Returns the value or raises MissingEnvVar(name) exception.

// Will crash with clear error if DATABASE_URL is not set
let dbUrl = Env.getExn("DATABASE_URL")

4.2. Type Coercion

4.2.1. getInt

let getInt: string => option<int>

Parses the environment variable as an integer.

let port = Env.getInt("PORT")->Option.getOr(3000)
let workers = Env.getInt("WORKERS")->Option.getOr(4)

4.2.2. getFloat

let getFloat: string => option<float>

Parses the environment variable as a float.

let timeout = Env.getFloat("TIMEOUT_SECONDS")->Option.getOr(30.0)

4.2.3. getBool

let getBool: string => option<bool>

Parses the environment variable as a boolean. Recognises:

  • True values: "true", "1", "yes", "on"

  • False values: "false", "0", "no", "off"

let debug = Env.getBool("DEBUG")->Option.getOr(false)
let enableMetrics = Env.getBool("ENABLE_METRICS")->Option.getOr(true)

4.3. Mutation

4.3.1. set

let set: (string, string) => unit

Sets an environment variable.

Env.set("NODE_ENV", "test")

4.3.2. delete

let delete: string => unit

Deletes an environment variable.

Env.delete("TEMPORARY_TOKEN")

4.4. Introspection

4.4.1. has

let has: string => bool

Checks if an environment variable is set.

if Env.has("REDIS_URL") {
  initializeRedisCache()
}

4.4.2. all

let all: unit => Dict.t<string>

Returns all environment variables as a dictionary.

let allEnv = Env.all()
allEnv->Dict.forEach((key, value) => {
  Console.log(`${key}=${value}`)
})

4.5. Environment Detection

4.5.1. isDevelopment

let isDevelopment: unit => bool

Returns true if NODE_ENV, DENO_ENV, or ENV is "development" or "dev".

4.5.2. isProduction

let isProduction: unit => bool

Returns true if NODE_ENV, DENO_ENV, or ENV is "production" or "prod".

4.5.3. isTest

let isTest: unit => bool

Returns true if NODE_ENV, DENO_ENV, or ENV is "test".

4.6. Exception

4.6.1. MissingEnvVar

exception MissingEnvVar(string)

Raised by getExn when the requested environment variable is not set.

try {
  let secret = Env.getExn("SECRET_KEY")
  // use secret
} catch {
| Env.MissingEnvVar(name) =>
  Console.error(`Missing required env var: ${name}`)
  Process.exit(1)
}

5. Patterns & Best Practices

5.1. Configuration Module Pattern

Create a dedicated configuration module that validates all required env vars at startup:

// src/Config.res
let database = {
  "url": Env.getExn("DATABASE_URL"),
  "maxConnections": Env.getInt("DB_MAX_CONNECTIONS")->Option.getOr(10),
  "timeout": Env.getFloat("DB_TIMEOUT")->Option.getOr(30.0),
}

let server = {
  "host": Env.getOr("HOST", "0.0.0.0"),
  "port": Env.getInt("PORT")->Option.getOr(3000),
}

let features = {
  "debug": Env.getBool("DEBUG")->Option.getOr(false),
  "metrics": Env.getBool("ENABLE_METRICS")->Option.getOr(true),
}

5.2. Fail-Fast Validation

// Validate all required env vars at startup
let validateConfig = () => {
  let required = ["DATABASE_URL", "SECRET_KEY", "API_ENDPOINT"]
  let missing = required->Array.filter(name => !Env.has(name))

  if Array.length(missing) > 0 {
    Console.error("Missing required environment variables:")
    missing->Array.forEach(name => Console.error(`  - ${name}`))
    Process.exit(1)
  }
}

6. Runtime Detection

rescript-env automatically detects the JavaScript runtime:

Runtime Detection API Used

Deno

globalThis.Deno exists

Deno.env.get(), Deno.env.set(), etc.

Node.js / Bun

globalThis.process exists

process.env object

Browser / Unknown

Neither exists

Returns None / no-op for mutations

7. Development

7.1. Prerequisites

  • Deno 1.40+

  • ReScript 11+

7.2. Building

# Install dependencies and build
deno task build

# Watch mode for development
deno task dev

# Clean build artifacts
deno task clean

7.3. Project Structure

rescript-env/
├── src/
│   ├── Env.res          # Implementation
│   └── Env.resi         # Public interface
├── deno.json            # Deno configuration
├── rescript.json        # ReScript compiler config
├── README.adoc          # This file
├── ROADMAP.adoc         # Future plans
├── CHANGELOG.adoc       # Version history
└── LICENCE              # AGPL-3.0-or-later

8. Ecosystem

This library is part of the ReScript Full Stack ecosystem:

Library Purpose

rescript-env

Environment variable access (this library)

rescript-full-stack

Ecosystem overview and integration

More coming soon…​

See ROADMAP.adoc

9. Contributing

See CONTRIBUTING.md for guidelines.

10. Licence

SPDX-License-Identifier: AGPL-3.0-or-later

Copyright © 2025 Hyperpolymath

This program is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version.

About

Environment variable management and configuration for ReScript applications

Topics

Resources

License

Unknown, Unknown licenses found

Licenses found

Unknown
LICENCE
Unknown
LICENSE

Code of conduct

Contributing

Security policy

Stars

Watchers

Forks

Sponsor this project

Packages

No packages published

Contributors 2

  •  
  •