Load environment variables from encrypted .env.vault files, with NodeJS 🚀.
Heroku with Express
Learn how to make Heroku, Express, and Dotenv Vault work together. This tutorial assumes you have already created a .env
file and synced it.
You can find a complete example repo here.
Deploy to Heroku
Add a Procfile to run your Express app.
web: node index.js
Your index.js file should look something like this.
// index.js
const PORT = process.env.PORT || 5000
const express = require('express')
const app = express()
app.listen(PORT, () => {
console.log(`Running on port ${PORT}.`)
})
app.get('/', (req, res) => {
res.send(`Hello ${process.env.HELLO}`)
})
Commit that to code and push it to Heroku.
$ heroku create
$ git push heroku
Your app will say ‘Hello undefined’.
Nice. Next, let’s configure our environment variables using Dotenv Vault.
Require dotenv
Install dotenv.
$ npm install dotenv --save
Then require it as early as possible in your code.
// index.js
require('dotenv').config()
console.log(process.env) // for debugging purposes. remove when ready.
const PORT = process.env.PORT || 5000
const express = require('express')
const app = express()
...
Create your .env file
# .env
HELLO="Development"
Test it is working locally.
$ node index.js
{
HELLO: 'Development'
}
Running on port 5000
It says Hello Development at http://localhost:5000.
Build .env.vault
First set a production value for when we deploy. I set it to HELLO=Production. Run dotenv-vault open to edit production values.
$ npx dotenv-vault open production
Then build your localized encrypted .env.vault file.
$ npx dotenv-vault build
Great! Commit your .env.vault
file to code. It is safe and necessary to do so.
Set DOTENV_KEY
Lastly, set the DOTENV_KEY on Heroku.
Run npx dotenv-vault keys production to get your production decryption key.
$ npx dotenv-vault keys production
remote: Listing .env.vault decryption keys... done
dotenv://:[email protected]/vault/.env.vault?environment=production
Visit your Heroku Project’s Environment Variables under settings of your heroku application and set it.
Commit and push
That’s it!
Commit those changes safely to code and deploy to Heroku.
When the app boots, it will recognize the DOTENV_KEY
, decrypt the .env.vault file, and load the production environment variables to ENV
. If a DOTENV_KEY
is not set (like during development on your local machine) it will fall back to regular dotenv.
You’ll know things worked correctly if you see the message ‘Loading env from encrypted .env.vault’ in your heroku logs.