Configuration settings in Node with dotenv
I am currently building a chatbot in Node which utilizes Microsoft’s Language Understanding Intelligence Service (LUIS) to determine a user’s intent from their question or message.
Using LUIS requires specifying a URL containing secrets in my chatbot application; therefore I should get this from a Node environment variable so it doesn’t appear in source control. I would say I am still new to Node development, so I thought I would research options for doing this.
After researching, I settled on dotenv due to its simplicity and popularity. dotenv is an npm module that loads environment variables from a .env file into process.env.
To show how simple it is to use, I created a project over on my GitHub; there are only two steps:
Create .env file
In the root directory of your project, create a file called .env. The contents of the file should be of the form NAME=VALUE on separate lines, in my example this is:
SECRET_KEY=My secret value
Configure dotenv
Next in your application, you just need to import the dotenv module and configure it. To centralize access to configuration and configure dotenv, I created a module called settings show below:
declare function require(moduleName: string): any;
if (process.env.NODE_ENV !== "production") {
const dotenv: any = require("dotenv");
dotenv.config();
}
export const secretKey = process.env.SECRET_KEY || "Fallback value";
You will notice that I wrapped the dotenv import with an if; this is an conditional import in TypeScript where dotenv is imported and configured only during development.
Per this issue on the dotenv’s GitHub, in production environments it is advised to use the capabilities of the service you are using to configure environment variables rather than with dotenv. For example, with Docker I can specify configuration with the run command or with Compose to set SECRET_KEY.