Embedded Environment Variables
The Environment Manager provides two convenient ways to access your environment variables:
Direct Property Access
You can access environment variables directly as properties of the environment manager instance. This provides a clean and intuitive way to access your configuration:
const env = createEnvSchema((schema) => ({
DATABASE_URL: schema.string(),
PORT: schema.number(),
DEBUG: schema.boolean()
}));
// Access variables directly
console.log(env.DATABASE_URL); // "postgres://localhost:5432/mydb"
console.log(env.PORT); // 3000
console.log(env.DEBUG); // true
Using the Getter Method
For cases where you want to provide default values or handle missing variables, you can use the get()
method:
const env = createEnvSchema((schema) => ({
DATABASE_URL: schema.string(),
PORT: schema.number(),
DEBUG: schema.boolean()
}));
// Access with default values
console.log(env.get('DATABASE_URL', 'postgres://localhost:5432/default'));
console.log(env.get('PORT', 8080));
console.log(env.get('DEBUG', false));
Type Safety
Both methods provide full TypeScript type safety based on your schema definition. The direct property access will infer the correct types from your schema, while the getter method will ensure the default value matches the expected type.
Best Practices
- Use direct property access for required variables that you know will always be present
- Use the getter method when you need to provide fallback values
- The getter method is particularly useful in development environments where some variables might be optional