API Reference
createEnvSchema
Creates a type-safe environment schema and returns an environment manager instance.
import { createEnvSchema } from 'envitron';
const env = createEnvSchema((schema) => ({
PORT: schema.number(),
NODE_ENV: schema.enum(['development', 'production', 'test'] as const),
}));
// You can also have no schema and only set options
const envWithoutSchema = createEnvSchema({
// you options here
});
Options
envFile
(string | string[]): Path(s) to.env
file(s). Default:.env
, if more than one is provided, envs will be merged in file order.rootPath
(string): Root directory for env file resolution. Default:process.cwd()
, will always try to resolve from the current directly.logs
(boolean): Enable logging. Default:true
throwErrorOnValidationFail
(boolean): Throw on schema validation error. Default:true
, the absence of the .env files will not throw error.loadFromProcessEnv
(boolean): Merge envs fromprocess.env
other than from the env files. Default:false
. Envs from process.enc will have the prority over the env files
// Example with loadFromProcessEnv
const env = createEnvSchema(
(schema) => ({
PORT: schema.number(),
NODE_ENV: schema.enum(['development', 'production', 'test'] as const),
DEBUG: schema.boolean({ optional: true }),
}),
{
loadFromProcessEnv: true,
}
);
// .env file content:
// PORT=4000
// NODE_ENV=development
// DEBUG=true
// When running with: PORT=3000 node index.js
console.log(env.PORT); // 3000 (from process.env)
console.log(env.NODE_ENV); // 'development' (from .env file)
console.log(env.DEBUG); // true (from .env file)
Accessing Environment Variables
Direct Property Access
You can access environment variables directly as properties of the environment manager instance:
const port = env.PORT; // number
const nodeEnv = env.NODE_ENV; // 'development' | 'production' | 'test'
Using the Getter Method
For cases where you want to provide default values, use the get()
method:
const port = env.get('PORT', 3000); // number
const nodeEnv = env.get('NODE_ENV', 'development'); // 'development' | 'production' | 'test'
env.set(key, value)
Sets the value of an environment variable at runtime (does not persist to file). Default values are not enforced and any can be passed.
env.set('PORT', 8080);
env.all()
Returns an object with all parsed environment variables.
const allEnvs = env.all();
Error Handling
- Throws on missing required or invalid type by default (configurable).
- Logs errors if
logs: true
. - Use
optional: true
in schema to allow missing values.