We can use a npm package called dotenv to load all our environment variables from a .env file to the global object property, process.env
. This allows us to access them in our program.
import dotenv from "dotenv"; // Imports the npm packagedotenv.config(); // Loads environment variables into process.envconsole.log(process.env.DB_HOST); // Prints “123.45.678.90”console.log(process.env.API_KEY); // Prints “V3rYPubl1cK3y”
It’s easy to accidentally stage and push files containing sensitive information such as API Keys and database configurations to a remote Github repository. This is where we can take advantage of .gitignore, a plain text file in which each line corresponds to a file, directory, or pattern we would like to ignore when staging. The files, .env and thumbs.db, are being ignored in the example as well as the node_modules directory.
# Environment Variables.env# Windows OS filethumbs.db# node_modules foldernode_modules/