- You have some dynamic values in your code which you don't want to hardcode.
- You have API Keys in your opensource project which you obviously don't want to push to GitHub
- You have some values in your code that depend on what environment you are building your code for.
If you fall into any of the above-mentioned scenarios I have a got a solution for you. 😃
In Node, there is something called environment variables which you can see by logging
For example, you can set a
NODE_ENV variable which is basically used to define what environment you want to build your code for.
Then further use this variable to generate different builds.
Instead of setting these environment variables ourselves, we will be using the
$ npm i --save dotenv
Once dotenv is installed let's create a
.env file in the root of our project
and add the
PORT variable into it.
Now let's see how we can use this
.env file in our code. We will create a basic node server and use
PORT defined in our
NOTE: If you do not understand the server part, don't worry. It's not important to understand how to use
require('dotenv').config() const http = require('http') const server = http.createServer(callback) server.listen(process.env.PORT || 4000)
We basically created a server in node and the server is listening on the port defined in our node environment variables. If it's not defined there we give it a fallback value.
Now the value of this
PORT can be different depending upon where you deploy your server be it Heroku or something else.
dotenv is loaded first and it has a config function that basically reads our
.env file and populates the environment variables.
You can use dotenv to store your server configuration or use it with webpack to define global variables using webpack's definePlugin.
- You need to load your env config once in your webpack config or in your entry file and also never commit your
- In order to maintain multiple
envfiles each for different environment you can use
dotenv-flowpackage. You must set your
process.env.NODE_ENVvariable first as
dotenv-flowuses that variable to decide which env file to pick. https://www.npmjs.com/package/dotenv-flow
If you face any problem in implementing this, let me know in the comments. I will be happy to resolve.
Thanks for reading 😀