Enveloped
Ir a la página
Enveloped is an alternative for dotenv
, more feature-rich out of the box, with pretty simple configurations.
Requirements
At the moment, Enveloped it's a zero-dependencies package.
The .env file must be in JSON
Installation and usage
In an initialized project, run:
npm i enveloped
Then, on the main file, add this lines:
import enveloped from "enveloped";
enveloped.init();
I strongly recommend to put them at the top of all.
Now, every time you need an env variable, use the process.var
function:
/* .env content
{
"CURRENT": {
"STAGE": "testing"
}
}
*/
let envStage1 = process.var("CURRENT.STAGE");
console.log(envStage1); //-> testing
// Also valid
envStage = process.var("CURRENT").STAGE;
const { STAGE } = process.var("CURRENT");
Configuration
You can pass a custom configuration through enveloped.init(config)
, where config is an object with:
-
rootPath
: directory path where the.env
file/s are located. (default:process.cwd()
) -
filename
: JSON env file name. (default:.env
) -
type
: iffilename
is not supplied, this property will load append to the file name a type. It's a nice-to-have when working with different env files, depending on the stage. (default: empty string) (example:type: "development"
, loaded file:.env.development
) -
secretKey
: the secret key used to encrypt the.env
content. It must have only 32 characters (default: it generates a random on initialization). -
debugMode
: if something is not working correctly, this mode will output some help logs to the console. (default:false
)
All of this properties are optional. It's important to notice that type
will be ignored if filename
is supplied.
How it works?
When you call enveloped.init()
, the script will:
- Merge the configs, in case you supplied a custom one.
- Setup
debugMode
if it's true. - Configure the
process
node object, adding thevar
function. - Setup the secret key for the encryption.
- Get, validate and parse the env file.
- Encrypt a minified version of the env file to a hash.
- Save the hash in a env variable called
NODE_ENVELOPED
.
As you can see, there will only be one env variable, containing a hash.
Now, every time you call process.var("<varName>")
, it will:
- Read the
NODE_ENVELOPED
hash. - Decrypt it and convert it to an object.
- Search the var.
- Return the value if it finds it, or null if not.
Of course, the varName
can be chained with dots like: "KEY.CHAINED"
, to refer a nested key.
For an in-depth guide or reference, you can visit the Wiki.
Licence
Enveloped is under Mozilla Public Licence 2.0
so, obviously, it is open-source. More info at Mozilla MPL 2.0
Made by Juan Saez