How to Read Environment Variables from Node.js

Introduction

The core module of node.js called process gives us the env property that hosts all the environment variables set in the initial stages when the process was started.

Let’s see a code that sets USER_ID and USER_KEY and runs app.js

USER_ID=123456 USER_KEY=ninja node app.js

 

That will pass our user USER_ID as 123456 and the USER_KEY as ninja. This makes it suitable for testing. However, for production, we will probably have to configure some bash scripts to export variables.

Let’s see an example where we can see the USER_ID and USER_KEY. 

Example

process.env.USER_ID // "123456"
process.env.USER_KEY // "ninja"

 

Using the same way, we can access any custom environment that we set.

Let’s see what we can do if we have multiple environment variables in our node.js project.

Multiple Environment Variables

If we have multiple environment variables in our node.js project, we can easily create a .env file in our root directory of the node.js project, and then we can use the dotenv package to load them during runtime.

Let’s see the code now.

# .env file 
USER_ID="123456" 
USER_KEY="ninja" 
NODE_ENV="coding"

 

In our js file:

require('dotenv').config(); 
process.env.USER_ID // "123456" 
process.env.USER_KEY // "ninja" 
process.env.NODE_ENV // "coding"

 

Now Let’s quickly have a look at the frequently asked questions:

Frequently Asked Questions

1. Is Node JS frontend or backend?

Node.js can be used in both the frontend and backend of applications and websites, thereby making the work of developers easier.

2. Is Node JS a programming language?

No, we can say that node.js is not a programming language, it allows developers to use JavaScript, a programming language for creating web applications. 

3. Name some companies that use Node.js.

Some companies that use node.js are eBay, PayPal, Yahoo, Microsoft, and Uber.

4. List some advantages of using Node.js.

Some advantages of Node.js are:

  • Easy Scalability
  • Real-time web apps 
  • Fast Suite
  • Easy to learn and code
  • Caching
  • Data Streaming
  • Corporate Support

Key Takeaways

In this article, we got to know the ways we can use to read environment variables from node.js

This doesn’t seem enough, though.

Of course not!

Whether it is frontend or backend or even both with node.js, Web development is all about learning by doing. You can now check out this course on Full Stack Development, which includes tutorials on Node.js.

Happy Learning!

 

Was this article helpful ?
0 upvotes

Comments

No comments yet

Be the first to share what you think