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 ;)

Awesome automated testing setup

Usually I have to start dev server and tests in different tabs in the terminal, but how awesome and useful would it be to have only one script for that.

Well, today @kentcdodds teach me an awesome solution for that in one of the lessons at Testing JavaScript: start-server-and-test from @bahmutov.

package.json

"scripts": {
  "test": "jest --watch",
  "test:run": "start-server-and-test start:dev http://localhost:8080 test"
  "start:dev": "webpack-dev-server"
}

So basically when I run yarn test:run, start-server-and-test run the first parameter - start:dev and wait for the server to start responding. When this happens it will run the third parameter - test.

This is very useful not only for the developer but for the CI too.