In five easy steps, we’ll update.gitignore, create a.env file, and read it:
- Add .env to gitignore
# dotenv environment variables file
.env
.env.test
- Install npm package dotenv
npm i dotenv
- It’s time to use our env variables.
Add some variable to your .env file, for exemple we’re going to add a status for our nodejs app and define two different ports, one for development status and one for production
STATUS =production
DEV_PORT =7000
PROD_PORT = 8000
- add this in the beginning of your index.js file to load .env file
require("dotenv").config();
- Then in our entry point we’re testing if the STATUS is production we’re going to use the PROD_PORT else we’re using the DEV_PORT
- Run the application Change the status variable in your .env and see what happens