How Environment Variables Are Parsed
Envitron supports two file formats: traditional .env files and JSON files. The format is automatically detected based on the file extension and content.
File Format Detection
Envitron automatically detects the file format:
- JSON files (
.jsonextension): Parsed as JSON with native types - Traditional .env files (
.envor other): Parsed with .env syntax rules
// Uses JSON parsing
createEnvSchema(schema, { envFile: '.env.json' });
// Uses .env parsing
createEnvSchema(schema, { envFile: '.env' });
// Merges both formats
createEnvSchema(schema, { envFile: ['.env', '.env.json'] });
JSON Parsing
JSON files are parsed with native JavaScript types:
- Strings:
"value" - Numbers:
123,3.14 - Booleans:
true,false - Arrays:
["item1", "item2"],[1, 2, 3] - Objects:
{ "key": "value" } - Null: Treated as
undefinedin the schema
JSON Example
{
"PORT": 3000,
"DEBUG": true,
"HOSTS": ["localhost", "127.0.0.1"],
"database": {
"host": "localhost",
"port": 5432
}
}
const env = createEnvSchema(
(schema) => ({
PORT: schema.number(), // 3000 (native number)
DEBUG: schema.boolean(), // true (native boolean)
HOSTS: schema.array(schema.string()), // ['localhost', '127.0.0.1']
database: schema.object({
host: schema.string(),
port: schema.number(),
}),
}),
{ envFile: '.env.json' }
);
JSON Validation Rules
- Root must be an object (not an array or primitive)
- All values are validated against the schema
- Nested objects and arrays are supported
- Type mismatches trigger validation errors
See JSON Environment Files for detailed examples.
Traditional .env Parsing
Environment variables from .env files are parsed as strings and converted based on the schema type:
- Booleans:
"true","false" - Numbers:
"123","3.14" - Enums: Restrict to a set of allowed values
- Strings: Handles quotes, spaces, special characters, escaping
- Arrays: CSV format (comma-separated values)
Parsing Rules
- Double quotes (
"): Supports escape sequences (e.g.,\n,\t,\").#is treated as a literal character. - Single quotes (
'): Takes the literal value, no escape sequences.#is treated as a literal character. - Unquoted: Value is trimmed.
#starts a comment. No escape sequences. - Empty values: If a variable exists but has no value (e.g.,
EMPTY=), it returnsundefined.
Example
BOOLEAN=true
NUMBER=123
CSV="foo,bar,baz"
QUOTED_STRING="hello world"
ENUM_ENV=production
DOUBLE_QUOTED_ESCAPES="line1\nline2"
SINGLE_QUOTED_LITERAL='line1\nline2'
UNQUOTED_SPACES= some value # comment
EMPTY=
ONLY_SPACES=
HASH_VALUE="value#notacomment"
UNQUOTED_HASH=foo # this is a comment
const env = createEnvSchema(schema => ({
BOOLEAN: schema.boolean(),
NUMBER: schema.number(),
CSV: schema.array(),
QUOTED_STRING: schema.string(),
ENUM_ENV: schema.enum(['development', 'production', 'test'] as const),
DOUBLE_QUOTED_ESCAPES: schema.string(),
SINGLE_QUOTED_LITERAL: schema.string(),
UNQUOTED_SPACES: schema.string(),
EMPTY: schema.string(),
ONLY_SPACES: schema.string(),
HASH_VALUE: schema.string(),
UNQUOTED_HASH: schema.string(),
}));
console.log(env.get('BOOLEAN')); // true
console.log(env.get('NUMBER')); // 123
console.log(env.get('CSV')); // ['foo', 'bar', 'baz']
console.log(env.get('QUOTED_STRING')); // 'hello world'
console.log(env.get('ENUM_ENV')); // 'production'
console.log(env.get('DOUBLE_QUOTED_ESCAPES')); // 'line1\nline2' (with actual newline)
console.log(env.get('SINGLE_QUOTED_LITERAL')); // 'line1\nline2' (literal backslash-n)
console.log(env.get('UNQUOTED_SPACES')); // 'some value'
console.log(env.get('EMPTY')); // undefined
console.log(env.get('ONLY_SPACES')); // undefined
console.log(env.get('HASH_VALUE')); // 'value#notacomment'
console.log(env.get('UNQUOTED_HASH')); // 'foo'
Format Comparison
| Feature | Traditional .env | JSON |
|---|---|---|
| Native types | ❌ All strings | ✅ Yes |
| Nested objects | ❌ No | ✅ Yes |
| Arrays | ✅ CSV only | ✅ Native arrays |
| Comments | ✅ Yes (#) | ❌ No |
| Escape sequences | ✅ Yes | ✅ Yes |
| Type safety | ⚠️ After parsing | ✅ Native |
Notes
- Enums: If the value is not in the allowed set, an error is thrown at load time.
- Quoting (.env files): Use double quotes for escape sequences, single quotes for literal values, and unquoted for trimmed values with comment support.
- Empty values (.env files): Any variable present in the
.envfile but with no value will returnundefined. - JSON validation: JSON files must have a top-level object. Arrays and primitives at the root level are not supported.