rolodato / dotenv-safe Goto Github PK
View Code? Open in Web Editor NEWLoad environment variables from .env and ensure they are all present
Home Page: https://www.npmjs.com/package/dotenv-safe
License: MIT License
Load environment variables from .env and ensure they are all present
Home Page: https://www.npmjs.com/package/dotenv-safe
License: MIT License
We're currently not using this util because it doesn't support to encrypt the environment file as it contains sensitive information. Some our clients want to hide the information as much as possible for normal user. For now, we are using a helper class to load environment variables supports encrypt/decrypt the file based on the secret key (i.e. a .dat file stored somewhere that the app should know and read it contents) - using cryptoJS.AES.encrypt(input, key), cryptoJS.AES.decrypt(encryptedStr, key)
Hence, I would like to raise this issue to know other approaches and looking for this util can be updated and support that kind of feature.
While I am using Typescript process.env
value type is string | undefined
. It forces me to write additional code to check if my value from process.env is undefined or not, before using it. If I am using dotenv-safe, I should be able to avoid writing those extra code. Am I correct? But, I am unable to. Because of type issues. Can we solve it?
globals.d.ts
interface ProcessEnv {
[key: string]: string | undefined;
}
It would be convenient to declare the default values in .env.example. This will allow not to duplicate in the field .env and simplify deployment.
Is there any way to configure which specific values are allowed to be empty? For example, on my local machine my DB password is ''
(empty string), but I want to ensure that we don't accidentally set a production DB password, or other ENV variables to empty string, since those could cause failure.
Perhaps this could be implemented with allowEmptyValues
to either be a boolean or an array of env keys?
require('dotenv-safe').config({ allowEmptyValues: [ 'DB_PASSWORD' ] })
.env.example
seems to be a much more common filename than .env.sample
in both Ruby and Node land. Perhaps consider using it as the default?
EDIT: Also this module is genius.
Hello, I'm an avid user of this module. Thanks for making and maintaining it.
I often find that this module causes issues in CI environments where the env configuration is not always the same as development. So our team (@electron) usually ends up doing this:
if (!process.env.CI) require('dotenv-safe').load()
All the CI providers set this environment variable.
Would you open to making this a built-in feature in dotenv-safe? Maybe an option?
Edit: One could even argue that because this tool is intended for use in development
, it could automatically abort if process.env.CI
is detected. That would of course be a breaking change and would require a major version bump.
Custom paths for .env files is not supported by dotenv-safe.
`var dotenv = require('dotenv-safe');
dotenv.load({ path: '../../.env'});`
Will result in an exception being thrown even if the file '../../.env.example' exists.
In dotenv you can load multiple env files, by calling .config({}) multiple times with different 'path' parameters.
eg I can do:
dotenv.config({ path: '.env'}); // this contains non-sensitive variables shared by all environments & devs
dotenv.config({ path: '.env.local'}); // this contains dev- or environment-speciffic vars
With dotenv-safe I can't seem to achieve the same behaviour.
dotenv.config({ path: '.env', example: '.env.template' });
dotenv.config({ path: '.env.local', example: '.env.template' });
I get errors about template vars missing from .env (since it only contains SOME vars - correctly)
dotenv.config({ path: '.env', example: '' });
dotenv.config({ path: '.env.local', example: '.env.template' });
It complains env.example doesnt exist
let dotenv = require('dotenv');
let dotenvsafe = require('dotenv-safe');
dotenv.config({ path: '.env' });
dotenvsafe.config({ path: '.env.local', example: '.env.template' });
But it just feels ugly.
Any advice?
It would be cool if you could do:
dotenv.config({ path: '.env', example: null }); // import files as with plain dotenv
dotenv.config({ path: '.env.local', example: null }); // import files as with plain dotenv
dotenv.config({ example: '.env.template' }); // run the check here
There is the error on new version. MissingEnvVarsError.js is missed in package.json file list, so we didn't publish the file.
I'm not sure if this is somehow related to #34, as I'm new to this stack.
I'm testing code that includes a call to dotenvSafe.load({ ... })
. I don't want to keep dummy .env
and .env.example
files together with my tests just to make them work.
I'm using Jest but I assume a similar approach would apply for mocha etc.
How do you guys deal with this?
If any test that renames files fails, it makes every test that runs after that fail until all the test files are back to their initial state. The tests should have proper before/after steps to prevent this.
I get the following error when a .env
file is not present, but the variables are still available in the environment:
{ Error: ENOENT: no such file or directory, open '.env'
at Error (native)
at Object.fs.openSync (fs.js:640:18)
at Object.fs.readFileSync (fs.js:508:33)
at Object.config (/pipeline/source/node_modules/dotenv/lib/main.js:30:37)
at Object.config (/pipeline/source/node_modules/dotenv-safe/index.js:25:16)
at Object.<anonymous> (/pipeline/source/webpack.config.js:1:86)
at Module._compile (module.js:570:32)
at Object.Module._extensions..js (module.js:579:10)
at Module.load (module.js:487:32)
at tryModuleLoad (module.js:446:12) errno: -2, code: 'ENOENT', syscall: &#Hash: 02f39e618514ebe1e2c2
The error does not block the build of the project from proceeding (i.e. fail with exit code != 1), but it is a bit misleading.
Setup:
Since the update to 5.0.0, I noticed you removed the config.js file and integrated it into index.js. This breaks for me (and probably a lot of other people) who used to run:
node -r dotenv-safe/config app.js
This wasn't mentioned in the changelog but I would love it if you would consider reintroducing config.js so that I won't have to change the way we run our applications. :)
This doesn't appear to work with the --require
flag, as dotenv does. I'm still in the process of debugging to figure out why and see if I can provide a fix, but I figured I'd open a ticket now.
Hi
Is there an option to validate that all the variables in .env are also in .env.example ?
example :
.env
A=1
B=2
C=
.env.example:
A=
B=
this should throw an error
Make one retroactively.
Add option allowUnusedValues
and UnusedEnvVarsError
If a variable is not defined in the example file, but present in the environment, disabling this option will throw an error after loading. Defaults to true.
Hi there! Thanks for dotenv-safe
!
Would it be possible to upgrade the dotenv
dependency? It is currently set at ^8.2.0
, but the latest version is 16.0.0
.
An alternative to upgrading dotenv
would be to move dotenv
to peerDependencies
and accept any version above 8.2.0
, which would allow consuming projects to choose their version.
This is breaking the behavior described here: https://github.com/motdotla/dotenv/tree/fdd0923e82e12a6e29b65898990201857141e75d#what-happens-to-environment-variables-that-were-already-set
We will never modify any environment variables that have already been set. In particular, if there is a variable in your .env file which collides with one that already exists in your environment, then that variable will be skipped. This behavior allows you to override all .env configurations with a machine-specific environment, although it is not recommended.
Hi, @rolodato. You are making an amazing package. Let's make it better with Continues Integration.
This issue can not to been resolved with pull requests only. But I can help as consultant for any questions.
This would prevent the test
folder from being published to NPM. I can submit a PR if you would like.
dotenv 5.0 is out:
https://github.com/motdotla/dotenv/releases/tag/v5.0.0
node version: v10.20.1
dotenv-safe version: 8.2.0
I set the allowEmptyValues
to true but I'm still getting the MissingEnvVarsError.
Here is my code:
require('dotenv-safe').config({
allowEmptyValues: true,
path: path.join(__dirname, '../../.env'),
example: path.join(__dirname, '../../.env.example'),
});
I couldn't figure out what I'm missing here. Thank you for your help!
As of v4 if a variable is present in .env.example
and missing from .env
the name is not returned.
Test steps to recreate (output truncated slightly for clarity):
# Setup example project
$ mkdir dotenv-safe-test && cd $_
$ npm init -y
$ echo $'EXAMPLE_TEST_VAR_1=\nEXAMPLE_TEST_VAR_2=' > .env.example
$ echo $'EXAMPLE_TEST_VAR_1=true' > .env
$ echo $'"use-strict";\nrequire("dotenv-safe").load();\nconsole.log("Testing.");' > index.js
# NOTE - no variable names.
$ npm install [email protected]
$ node index.js
Error
at Object.config (/Users/mwatson/Desktop/dotenv-safe-test/node_modules/dotenv-safe/index.js:37:19)
# NOTE - variable names.
$ npm install [email protected]
$ node index.js
Error: Missing environment variables: EXAMPLE_TEST_VAR_2
Line 46 in 78f290e
parse()
function is used directly from dotenv
, without doing the checking for the entries in the .env.example
file. Add the checkings so it could be used in arbitrary objects instead of only process.env
.
It would be great if the error thrown at https://github.com/rolodato/dotenv-safe/blob/master/index.js#L32 could be custom or even a custom callback function.
so instead of a "ugly" error, a custom message could be printed.
this:
Error: Missing environment variables: URL
at Object.module.exports.config (node_modules/dotenv-safe/index.js:32:19)
at Object. (config/index.js:16:23)
at Module._compile (module.js:541:32)
at Object.Module._extensions..js (module.js:550:10)
at Module.load (module.js:458:32)
at tryModuleLoad (module.js:417:12)
at Function.Module._load (module.js:409:3)
at Module.runMain (module.js:575:10)
at run (node.js:348:7)
at startup (node.js:140:9)
could become this:
Please setup the variable
URL
at your.env
file. You can use yourenv.example
as a template.
maybe the callback function could be called with the missing
variable and the original options
so we could write something like:
const config = dotenv.load((err) =>
console.log(`Please setup the variables ${err.missing} at your .env file.
You can use your ${err.options.sample} as a template.`)
);
In the description for dotenv/config
, it includes the ability to set dotenv
configuration options via env var: https://www.npmjs.com/package/dotenv
DOTENV_CONFIG_<OPTION>=value node -r dotenv/config your_script.js
However, this issue - motdotla/dotenv#423 - explains that only works when
using
dotenv/config
(usually via preloading)
However, the code for dotenv-safe makes a requires call to dotenv
not dotenv/config
: https://github.com/rolodato/dotenv-safe/blob/master/index.js#L3
And the code for dotenv-safe/config
(https://github.com/rolodato/dotenv-safe/blob/master/config.js) replicates the CLI config (https://github.com/motdotla/dotenv/blob/master/lib/cli-options.js), but not the newer ENV options (https://github.com/motdotla/dotenv/blob/master/lib/env-options.js).
This means that the environment variables (e.g. DOTENV_CONFIG_PATH
) are not recognised when using dotenv-safe/config
. And unfortunately I cannot use the CLI configuration options because I'm running webpack, which fails if it there is a CLI option that it doesn't recognise.
These are the scripts that I've tried:
DOTENV_CONFIG_PATH=../../.env node -r dotenv/config $(yarn bin webpack)
- this loads the correct .env file, doesn't perform the safety check, and then runs webpack with the variables from the .env file.
DOTENV_CONFIG_PATH=../../.env node -r dotenv-safe/config $(yarn bin webpack)
- this does not load the correct .env file and then fails on the safety check due to missing env vars.
For now, I can require dotenv-safe
in the entry point to my application instead of using dotenv-safe/config
. But, it would be nice to be able to use the newer functionality.
I really like this package as it won't allow your program to run without environment variables. But sometimes there are sane defaults that don't require being overridden, like the port number for the database. For those cases, this library can optionally read a .env.default
file and fill values from that if they aren't defined otherwise.
I see that #30 was closed with a very good reason, but in this case you'd never put a default value for things like usernames and passwords. Only for sane defaults.
With environment variables defined via .env
, it'd be useful to support the following:
node -r 'dotenv-safe/register' somescript.js
This way the environment is set without customizing somescript.js
to include require('dotenv-safe').load()
A declarative, efficient, and flexible JavaScript library for building user interfaces.
๐ Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.
TypeScript is a superset of JavaScript that compiles to clean JavaScript output.
An Open Source Machine Learning Framework for Everyone
The Web framework for perfectionists with deadlines.
A PHP framework for web artisans
Bring data to life with SVG, Canvas and HTML. ๐๐๐
JavaScript (JS) is a lightweight interpreted programming language with first-class functions.
Some thing interesting about web. New door for the world.
A server is a program made to process requests and deliver data to clients.
Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.
Some thing interesting about visualization, use data art
Some thing interesting about game, make everyone happy.
We are working to build community through open source technology. NB: members must have two-factor auth.
Open source projects and samples from Microsoft.
Google โค๏ธ Open Source for everyone.
Alibaba Open Source for everyone
Data-Driven Documents codes.
China tencent open source team.