Heroku

Use dotenvx with Heroku

Find code examples for this guide on GitHub.

Initial setup

Add a Procfile and a simple Hello World app, then push to Heroku.


# Procfile
web: node index.js

// 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}`)
})

Run dotenvx

Install Dotenvx as an application dependency so Heroku's Node.js build installs the native CLI for its platform:


$ npm install @dotenvx/dotenvx

Add the start script to package.json, keeping your other scripts:


{
  "scripts": {
    "start": "dotenvx run -f .env.production --strict -- node index.js"
  }
}

Update your Procfile:


web: npm start

Add production environment


# .env.production
HELLO="production"

Encrypt production


$ npx dotenvx encrypt -f .env.production

Commit .env.production. Do not commit .env.keys. Keep private keys somewhere safe like 1Password or Armor ⛨.

Set decryption key

Set DOTENV_PRIVATE_KEY_PRODUCTION on Heroku to the production key from .env.keys, and set DOTENV_FILE to .env.production.


$ heroku config:set DOTENV_PRIVATE_KEY_PRODUCTION='your-private-key' DOTENV_FILE='.env.production'
$ git push heroku

Your app restarts and env is injected from the encrypted .env.production file.

markdown