Use dotenvx with Heroku

Use dotenvx with Heroku

Initial setup

Add a Procfile to run your app.

# Procfile
web: node index.js

Install the necessary web server libraries in the language of your choice.

npm install express --save

Create a simple Hello World program.

// index.js
const express = require('express')
const app = express()
const PORT = process.env.PORT || 3000

app.get('/', (req, res) => {
  res.send(`Hello ${process.env.HELLO || ''}`)

app.listen(PORT, () => {
  console.log(`Server running on port:${PORT}`)

Commit to code and push to Heroku.

git commit -am "initial commit"
heroku create
git push heroku

Once deployed, your app will say 'Hello [blank]' as it doesn't have a way to access the environment variable yet. Let's do that next.

Run dotenvx

Install dotenvx via the dotenvx buildpack.

heroku buildpacks:add

Update your Procfile to use dotenvx.

# Procfile
web: dotenvx run -- node index.js

Add production environment

Create .env.production in the root of your project.

# .env.production

Encrypt production

dotenvx encrypt -f .env.production

Your .env.production file is now encrypted, and you have a .env.keys file.


#/            public-key encryption for .env files          /
#/       [how it works](     /

# .env.production


#/ private decryption keys. DO NOT commit to source control /
#/     [how it works](       /

# .env.production

We're ready to inject the encrypted .env.production secrets into the app on boot.

Set decryption key

Set DOTENV_PRIVATE_KEY_PRODUCTION on Heroku using the production key in your .env.keys file. We'll use the Heroku cli, but you can also use their dashboard.

heroku config:set DOTENV_PRIVATE_KEY_PRODUCTION='424d0ea072eb17c6bee9b4b42ff6333513cf128ea3d5d60ccf79246ca7c3f786'


git push heroku

Your app restarts and env is successfully injected using the encrypted contents of .env.production.

heroku[web.1]: Starting process with command `dotenvx run -- node index.js`
app[web.1]: [[email protected]] injecting env (2) from .env.production
app[web.1]: Server running on port:7521/

Visit your url and it says Hello production.

Great job! That's pretty much it. See the bonus section(s) below to go a little deeper.


Try changing the value of .env.production to your name.

npm run dotenvx -- set HELLO Mot

Commit .env.production safely to code and redeploy.