Problem statement
You have a node application that needs to support variances in environment variables; however, this application is hosted in Elasticbeanstalk. This post will show how to enable environment variable support for your node application.
Why
Environment variables allows flexibility to your code without having to have hard code values that could change for various reasons:
- You don’t control the values
- Third party integrations
- The value varies based on the environment
- DEV, UAT, STAGING, PROD, etc
- The values can determine some conditional execution path
- Disable emails
- Control logging patterns
- Feature toggles
How
We need a file to standardize environment variable support in the application. Create a file named env.js
. It will export an object containing everything in process.env
in addition to a specific PORT
variable.
import dotenv from "dotenv";
// injects values from the .env file into process.env
dotenv.config();
const PORT = process.env.PORT || 8080;
const resolved = { ...process.env, PORT };
export default resolved;
Assume we have a basic node express application. For ease of debugging, add a basic route displaying some environment variable MY_ENV_VALUE
. It will return a specific environment variable.
import express from "express";
import env from "./env.js";
const app = express()
app.get('/', (req, res) => {
res.send('Hello World!')
})
app.get("/env", (req, res) => {
const { MY_ENV_VALUE } = env;
res.status(200).json({
MY_ENV_VALUE
});
});
const port = 8080;
app.listen(port, () => {
console.log("Running on Port: " + port);
});
Running the application in Elasticbeanstalk and sending a request to GET /env
will show the environment variable as undefined.
Let’s define it in Elasticbeankstalk.
- Go to Configuration
- Find the
Software
section. SelectEdit
- Set the environment key and value. Select
Apply
.
- Wait for environment to reload with the new environment properties we specified. The environment property will be added to
process.env
and by design, will be exposed in theenv
module we exported earlier.
Once the environment is done refreshing, launch it in the browser.
GET /env shows:
Conclusion
Supporting environment variables in your application will allow for scalable applications that do not need changes to support variances in your environments. If you need to support secret environment variables I recommend using AWS KMS https://aws.amazon.com/kms/, this service will encrypt your keys at rest and give you more granular access control of the values.
Top comments (0)