Dotenv Module
The std/dotenv module loads environment variables from .env files and provides runtime access to environment variables.
Import
Section titled “Import”import { dotenv } from "std/dotenv"Functions
Section titled “Functions”dotenv.load(path?: string): bool
Section titled “dotenv.load(path?: string): bool”Load environment variables from a .env file. Defaults to ".env" in the current directory. Returns true on success.
dotenv.load() // Load from .envdotenv.load(".env.local") // Load from a specific filedotenv.get(key: string, defaultValue?: string): string
Section titled “dotenv.get(key: string, defaultValue?: string): string”Get an environment variable by key. Returns the value, the default, or null if not found.
const port = dotenv.get("PORT", "3000")const dbUrl = dotenv.get("DATABASE_URL")dotenv.set(key: string, value: string): void
Section titled “dotenv.set(key: string, value: string): void”Set an environment variable at runtime.
dotenv.set("NODE_ENV", "production")dotenv.has(key: string): bool
Section titled “dotenv.has(key: string): bool”Check if an environment variable exists.
if (dotenv.has("API_KEY")) { println("API key configured")}dotenv.all(): map
Section titled “dotenv.all(): map”Get all loaded environment variables as a map.
const env = dotenv.all()for (var key in env) { println(key + "=" + env[key])}dotenv.require(key: string): string
Section titled “dotenv.require(key: string): string”Get a required environment variable. Throws an Error if the variable is not set.
try { const secret = dotenv.require("JWT_SECRET")} catch (err) { println("Missing required config: " + err.message)}Function Reference
Section titled “Function Reference”| Function | Description |
|---|---|
dotenv.load(path?) | Load variables from .env file |
dotenv.get(key, default?) | Get a variable (with optional default) |
dotenv.set(key, value) | Set a variable at runtime |
dotenv.has(key) | Check if a variable exists |
dotenv.all() | Get all variables as a map |
dotenv.require(key) | Get a required variable (throws if missing) |
Example: Server Configuration
Section titled “Example: Server Configuration”import { dotenv } from "std/dotenv"import { createServer, Request, Response } from "std/http"
// Load environment variablesdotenv.load()
const port = int(dotenv.get("PORT", "3000"))const secret = dotenv.require("JWT_SECRET")
const app = createServer()
app.get("/health", function(req: Request, res: Response): Response { return res.json('{"status": "ok"}')})
app.listen(port).env File Format
Section titled “.env File Format”# Comments start with #PORT=3000DATABASE_URL=postgres://localhost/mydbJWT_SECRET=my-super-secret-keyDEBUG=true