env-safe
env-safe is module that loads that loads environment variables from a .env
file into process.env
with type-safe. And can also validate the type of process.env
. env-safe is dependent on dotenv and reflect-metadata.
Install
npm intall env-safe --save
Or installing with yarn? yarn add env-safe
Usage
Turn on emitDecoratorMetadata
, experimentalDecorators
in tsconfig.json:
{
"compilerOptions": {
"emitDecoratorMetadata": true,
"experimentalDecorators": true
...
}
...
}
Create a .env
file in the root of your project:
DATABASE_HOST="localhost"
DATABASE_PORT=3306
Use env-safe to create config class:
import { Key, Env } from 'env-safe';
@Env()
export class Config {
@Key()
static DATABASE_HOST: string;
@Key()
static DATABASE_PORT: number;
}
That's it. Just use the newly created config class:
import { Config } from './config.ts';
mysql.connect({
host: Config.DATABASE_HOST, // String("localhost")
port: Config.DATABASE_PORT // Number(3306)
});
Documentation
Comment
Comments may be added to your file on their own line or inline:
# This is a comment
DATABASE_HOST="localhost" # comment
DATABASE_PASSWORD="can-define-with-#"
Comments begin where a #
exists, so if your value contains a #
please wrap it in quotes.
Default value
Set default value to config class property:
@Env()
export class Config {
@Key({ default: 'localhost' })
static DATABASE_HOST: string;
@Key({ default: 3306 })
static DATABASE_PORT: number;
}
Type-Safe
Since the provided .env
does not contain all the variables defined in config class, an exception is thrown:
DATABASE_HOST=
DATABASE_PORT="wrong data"
@Env()
export class Config {
@Key()
static DATABASE_HOST: string; // Not defined Error
@Key()
static DATABASE_PORT: number; // NaN Error
@Key()
static DATABASE_USER: string; // Not defined Error
}
$ node dist/index.js
ERROR: DATABASE_USER is not defined in .env
.env
path
Change Can change .env
path in your project:
$ ls
development.env stagging.env production.env
@Env({ path: 'development.env' })
export class Config {
...
}
Multiple config class
Can define multiple config class:
AWS_SECRET_KEY="secret key"
S3_BUCKET="bucket name"
@Env()
export class AWSConfig {
@Key()
static AWS_SECRET_KEY: string; // String("secret key")
}
@Env()
export class S3Config {
@Key()
static S3_BUCKET: string; // String("bucket name")
}
Contributing Guide
See CONTRIBUTING.md