What are .env or Environment Variables?
- Security: API or other secret keys should not be put in plain text into the code directly which is visible to the end user.
- Flexibility: We can conditionally load the environment variables according to need like "if the server is in development then do XYZ else do ABC"
- Adoption: Different services may support such environment variables too like Azure, AWS, Heroku, Jenkins, etc.
Using dotenv module
- mkdir dotenv_demo
- cd doten_demo
- npm init -y
The "package.json" file may consist of all the project settings and other npm package dependencies. If you open that file it should look like this
{ "name": "dotenv_demo", "version": "1.0.0", "description": "", "main": "index.js", "scripts": { "test": "echo \"Error: no test specified\" && exit 1" }, "keywords": [], "author": "", "license": "ISC" }
Step 2: Install npm modules, for setting up the server as well as dotenv module.
For this purpose, I'm using the following command
npm install express dotenv --save
npm install nodemon --save-dev
After installing these modules, your "package.json" file will look like this
{ "name": "dotenv_demo", "version": "1.0.0", "description": "", "main": "index.js", "scripts": { "test": "echo \"Error: no test specified\" && exit 1", "start": "nodemon index.js" }, "keywords": [], "author": "", "license": "ISC", "dependencies": { "dotenv": "^16.0.1", "express": "^4.18.1" }, "devDependencies": { "nodemon": "^2.0.19" } }
Step 3: Setting up the server file i.e., "index.js".
const express = require('express');
const PORT = process.env.PORT || 3000;
const app = express();
app.listen(PORT, () => {
console.log(`Server is running at ${PORT} port`);
});Setting up the server file After setup the server. Let's configure the "dotenv" module.
Step 4: Before configuration. Let's first set up the env file. Create the ".env" file at the root directory of your application and your desired variables into it.
// envVariableName: envVariableValueURL=https://jatinnpminstall.blogspot.com/
Add configuration to your "index.js" or app file. After configuration your file will look like this.
const express = require('express'); const PORT = process.env.PORT || 3000; const app = express(); require('dotenv').config(); app.get('/', (req, res) => { res.send(process.env.URL); }); app.listen(PORT, () => { console.log(`Server is running at ${PORT} port`); });
CONGRATULATIONS.....You've successfully set up your environment variables.
Note: For security purposes, we add the ".env" file to our ".gitignore" file so that Git ignores it and it never uploads on any version controlling system.
ScreenShots
You can also visit my GitHub repository env_config_blog for that code in case you got any type of issue.

No comments:
Post a Comment