Today I Learned

Inspired by til.hashrocket.com

Environment Variables in Node.js

It's not something new but I think will be useful to share.

As you already know, environment variables are very useful on every system. It's allowing us to free our software from configuration dependencies.

In the Node.js world is very common to start the server with:

$ NODE_ENV=development node server.js

This is ok, but when env vars grow it's not that fun ;)

So, there is better way how to organize the configuration - dotenv:

  1. install the dotenv

  2. create .env file

  3. put all the configurations there

    NODE_ENV=development
    PORT=3000
    ...
  4. configure the package

    // Easy
    require('dotenv').config() //will try to open .env in the root
    console.log(process.env.PORT) //returns 3000
    // More flexible
    const dotenv = require('dotenv')
    
    //optional: Pass the path to the configuration. Default is .env file in the root
    const result = dotenv.config({ path: './.production.env' })
    
    //you can check if the config is found
    if (result.error) {
      throw result.error
    }
    
    console.log(result) //returns { parsed: {PORT: '3000'}}
    
    console.log(process.env.PORT) //returns 3000
  5. Pro tip: Create .env.example and add .env in .gitignore. Every dev should copy example file and add personal configs.

Please check out the documentation for detailed info about configuration.

This topic is well explained from @John_Papa in his article Node.js Everywhere with Environment Variables!

Cheers ;)