Fly.io with Express
In this tutorial, learn how to integrate Dotenv Vault with Fly.io and an Express application.
You can find a complete example repo here.
Deploy to Fly.io
Deploy your Express app to fly.io.
1
flyctl launch
Here’s an example of a simple Hello World Express app that runs on Fly.io.
1
2
3
4
5
6
7
8
9
10
11
12
// 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}`)
})
That will deploy your Express app to Fly’s infrastructure.
Install dotenv-vault
Create your local .env
file.
1
HELLO="Development"
Install dotenv-vault-core.
1
$ npm install dotenv-vault-core --save
Require it as early as possible in your Express application.
1
2
3
4
5
6
7
8
// index.js
require('dotenv-vault-core').config()
console.log(process.env) // for debugging purposes. remove when ready.
const PORT = process.env.PORT || 5000
const express = require('express')
const app = express()
...
Test that it is working locally.
1
2
3
4
5
$ 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.
1
$ npx dotenv-vault open production
Then build your localized encrypted .env.vault file.
1
$ npx dotenv-vault build
Great! Commit your .env.vault
file to code. It is safe to do so. It is a localized encrypted vault of your environment variables.
Set DOTENV_KEY
Lastly, set the DOTENV_KEY on Fly.io.
Run npx dotenv-vault keys production to get your production decryption key.
1
2
3
4
$ npx dotenv-vault keys production
remote: Listing .env.vault decryption keys... done
dotenv://:key_1234@dotenv.org/vault/.env.vault?environment=production
Set it on Fly.io.
1
$ flyctl secrets set NODE_ENV=production DOTENV_KEY='dotenv://:key_1234@dotenv.org/vault/.env.vault?environment=production'
WARNING: The single apostrophe is important. Otherwise, Fly.io will truncate the DOTENV_KEY incorrectly and decryption will not work.
That’s it!
Commit your changes to code and run:
1
$ flyctl deploy
When the deploy runs, it will recognize the DOTENV_KEY
, decrypt the .env.vault file, and load the production environment variables to Fly.io. If a DOTENV_KEY
is not set (like during development on your local machine) it will fall back to regular dotenv.