DEV Community

Cover image for Secret affair of Node.js - Environment Variables.
Radhakishan Jangid
Radhakishan Jangid

Posted on

Secret affair of Node.js - Environment Variables.

So today I am presenting you guys "Secret affair of Node.js - Environment Variables"

When you build a Node.js application you want them to run everywhere. This could be on your colleagues’ computers, internal company servers, cloud servers, or inside of a container (maybe using Docker).
This is the time when we use environment variables.

Environment variables are a fundamental part of developing with Node.js, allowing your app to behave differently based on the environment you want them to run in. Wherever your app needs configuration, you use environment variables. And they’re so simple, they’re beautiful!

Today, this post will help you create and use environment variable in your Node.js application.


Example of using ENV:


// server.js
const port = process.env.PORT;
console.log('Your port is ${port}');

Create a file named server.js and put the above code in the file. Now when you run this file you will see a message "Your port is undefined".
This is because there isn't any enviornment variable right now.

So for that we create a File name .env.

Create the .env file in the root of your app and add your variables and values to it.

NODE_ENV=development
PORT=8626
# Set your database/API connection information here
API_KEY=**************************
API_URL=**************************
Enter fullscreen mode Exit fullscreen mode

Remember Your .gitignore File

A .env file include many security related data, so you better put this file into gitignore.
Open or create .gitignore file and add

.env

anywhere in the file.

Now install Install dotenv from npm

npm install dotenv

Now read the env data like this


// server.js
console.log('Your port is ${process.env.PORT}'); // undefined
const dotenv = require('dotenv');
dotenv.config();
console.log('Your port is ${process.env.PORT}'); // 8626

Now run your code
node server.js.

This is it, now you can use any variable like this

process.env.Variable.

GoodBye :)

Top comments (0)