Post/Code

HomeAboutUsesNow

Dotenv.

Environment variables are an important part of any codebase. I have found using dotenv to be particularly useful.

Effectively, you would use environment variables anywhere you make use of environment specific config in your code. Typically, this is not something you want to reveal. Node.js is then able to access these environment variables via the process.env object.

  • npm i dotenv // to install

Add the following to your .gitignore file. (You do not want to store your valuable usernames, details etc in your code repo):

  • .env

Let's say you wanted to specify your port number, in your .env file you will then add:

PORT=3000 HOST=yourhostnamehere

Now you are ready to roll - in the relevant Node.js file add:

require('dotenv').config();

...

const PORT = process.env.PORT;
const HOST = process.env.HOST;

...

server.listen(PORT, () => {
  console.info(`Server listening on port: ${PORT}...`);
});

If you were hosting your application on an Azure App Service for example, you would navigate to your App Service in the Azure Portal. From there select the "Application Settings" blade and then in your App Settings, you would create fields named as you have them in your .env file.