Sharing my tech Journey

How to use different configurations based on the environment

Creating a plain nodejs app is simple. Building on top of this app with lots of awesome features will be great.

But how can we make it work in our local, and at the same time running in dev, deploy it in qa and running it in pre-prod (staging) and PROD env?

spiderman-multiverse

This is where you need to put on your DevOps hat and start thinking about how your application needs to run in different environments at the very beginning of the app development process.

To make the app run in different environments, We need to write our app in a way that, the app can customise itself based on the environment it runs. It should pick up appropriate configuration for that environment and apply that configuration.

Let us start that by adding config module to our app.

$ npm install config

Config package gives the flexibility to the app to use environment specific configurations and thus enabling us to write modularised code.

Now let us create a config folder in the main directory strucutre. folder-with-config

We will create two config json files, one for dev (dev.json) and one for production (production.json) for now. configs-in-folder

To use this config in our code, we need to define the environment in which the code runs as part of our start script.

"start": "NODE_ENV=dev node app.js",

Let us add some configuration to the dev.json file.

{
"auth":{
"secretKey":"My Development Secret Key"
}
}

To use this configuration in the code, we will need to intialise a config object which can hold all of this config data and from that config object we can get the required objects within that.

in our app.js file, add the initialisation line.

const config = require("config");
<some other codes>
...
app.get("/secret-key", (request, response) => {
response.json({ info: "Your Secret Key is >> " + config.get("auth").secretKey });
});

Now restart the app server.

npm run start

When you hit http://localhost:3000/secret-key, you should be able to see the data from the config object. Change the data in the config and restart the server and you should see the updated data.

Let us some other data in production.json configuration.

{
"auth": {
"secretKey": "b4b30115148d40ae9574f7a197e8539d"
}
}

Change the node environment to production in package.json file.

"start": "NODE_ENV=production node app.js",

Start the server for production.

npm run start

If you change the NODE_ENV=production and start the server and when you change the data in production.json, you will see corresponding data loaded for that environment.

We will use the config files to configure our database backend for various environment in our next post!