While in debug and release, we will have sensitive information to deal with, and we usually don't want those to be written in our code, incase someone has access to our code, or we commit it to source control(like github). Sensitive information could include API-Keys or anything sensitive. In our case, we have sensitive stuff like our Port, our database connection string and so on, we can put them in a separate secure file, that will be ignored when we are pushing our code to source controls(like github), the common way of doing this is by putting it in a .env
file, which contains stuff called "environment variables", we will use them in our environment and can access them so far as we are in the scope of our environment, but anyone outside our environment can't use it.
so, go ahead and create a new file in your project root, and call it .env
, then in there, we will first of all, save our connection port.
So, your .env file will look something like this
PORT=3000
so, our port is 3000, then in our code, in order to be able to access the data in our environment, we have to install a library called dotenv
.
The command you want to run is npm install dotenv
.
then in your app.js
, you want to import and initialize your environment
require('dotenv/config')
In Node.js, when using the dotenv
library for managing environment variables, you typically don't save it to a constant because dotenv
doesn't provide an object or instance to store. Instead, you use the require('dotenv/config')
statement to load the environment variables from a .env
file into the Node.js process.
require('dotenv/config')
: This line is used to load and configure environment variables from a .env
file in your Node.js application. It searches for a .env
file at the root of your project and reads the variables from the file and adds them to the process.env
object, which is a global object in Node.js containing environment variables. It essentially configures your application to use these environment variables.
So, in order to access your environment variables, you can call the process.env.<Variable Name>
the way you saved the variable, if it was in CAPS, then type it in all caps. in our case, we would end up with
require('dotenv/config');
const env = process.env;
const port = env.PORT;
the reason I saved it in an env constant is so that I can use it multiple times without having to explicitly state process.env.PORT
, process.env.DATABASE_CONNECTION_STRING
.