Node.js

Use Dotenvx with Node.js.

Install

Get the Dotenvx Node.js SDK.

$ npm install @dotenvx/dotenvx

Encrypt

Start with a secret value in your .env file, like:

# .env
HELLO="Secret"

Encrypt it with a single command.

$ npx dotenvx encrypt
◈ encrypted (.env)

The values become ciphertext and only your private key can unlock them.

# .env
DOTENV_PUBLIC_KEY="0220d830351410598be484f43a7b07097e09851f50426832876e8b5815a1752990"

HELLO="encrypted:BHLTACNJMr00nTG6yXpkCyWFKF/MY0ajN855tg3uVtKopTe2AGzSkQlcPd21pTOT3Ci8IKrdIg2TMZFoq1mDR6yb06QCRvqHXtpkZkAHYCEHfeWqqC8tMFovcYq5JS2uZSrC/qUGDA=="

Commit

Commit your encrypted .env files with your code. It's safe. Now you can securely share secrets through git.

$ git add .env
$ git commit -m "encrypt .env"

Ship

Load your secrets before your app uses them. Create an index.js file:

// index.js
require('@dotenvx/dotenvx').config()

console.log(`Hello ${process.env.HELLO}`)

Run your app:

$ node index.js
⟐ injected env (2) from .env
Hello Secret

Dotenvx uses your private key to decrypt and inject your secrets just-in-time to your code.

Deploy

Find your private key with the keypair command.

$ npx dotenvx keypair
{"DOTENV_PUBLIC_KEY":"0220d830351410598be484f43a7b07097e09851f50426832876e8b5815a1752990","DOTENV_PRIVATE_KEY":"b37dbad0e00206f31486c4f44f8cc7abf2f1be96d5ba352eb791122b5e131bbf"}

Deploy your code and encrypted .env file, install your npm dependencies, and set DOTENV_PRIVATE_KEY on your production environment. Keep .env.keys on your local machine.

And run your app:

$ node index.js
⟐ injected env (2) from .env
Hello Secret

Dotenvx uses your private key to decrypt and inject your secrets just-in-time, but this time with the private key stored on your server.

Production

Give production its own secrets by creating a .env.production file:

# .env.production
HELLO="Production"

Encrypt it:

$ npx dotenvx encrypt -f .env.production
◈ encrypted (.env.production)

Commit it:

$ git add .env.production
$ git commit -m "encrypt .env.production"

Find the matching private key with npx dotenvx keypair -f .env.production. This time set DOTENV_PRIVATE_KEY and DOTENV_FILE on your server.

Run it:

$ node index.js
⟐ injected env (2) from .env.production
Hello Production

Dotenvx needs DOTENV_FILE so it knows to load .env.production. Same code, but this time, production secrets.

You can even compose multiple environments like this with DOTENV_FILE=.env.production,.env for example. Comma separate them.

Conclusion

You've encrypted a .env file, committed it to git, and loaded its secrets with the Node.js SDK. You've also learned how to set a private key on your server and load different secrets for production without changing your code.

Your secrets now travel with your code, and each environment needs just one private key to use them.