Environment variable
Today we will learn ab
.then((conn)=>{
console.log(`Connected to DB: ${conn.connection.host}`);
})
Basically, it provides ${conn. connection.host} hostname.
Environment Variable
Environment variables are basically used for storing sensitive data such as passwords, API credentials and other information that should not be written directly in code.
Environment variables must be used to configure any variables or configuration details that may differ between environments.
Environment variables are variables available in your program or application dynamically in runtime. The value of these variables can come from a range of sources -- text files, third-party secrets managers, calling scripts, etc.
Good practices for defining environment variables in the .env file
Use Descriptive names:-
Use clear and meaningful names for your environment variables.
Use UpperCase letters:-
It's a common convention to use Uppercase letters for environment variables.
Separate Words With Underscores:-
Use separate words for more readability. Example:- "DATABASE_URI" instead of "database URL"
Don't commit.env file to version control:-
If you share your .env file with version control then your all sensitive data will be leaked.
Keep the file consistent:-
Use a consistent format for example:-"VARIABLE_NAME=Value".
Set up and read a .env file in nodejs
create a new file in the root directory of your project called .env This should not have any file extension and should be in the main directory of your main code file.
Add your environment variables to the .env file using the following format: KEY=VALUE.
Save the .env file.
Now install dotenv npm package. "npm install dotenv"
In your main code file, import the package that you just installed and load the environment variables from the .env file: "require('dotenv').config();"
You can now access the environment variables in your code using the process.env object.
Examples:-
const sunny ={
host: process.env.DB_HOST,
user: process.env.DB_USER,
password: process.env.DB_PASSWORD
}
PORT=5001
ID =10
SECRET=SECRET
CLIENT_URL =https://localhost:3000