For enquiries call:

Phone

+1-469-442-0620

Aage ki Socho

HomeBlogWeb DevelopmentNode Environment Variables: Process env Node

Node Environment Variables: Process env Node

Published
05th Sep, 2023
Views
view count loader
Read it in
6 Mins
In this article
    Node Environment Variables: Process env Node

    Developers need to pay attention to several things when configuring Nodejs applications. 

    All applications are typically required to deploy in a development environment before being deployed in the production environment, and it is crucial to be certain that each environment has been set up right. If our production application is using our development credentials, it will be disastrous. 

    Here Environment variables come in handy, they are one of the preferred strategies to define and consume environment-specific configurations and are supported by all the major operating systems. 

    Environment variables allow us to supervise the configuration of our applications separately from our base code. Separate configurations promote the implementation of our application in different environments (development, test, production), allowing our app to behave differently based on the environment they are running in.  

    The benefits of using the environment variables can be listed below. 

    • Security: API keys/other secret keys should not be put in plain text in the code to be directly visible. 
    • Flexibility: you can introduce conditional statements based on environments like “If production server then do X else if test server then do Y…”. 
    • Adoption: Popular services like Azure or Heroku support the usage of environment variables. 

    An alternate approach to learning more about nodejs and environment variables is to go through this Node.js full course

    The env files provide a popular solution for setting up the environment variables, particularly in Node.js. Platforms like Heroku, for example, use .env files as recommended best practices. 

    They can be defined in the majority of cloud-provider Platforms as a Service (PaaS) offerings, and are a typical method for configuring many platforms like Heroku, Azure, AWS, etc. 

    In this post, let us look at a simple Node.js application configured via environment variables and walk-through creating and using environment variables, leading to a Node.js app that can run anywhere. 

    Do you want to see how to utilize this in real projects? Then check out the full-stack developer course with placement guarantee. 

    Basics of Environment Variables in Node.js

    In Node.js, Environment variables are Accessible and supported out of the box. When the Node.js process boots up, it automatically provides access to all the existent environment variables by building theenv object as a property of the global object called process. 

    These variables are external to our application and reside in the operating system or the container of the running application. An environment variable is merely a name assigned to a value. 

    By convention, the names are capitalized and the values are strings.
    For example, PORT = 3000. 


    When a Node.js application commences or a script is run, a new child process is launched, inheriting the `environment variables` from the parent process. These environment variables are parsed by the node application, creating a process.env object with string format key value pairing. Some common examples are: 

    • HTTP Address and Port number. 
    • Database Credentials. 
    • Location of static files and folders. 
    • Credentials of External API. 

    What is process.env

    The process.env is a global variable injected at runtime by your Node.js application to depict the state of the environment your app is in at the time of initiation and utilize the same at runtime. There by, its basic use is to depict the state of the system environment of our app on initialization. 

    For example, if you set a PORT variable in the system, it can be accessed through the process.env.PORT variable because, when we set an environment variable, it is loaded into process.env during runtime and can later be accessed. 

    To inspect the contents of process.env, we can use an interactive Node terminal as done below. 

    Till now you would have understood how environment variables in a Node application are populated, so let's dive in to understand how to work with them. 

    Also, read about how to export Node.js modules using exports

    process.env: Listing of Environment Variables

    The process.env is a global object used to access all the environment variables of the environment your application is running. That means that it is accessible everywhere in our application. 

    If you want to take a look at this object, run the Node.js REPL with “node” in your command line and then type: 

    console.log(process.env); 

    This code will output all environment variables that this Node.js process can pick up. 


    Now that we have accessed the process.env object by logging it onto the console, we can also similarly list the default environment variables of our application. Accessing an environment variable from process.env is no different from that of a typical object: 

    const PATH = process.env.PATH 

    The one significant difference with the process.env object is that all the key and value pairs will always be strings,as environment variables can only be strings. 

    Note* 

    On the contrary, if a value in the environment variables needs to be of non-string type, it must be parsed or cast, e.g., casting a PORT environment variable to an integer:r: 

    const PORT = parseInt(process.env.PORT); 

    Installing Environment Variables

    Node.js natively does not load .env files, so we must utilize the dotenv package to load the file and expose the values via process.env. 

    As per the definition from its package, Dotenv is a zero-dependency module that loads environment variables from a .env file into process.env. Storing configuration in the environment separate from code is based on The Twelve-Factor App methodology. 

    Let's start by adding dotenv as a project dependency in the package.json file under the dependencies property. 

    Next, download the dependency with the following: 

    npm i  

    Alternatively, you can use the below command which will automatically update the package file. 

    npm install dotenv --save 

    Now we can create a .env file at the root of our node.js project, which will contain all your environment variables related to your project. Though, to load the .env file, we must load the dotenv package and call the configure() function at the very start of the index.js file: 

    require('dotenv').config(); 

    The above code present in your index file automatically loads the .env file in the root of your project and initializes the values, skipping any variables already present. Though, be careful and do not use .env files in your production environment. Instead, place them on the respective host to secure them. And therefore, you should wrap your load statement in an if statement using the node js node_env variable like the one below. 

    if (process.env.NODE_ENV !== 'production') { 
      require('dotenv').config(); 
    } 

    Now we can access our environment variables and list them in our node.js project for node_env development. 

    Installing Custom Environment Variables

    As our application now has the power to read the .env file, it becomes even easier to customize and create custom environment variables. 

    Customizing a .env file can be done by writing the name of the environment variable we want to override at the start of each line, followed by ‘=’ sign and then the string value that is to be assigned to it. 

    Let us understand the same by taking the example below, we assign new values for the variables PORT and MYNAME in the .env file as shown: 

    Now, run the application with the following command: 

    node src/index.js 

    Next, open http://localhost:5001; notice the port changed and the message Hello, Jane! returns. 

    This example helps us understand how easy it is to add custom variables to our env file. Similarly, many more variables can be added to the env file as per the environment. 

    For next steps, check out our blog posts about what is Node_ENV production and how to get it on windows? 

    Unlock the power of Python programming with our unique certification course. Learn Python programming and earn a certificate in just a few weeks. Start your journey today!

    Conclusion 

    This article concentrates on understanding the use of environment variables in a node application and the convenience that it brings when included in a .env file to define the configuration values related to an environment without managing them as a part of your operating system or adding them via the terminal every time you need to run a script.

    These are just some of the things you can do with environment variables and all the tools that exist. Now that you’ve learned a bit more about environment variables in Node.js, it's high time to try out KnowledgeHut’s Node.js full course to understand how to utilize this in real projects. 

    Frequently Asked Questions (FAQs)

    1What is the meaning of .env in Node.js?

    The env files or the environment files provide a popular solution for setting up the environment variables, particularly in Node.js. Platforms like Heroku, for example, use .env files as recommended best practices. 

    2How can I see node environment variables?

    If you want to take a look at the node's environment variables, you can run the Node.js REPL with “node” in your command line and then type: 

    console.log(process.env); 

    It will output all environment variables that this Node.js process can pick up. 

    Now that we have accessed the process.env object by logging it onto the console, we can also similarly list the default environment variables of our application. To access a specific variable, access it like you would access any property of an object: 

    EG: 

    console.log('The value of PORT is:', process.env.PORT); 
    3How can I set environment variables? 

    You can set the environment variable through process global variable as follows:  

    process. env['NODE_ENV'] = 'production';  

    or 

    You can add the same in the .env file of your project and then access it via the dotenv package in your codebase. 

    4What do you mean by process environment?

    In Node.js, process.env is a global variable injected during runtime. It is a view of the state of the system environment variables. When we set an environment variable, it gets loaded into the process. 

    If you want to take a look at this object, run the Node.js REPL with “node” in your command line and then type: 

    console.log(process.env); 

    This code will output all environment variables that this Node.js process can pick up. 

    Profile

    Nikhilesh Pandey

    Author

    "Experienced Lead Developer oriented towards problem-solving and analyzing impacts, both technically and functionally, Enjoy's working with web technologies with a strong focus on quality code and robust system architecture."

    Share This Article
    Ready to Master the Skills that Drive Your Career?

    Avail your free 1:1 mentorship session.

    Select
    Your Message (Optional)

    Upcoming Web Development Batches & Dates

    NameDateFeeKnow more
    Course advisor icon
    Course Advisor
    Whatsapp/Chat icon