On this article we’re going to cowl atmosphere variables also called env variables. These are principally key-value pair of knowledge set that’s saved within the working system stage
On this article we are going to find out about atmosphere variables in NodeJs with examples
- What are Setting variables
- Why are env variables are necessary
- Conditions for the challenge
- Putting in NodeJs and organising a brand new Mission
- Initializing your first env variable with NodeJS
- env variables in API calling / async duties
- env variables in Database operations / async duties
- Superior env variable manipulation in Node JS: Encoding, Validation and sort conversion
- Secrets and techniques administration and Safety Finest Practices with examples
- Widespread Pitfalls and learn how to keep away from them
- Conclusion
Setting Variables
Setting variables are a key-value pair knowledge set which might be avaiable on the working system stage. These knowledge set can be found in all main working system command line shells Home windows, Mac and Linux
Why are env variable necessary?
- Separation of issues
- Safety
- Portability
- Scalability
- Compatibility
- Interoperability
Conditions for this Mission
On this challenge we’re going to assume the next
- Primary data of NodeJs
- Primary Data of JavaScript
- Some data of Backend growth
Putting in Node and organising the challenge
These are totally different strategies of putting in NodeJS in your machine. You possibly can go to the node official web site and obtain a model from there
Allow us to contemplate putting in nodejs in a linux working system ideally ubuntu
Step 1: Open your terminal
Step 2: Use curl or wget script beneath to put in nvm utilizing the nvm git repository. run the script to put in the nvm
curl -o- https://uncooked.githubusercontent.com/nvm-sh/nvm/v0.39.3/set up.sh | bash
# OR
wget -qO- https://uncooked.githubusercontent.com/nvm-sh/nvm/v0.39.3/set up.sh | bash
Step 3: Shut and re-open your terminal and run the next to use the script
export NVM_DIR="$HOME/.nvm"
[ -s "$NVM_DIR/nvm.sh" ] && . "$NVM_DIR/nvm.sh"
Step 4: Affirm Set up
You possibly can verify that NVM has been put in in your system by operating the next command
nvm --version
*Step 5 : * Putting in Node
sort the beneath command to put in the newest model of node
nvm set up newest
or
nvm set up --lts
Step 6 Setting the default model
you’ll be able to set a default model of node for use throughout your system through the use of the next command
nvm alias default 20.8.0
Step 6: Checking if node is put in
you’ll be able to sort the beneath command to test if the node is put in in your system
node -v # tells you the present model of node in your system. In our case it's 20.8.0
Initializing the challenge
Now, that we’ve got put in the node on our machine. Allow us to create a brand new challenge the place we shall be utilizing the env variable
create a brand new listing and title it env-demo and cd into the listing
mkdir env-demo
cd env-demo
Now, that we’ve got created the folder and cd into it. Kind the beneath command to initialize a brand new challenge and fill out the fields as you see match.
npm init
package deal title: (env-demo)
model: (1.0.0)
description:
entry level: (index.js)
check command:
git repository:
key phrases:
creator:
license: (ISC)
this may create a package deal.json file for you that appears one thing like this:
{
"title": "env-demo",
"model": "1.0.0",
"description": "",
"predominant": "index.js",
"scripts": {
"check": "echo "Error: no check specified" && exit 1"
},
"creator": "",
"license": "ISC"
}
Initializing your first env variable: Step By Step
Step 1: Set up the dotenv package deal
Now that you’ve initialized the challenge within the above part and created a package deal.json file. In your terminal sort the beneath command to put in the node dotenv package deal that’s used to create env recordsdata
npm set up dotenv --save
It will set up the dotenv package deal and reserve it as a dependency in your package deal.json
file. that ought to look one thing like this
{
"title": "env-demo",
"model": "1.0.0",
"description": "",
"predominant": "index.js",
"scripts": {
"check": "echo "Error: no check specified" && exit 1"
},
"creator": "",
"license": "ISC",
"dependencies": {
"dotenv": "^16.3.1"
}
}
Step 2 Create the .env file
- In your root folder create a brand new file and title it
.env
. - Open your .env file in your textual content editor and create some key-value pairs. These are your atmosphere variable. I’ve created some in your reference beneath
DATABASE_URL=sample-database-url
PORT=3000
SECRET_KEY=mysecretkey
Step 3 Load and skim the env variables
In your root folder create an index.js file after which open your terminal and sort the beneath command to put in categorical js.
npm set up categorical --save
This installs expressjs and saves it as a dependency in your package deal.json file, your package deal.json
seems like this
{
"title": "env-demo",
"model": "1.0.0",
"description": "",
"predominant": "index.js",
"scripts": {
"check": "echo "Error: no check specified" && exit 1"
},
"creator": "",
"license": "ISC",
"dependencies": {
"dotenv": "^16.3.1",
"categorical": "^4.18.2"
}
}
and your challenge construction seems like this
Now, open your index.js file and sort the beneath command to start out a easy net server.
const categorical = require('categorical');
const app = categorical();
const port = 4000; // defaults to 4000
app.get('/', (req, res) => {
res.ship('Howdy World!')
})
app.hear(port, () => {
console.log(`Server operating on http://localhost:${port}/`);
});
run the code with
node index.js
and go to localhost://4000 to get the hi there world
loading and studying the .env file
Now that we’ve got the server operating allow us to learn the .env file that we created within the earlier step and cargo the port particulars from the .env file
Open the index.js file and require the dotenv library there
require('dotenv').config()
now, you’ll be able to entry the .env file utilizing the method.env. Allow us to use the method.env to entry the port quantity in our index.js file
const categorical = require('categorical');
require('dotenv').config()
const app = categorical();
const port = course of.env.PORT || 4000; // Learn from .env if not accessible then defaults to 4000
app.get('/', (req, res) => {
res.ship('Howdy World!')
})
app.hear(port, () => {
console.log(`Server operating on http://localhost:${port}/`);
});
Now allow us to restart the server and go to localhost://3000 . As a substitute of operating at 4000 our server is now operating on port 3000 which it took from the .env file
you may also see this within the console
You have got now efficiently created and saved the env file in your machine
As one other instance you’ll be able to entry the DATABASE_URL like so
const dbUrl = course of.env.DATABASE_URL;
// Use dbUrl to hook up with your database
Listed below are all of the recordsdata
index.js
const categorical = require('categorical');
require('dotenv').config()
const app = categorical();
const port = course of.env.PORT || 4000; // Learn from .env if not accessible then defaults to 4000
app.get('/', (req, res) => {
res.ship('Howdy World!')
})
app.hear(port, () => {
console.log(`Server operating on http://localhost:${port}/`);
});
package deal.json
{
"title": "env-demo",
"model": "1.0.0",
"description": "",
"predominant": "index.js",
"scripts": {
"check": "echo "Error: no check specified" && exit 1"
},
"creator": "",
"license": "ISC",
"dependencies": {
"dotenv": "^16.3.1",
"categorical": "^4.18.2"
}
}
.env
DATABASE_URL=sample-database-url
PORT=3000
SECRET_KEY=mysecretkey
Tips on how to use env variables in async duties
On this part we’re going to focus on about how env variables can be utilized in async duties like calling an API or database operations
Env variables are particularly necessary in these duties, as a result of they can be utilized to retailer credentials and endpoints securely
Additionally, these variables may be automated as a result of these change between totally different atmosphere similar to growth, staging and manufacturing.
Step 1 Organising the env variables
open your .env
file and edit it like this
API_URL=https://jsonplaceholder.typicode.com/todos/1
API_KEY=sfjks4325
PORT=3000
Step 2 utilizing async / await with env variables
Subsequent, set up the axios library to make calls to the distant server like
npm set up axios --save
this may set up the axios and reserve it as a dependency in your package deal.json file
the package deal.json file ought to look one thing like this
{
"title": "env-demo",
"model": "1.0.0",
"description": "",
"predominant": "index.js",
"scripts": {
"check": "echo "Error: no check specified" && exit 1"
},
"creator": "",
"license": "ISC",
"dependencies": {
"axios": "^1.5.1",
"dotenv": "^16.3.1",
"categorical": "^4.18.2"
}
}
Subsequent use the axios to make calls to the jsonplaceholder web site and log them to the console
Kind this code in your index.js
file
const categorical = require('categorical');
require('dotenv').config();
const axios = require('axios');
const app = categorical();
const port = course of.env.PORT || 4000; // Learn from .env if not accessible then defaults to 4000
const fetchData = async () => {
const url = course of.env.API_URL;
const apiKey = course of.env.API_KEY;
strive {
const response = await axios.get(url, {
headers: { 'Authorization': `Bearer ${apiKey}` }
});
console.log(response.knowledge);
} catch (error) {
console.error(`Error fetching knowledge: ${error}`);
}
};
app.get('/', (req, res) => {
fetchData()
res.ship('Howdy World!')
})
app.hear(port, () => {
console.log(`Server operating on http://localhost:${port}/`);
});
What are we doing right here:
- We’re importing the modules like categorical, dotenv, axios
- Then we’re initalizing the app and the port utilizing the env variables
- then we’re creating the async operate referred to as const fetchData = async ()=> (…)
- On this operate we’re utilizing the url and the apiKey from the .env file. Although I’ve to say you do not want apiKey to name the jsonplaceholder web site. I’ve simply put that key there for demo functions
- we’re logging the information to the console
- We’re calling the fetchData() technique on the get route. So, each time somebody goes to the / the strategy will get referred to as and the information will get logged to the console.
Utilizing Async/await with env variables in Database operations
Allow us to have a look at one other instance, this time we’re going to do database operations with env variables
step 1 arrange the env variables
Open the .env file in your textual content editor and sort the next
DB_HOST=localhost
DB_PORT=5432
DB_NAME=mydatabase
DB_USER=username
DB_PASSWORD=password
Step 2: Set up the pg library
subsequent step is to put in the pg library like so
npm set up pg --save
*Step 3: * Connect with the database and make the async question with .env file
write the next code to hook up with the database and use the .env credentials that we simply created
const { Pool } = require('pg');
require('dotenv').config();
const pool = new Pool({
host: course of.env.DB_HOST,
port: course of.env.DB_PORT,
database: course of.env.DB_NAME,
consumer: course of.env.DB_USER,
password: course of.env.DB_PASSWORD
});
const fetchUsers = async () => {
strive {
const res = await pool.question('SELECT * FROM customers');
console.log(res.rows);
} catch (err) {
console.error(`Error fetching customers: ${err}`);
}
};
fetchUsers();
we aren’t integrating this instance into our common codebase as a result of it’s an outlier and won’t be helpful additional down the road in our tutorial
Superior env variable manipulation in Node JS: Encoding, Validation and sort conversion
There’s extra to env variable than simply studying and storing them. With superior env variable manipulation we’re going to find out about
- Encoding
- Validation and
- Kind conversion
1. Encoding:
Encoding is used for numerous functions in atmosphere variables. This might be used for safety puposes. The preferred sort of encoding is completed utilizing the base64
Encoding
const decodedData = Buffer.from(encodedData, 'base64').toString('utf-8');
console.log(`Decoded: ${decodedData}`);
2. Validation
validation is used to test whether or not the code is legitimate or not. for instance the url that you will use is legitimate url or not and so on
or as on this instance we’re checking whether or not the port quantity is throughout the specified vary or not
const validatePort = (port) => {
const parsedPort = parseInt(port, 10);
if (isNaN(parsedPort) || parsedPort < 1024 || parsedPort > 65535) {
throw new Error('Invalid port quantity');
}
return parsedPort;
};
const port = validatePort(course of.env.PORT);
3. Kind conversion
env variables are at all times on the sort : string. If usually you could use different knowledge sorts as properly similar to int or booleans. Right here sort conversion helps
Integer instance
const isProduction = course of.env.NODE_ENV === 'manufacturing';
const retries = parseInt(course of.env.RETRIES, 10) || 3;
Boolean instance
const shouldLog = course of.env.SHOULD_LOG === 'true';
Mixture instance
Right here is an instance combining all of the superior env manipulation accessible within the env variables
// Encoding and decoding
const apiKey = Buffer.from(course of.env.API_KEY || '', 'base64').toString('utf-8');
// Validation
if (apiKey.size !== 32) {
throw new Error('Invalid API key size');
}
// Kind conversion
const maxUsers = parseInt(course of.env.MAX_USERS, 10);
if (isNaN(maxUsers)) {
throw new Error('MAX_USERS should be an integer');
}
Secrets and techniques Administration and Safety Finest Practices with examples
On this part we’re going to find out about secrets and techniques administration and finest practices with examples. Listed below are the steps you could take to safe the env variable together with their examples
1. By no means commit the .env
recordsdata
At all times be sure that the .env recordsdata are within the gitignore so they’re by no means commited to the git repository
# Ignore dotenv atmosphere variables file
.env
2. Hashing password
at all times hash the passwords, storing the passwords as plain textual content is a nasty observe. You need to use libraries like bcryt and others to hash the passwords
const bcrypt = require('bcrypt');
const saltRounds = 10;
async operate hashPassword(plainPassword) {
const hash = await bcrypt.hash(plainPassword, saltRounds);
return hash;
}
3. Encoding the env variables
As a safety measure at all times encode the secrets and techniques, the secrets and techniques are often base-64 encoded
const buffer = Buffer.from(course of.env.MY_SECRET, 'base64');
const decodedSecret = buffer.toString('utf-8');
4. Centralized secrets and techniques administration
for big initiatives you’ll be able to contemplate centralized secrets and techniques administration providers like hashicorp vault, AWS secrets and techniques supervisor and others
These provide superior options like secret rotation, automated lease and rotation and audit logging
right here is an instance with node vault
const vault = require("node-vault")({
endpoint: "https://vault-endpoint",
token: course of.env.VAULT_TOKEN,
});
async operate getDatabaseCreds() {
const knowledge = await vault.learn("path/to/secret");
return {
consumer: knowledge.knowledge.username,
password: knowledge.knowledge.password,
};
}
5. Least privilege precept
At all times observe the precept of least privilege. The api which doesn’t require write credentials ought to by no means be given write privileges.
Widespread Pitfalls and Tips on how to keep away from them
- Hardcoding Delicate info
- Lack of validation
- Ignoring Environments
- Insufficient safety
- Poor Documentation
- Fallback defaults
Want Chat API in your web site or app
DeadSimpleChat is an Chat API supplier
- Add Scalable Chat to your app in minutes
- 10 Million On-line Concurrent customers
- 99.999% Uptime
- Moderation options
- 1-1 Chat
- Group Chat
- Absolutely Customizable
- Chat API and SDK
- Pre-Constructed Chat
Conclusion
On this article we discovered about env variable and learn how to use them in NodeJs the entire information
We’ve coated the necessary subjects associated to env administration in NodeJs and this must be sufficient for many of the use-cases for env variables administration in Node js apps
I hope you appreciated the article and thanks for studying