How to use JSON as an Environment variable ๐ค

I am an Engineering undergraduate student passionate about web technologies. Worked with React, Vue, NodeJS, Express, MongoDB, PostgreSQL, Git.
While deploying an app into the production environment variables are the preferred approach to store sensitive credentials. In this article, I will discuss how to use JSON as an environment variable.
TL;DR
Are you in a hurry? Hope that the below snippet will serve your purpose.
// Import the JSON as a Javascript object first
const someJson = require("./path/to/json"); /*NodeJS syntax*/
// Convert the object to a string
JSON.stringify(someJson);
// Output will look like this
"{"key1":"value","key2":"value2"}"
// .env file
SOME_ENV_VARIABLE={"key1":"value","key2":"value2"}
// Use the same by parsing the string back to object
const SOME_ENV_VAR = JSON.parse(process.env.SOME_ENV_VARIABLE || {});
What Are Environment Variables?
According to Wikipedia, an environment variable is a dynamic-named variable responsible for the behavior of a process on a computer. Typically these variables are represented as a key-value pair and part of the environment that the process runs on.
Generally in a Javascript application environment variables are stored as a key-value pair in the .env file at the root directory of the project.
SECRET_KEY=super_secret_key
API_SECRET=extra_super_secret_key
During the initialization of the application, these variables are loaded as an object into process.env
Why use Environment Variables?
So you might think, environment variables are just like a variable that stores some value, right? ๐ค
// Why not use the variables directly in the app?
const SECRET_KEY = "super_secret_key";
const API_SECRET = "extra_super_secret_key";
This might look great but It's not a good idea to hardcode these into the code. Below are the few reasons mentioned:
Security: Most of the time the source code will be pushed into a version control system, thus hardcoding these values into the code will expose them. This will be a very big security concern.
Accessibility: As all of these variables are in one place, they are easily available if any update required.
Multiple modes: Typically in a production-level app there are multiple modes (e.g
development,testing,production, etc) running, and giving them access to multiple resources becomes very easy using environment variables.
What is JSON?
JSON (Javascript Object Notation) is a lightweight, easily readable, key-value paired data-exchange file format.
// example.json
{
"key1": "value1",
"key2": "value2"
}
JSON as an Environment variable
Most of the Secret Keys or API keys are provided as a string, thus can be easily used as an environment variable.
MONGODB_URI=mongodb://<credentials>@realm.mongodb.com:27020/?<parameters>
STRIPE_SECRET=d5h4drh5r1h5d1hg5trh11h5h1rehg1s5g1df5g1df5
But there are few services available (e.g Firebase) where a JSON will be more suitable than string.
/* firebase project configuration object */
const firebaseConfig = {
apiKey: "AIzaSGfbdb2fwgKOhjntgjgfjf44cHvY6ri8PrFdjaalY",
authDomain: "your-project-id.firebaseapp.com",
databaseURL: "https://your-project-id.firebaseio.com",
projectId: "your-project-id",
storageBucket: "your-project-id.appspot.com",
messagingSenderId: "xxxxxxxxx",
appId: "1:851485915280:web:4ja7df4d7e415ffaf74aadaf5",
}
So it can be written like this (writing all of the property as an environment variable)
// .env file (considering a React App)
REACT_APP_API_KEY=AIzaSGfbdb2fwgKOhjntgjgfjf44cHvY6ri8PrFdjaalY
REACT_APP_AUTH_DOMAIN=your-project-id.firebaseapp.com
REACT_APP_DATABASE_URL=https:\/\/your-project-id.firebaseio.com
...so on
// in the app
const firebaseConfig = {
apiKey: process.env.REACT_APP_API_KEY,
authDomain: process.env.REACT_APP_AUTH_DOMAIN,
databaseURL: process.env.REACT_APP_DATABASE_URL,
...so on
}
But this is not scalable, because in a real project there might be several versions (e.g development, staging, production) of this app deployed. So writing all of the properties, again and again, might not be a good idea.
// .env.development
REACT_APP_API_KEY=AIzaSGfbdb2fwgKOhjntgjgfjf44cHvY6ri8PrFdjaalY
REACT_APP_AUTH_DOMAIN=your-project-id.firebaseapp.com
...so on
// .env.test
REACT_APP_API_KEY=AIzaSGfKOhjntgjgfjf44cHvY6ri8PrFdjaalY
REACT_APP_AUTH_DOMAIN=your-project-id-test.firebaseapp.com
...so on
// .env.production
REACT_APP_API_KEY=AIzaSGfbdb2fwgKOhjntgjgfjf44cHvY6ridjaalY
REACT_APP_AUTH_DOMAIN=your-project-id-prod.firebaseapp.com
...so on
Instead of this, first, stringify the object and then use it as a single variable. Create a simple .js file to convert JSON to String.
// Import the JSON as a Javascript object first
const someJson = require("./path/to/json"); /*NodeJS syntax*/
// Convert the object to a string
JSON.stringify(someJson);
// Output will look like this
"{"apiKey": "AIzaSGfbdb2fwgKOhjntgjgfjf44cHvY6ri8PrFdjaalY", "authDomain": "your-project-id.firebaseapp.com" /* ...rest */}"
Then use the stringified object as an environment variable.
// .env file
REACT_APP_FIREBASE_CONFIG={"apiKey": "AIzaSGfbdb2fwgKOhjntgjgfjf44cHvY6ri8PrFdjaalY", "authDomain": "your-project-id.firebaseapp.com" /* ...rest */}
// in the code
const firebaseConfig = JSON.parse(process.env.REACT_APP_FIREBASE_CONFIG || {});
This approach is scalable and easy to read.
This example shows React App but the same applies to any Javascript project either frontend or backend.
In this example, shown credentials are meant to use on the client-side and visible to all. Please don't expose any sensitive information on the client.
Wrap up
Environment Variables are super useful and should be used while deploying an app to production. They make your code more scalable and modular.
Hope this article was helpful ๐. If so, then show your love and share it with others.
What to add something? write it in the comments ๐

