commaenv
v3.2.1
Published
An environment variable parser for nodejs. Unlike dotenv, this parses environment variables instead of loading them.
Maintainers
Readme
commaenv
Unlike dotenv, this parses environment variables instead of loading them.
Why use it?
This package is useful when you want:
- typed environment values instead of raw strings
- default values for missing variables
- strict validation for strings, numbers, booleans, arrays, and literal unions
- lightweight runtime behavior without extra config
Installation
npm install commaenvBasic usage
// Use the global Env singleton
import Env from "commaenv";
// Or create your own instance
import { EnvLoader } from "commaenv";
const Env = new EnvLoader();
Env.RegisterVariable("PORT", Env.number().Default(3000));
Env.RegisterVariable("NODE_ENV", Env.string().Default("development"));
Env.RegisterVariable("DEBUG_MODE", Env.boolean());
Env.RegisterVariable("ALLOWED_ORIGINS", Env.array("string").Default(["https://example.com"]));
const port = Env.GetVariable<number>("PORT");
const nodeEnv = Env.GetVariable<string>("NODE_ENV");
const debugMode = Env.GetVariable<boolean>("DEBUG_MODE");
const origins = Env.GetVariable<string[]>("ALLOWED_ORIGINS");
console.log(port, nodeEnv, debugMode, origins);Supported types
All of the EnvDataType children share 2 common methods.
EnvDataType.prototype.Parse; // Take a string name of the environment variable and parse it.
EnvDataType.prototype.Default; // Set the default value that will be returned when EnvDataType.prototype.Parse did not get a value for the variable.String
All string parser method
EString.prototype.OnValidationFailure; // Set the string validation error message.
EString.prototype.Validator; // Set a custom sring validation function. Throws a TypeError with "Value failed validator test." as the message, or OnValidationFailure if set.
EString.prototype.MaxLength; // Set a maximum length for the string variable.
EString.prototype.MinLength; // Set a minimum length for the string variable.Example
Env.RegisterVariable("APP_NAME", Env.string().Default("my-app"));
const appName = Env.GetVariable<string>("APP_NAME");Note
Strings are returned as-is. Empty strings are treated as missing only when a non-string parser is being used.
Number
All number parser method
ENumber.prototype.Positive; // Make parser only accept positive numbers.
ENumber.prototype.Negative; // Make parser only accept negative numbers.
ENumber.prototype.Integer; // Make parser only accept negative Integers. Note that numbers end with .0 are treated as integers by the javascript engine, and therefore will be treated as integers by this method as it uses Number.isInteger to check.
ENumber.prototype.Max; // Set the maximum acceptable value of the variable.
ENumber.prototype.Min; // Set the minimum acceptable value of the variable.Example
Env.RegisterVariable("PORT", Env.number().Default(8080));
const port = Env.GetVariable<number>("PORT");Note
Accepted values are valid JavaScript numbers. If the value is not numeric, it throws a TypeError.
Boolean
Env.RegisterVariable("DEBUG", Env.boolean().Default(false));
const debug = Env.GetVariable<boolean>("DEBUG");Note
Boolean values accept the following forms:
true,1false,0
The parser normalizes case and trims whitespace before evaluating.
Literal
All literal union parser method
ELiteral.prototype.Insensitive; // Whether to ignore case when checking for valid literal string type.Example
Env.RegisterVariable("NODE_ENV", Env.literal("development", "production", "test"));
const nodeEnv = Env.GetVariable<"development" | "production" | "test">("NODE_ENV");Env.RegisterVariable("HTTP_STATUS", Env.literal(200, 201, 204).Default(204));
const status = Env.GetVariable<200 | 201 | 204>("HTTP_STATUS");Note
Env.literal() accepts a finite set of allowed values. It supports either strings or numbers, and rejects anything outside that set.
For string literals, values are checked after trimming whitespace. For numeric literals, the environment value is parsed as a number before being matched against the allowed values.
Array
All array parser method
EArray.prototype.Parser; // Set a custom array parser for EArray.prototype.Parse, which uses JSON.parse by default.
EArray.prototype.Transformer; // Add a custom transformer method to transform the result array, this function is called once for every item in the array.Example
Env.RegisterVariable("FEATURES", Env.array("string").Default(["auth", "billing"]));
const features = Env.GetVariable<string[]>("FEATURES");Note
Supported array element types are:
Env.array("string")Env.array("number")
Registering variables
Env.RegisterVariable("TOKEN");
const token = Env.GetVariable<string>("TOKEN");If you do not pass a type, the package defaults to a string parser.
Defaults and missing values
When a variable is missing or empty for non-string types, the parser will fall back to the default value if one has been provided:
Env.RegisterVariable("CACHE_TTL", Env.number().Default(60));If the value is missing and no default exists, it throws a TypeError.
API summary
Env.RegisterVariable(name, type?)Env.GetVariable<T>(name)Env.string()Env.number()Env.boolean()Env.literal("development", "production")Env.literal(200, 201, 204)Env.array("string")Env.array("number")
Notes
- This library does not load
.envfiles. - It only reads from the current
process.envobject. - The package is designed to be small, explicit, and strict.
- Default import gives you the EnvLoader singleton, while
import { EnvLoader } from "commaenv";gives you the EnvLoader class so you can create an instance for yourself.
License
This project is licensed under the GPL-3.0-only license.
Todo
- ~~add literal type support~~
- ~~make GetVariable infer the type of the variable, if that's even possible~~ currently not possible without major changes to the lib
- MAYBE add a tuple parser
