Get Even More Visitors To Your Blog, Upgrade To A Business Listing >>

Environment Variables in Environment Variables in NodeJs: The complete Guide

Posted on Oct 6 • Originally published at deadsimplechat.com In this article we are going to cover environment Variables also known as env variables. These are basically key-value pair of data set that is stored in the operating system levelIn this article we will learn about environment variables in NodeJs with examplesEnvironment variables are a key-value pair data set that are avaiable at the operating system level. These data set are available in all major operating system command line shells Windows, Mac and LinuxIn this project we are going to assume the followingThese are different methods of installing NodeJS on your machine. You can go to the node official website and download a version from thereLet us consider installing nodejs in a linux operating system preferably ubuntuStep 1: Open your terminalStep 2: Use curl or wget script below to install nvm using the nvm git repository. run the script to install the nvmStep 3: Close and re-open your terminal and run the following to apply the scriptStep 4: Confirm InstallationYou can confirm that NVM has been installed on your system by running the following command*Step 5 : * Installing Nodetype the below command to install the latest version of nodeorStep 6 Setting the default versionyou can set a default version of node to be used across your system by using the following commandStep 6: Checking if node is installedyou can type the below command to check if the node is installed on your systemNow, that we have installed the node on our machine. Let us create a new project where we will be using the env variablecreate a new directory and name it env-demo and cd into the directoryNow, that we have created the folder and cd into it. Type the below command to initialize a new project and fill out the fields as you see fit.this will create a package.json file for you that looks something like this:Step 1: Install the dotenv packageNow that you have initialized the project in the above section and created a package.json file. In your terminal type the below command to install the node dotenv package that is used to create env filesThis will install the dotenv package and save it as a dependency in your package.json file. that should look something like thisIn your root folder create an index.js file and then open your terminal and type the below command to install express js.This installs expressjs and saves it as a dependency in your package.json file, your package.json looks like thisand your project structure looks like thisNow, open your index.js file and type the below command to start a simple web server.run the code withand go to localhost://4000 to get the hello worldNow that we have the server running let us read the .env file that we created in the previous step and load the port details from the .env fileOpen the index.js file and require the dotenv library therenow, you can access the .env file using the process.env. Let us use the process.env to access the port number in our index.js fileNow let us restart the server and go to localhost://3000 . Instead of running at 4000 our server is now running on port 3000 which it took from the .env fileyou can also see this in the consoleYou have now successfully created and saved the env file on your machineAs another example you can access the DATABASE_URL like soHere are all the filesIn this section we are going to discuss about how env variables can be used in async tasks like calling an API or database operationsEnv variables are especially important in these tasks, because they can be used to store credentials and endpoints securelyAlso, these variables can be automated because these change between different environment such as development, staging and production.open your .env file and edit it like thisNext, install the axios library to make calls to the remote server likethis will install the axios and save it as a dependency in your package.json filethe package.json file should look something like thisNext use the axios to make calls to the jsonplaceholder website and log them to the consoleType this code in your index.js fileLet us look at another example, this time we are going to do database operations with env variablesstep 1 set up the env variablesOpen the .env file in your text editor and type the followingnext step is to install the pg library like sowrite the following code to connect to the database and use the .env credentials that we just createdwe are not integrating this example into our regular codebase because it is an outlier and will not be useful further down the line in our tutorialThere is more to env variable than just reading and storing them. With advanced env variable manipulation we are going to learn aboutEncoding is used for various purposes in environment variables. This could be used for security puposes. The most popular type of encoding is done using the base64validation is used to check whether the code is valid or not. for example the url that you are going to use is valid url or not etcor as in this example we are checking whether the port number is within the specified range or notenv variables are always on the type : string. If often you need to use other data types as well such as int or booleans. Here type conversion helpsInteger exampleBoolean exampleHere is an example combining all the advanced env manipulation available in the env variablesIn this section we are going to learn about secrets management and best practices with examples. Here are the steps that you can take to secure the env variable along with their examplesAlways ensure that the .env files are in the gitignore so they are never commited to the git repositoryalways hash the passwords, storing the passwords as plain text is a bad practice. You can use libraries like bcryt and others to hash the passwordsAs a security measure always encode the secrets, the secrets are usually base-64 encodedfor large projects you can consider centralized secrets management services like hashicorp vault, AWS secrets manager and othersThese offer advanced features like secret rotation, automated lease and rotation and audit logginghere is an example with node vaultAlways follow the principle of least privilege. The api which does not require write credentials should never be given write privileges.DeadSimpleChat is an Chat API providerIn this article we learned about env variable and how to use them in NodeJs the complete guideWe have covered the important topics related to env management in NodeJs and this should be enough for most of the use-cases for env variables management in Node js appsI hope you liked the article and thank you for readingTemplates let you quickly answer FAQs or store snippets for re-use.Thank you for reading. Are you sure you want to hide this comment? It will become hidden in your post, but will still be visible via the comment's permalink. Hide child comments as well Confirm For further actions, you may consider blocking this person and/or reporting abuse Jaimal Dullat - Oct 4 Akinnimi Stefan Emmanuel - Sep 30 sandra oghenesode - Sep 30 Cody Barker - Oct 3 Once suspended, alakkadshaw will not be able to comment or publish posts until their suspension is removed. Once unsuspended, alakkadshaw will be able to comment and publish posts again. Once unpublished, all posts by alakkadshaw will become hidden and only accessible to themselves. If alakkadshaw is not suspended, they can still re-publish their posts from their dashboard. Note: Once unpublished, this post will become invisible to the public and only accessible to alakkadshaw. They can still re-publish the post if they are not suspended. Thanks for keeping DEV Community safe. Here is what you can do to flag alakkadshaw: alakkadshaw consistently posts content that violates DEV Community's code of conduct because it is harassing, offensive or spammy. Unflagging alakkadshaw will restore default visibility to their posts. DEV Community — A constructive and inclusive social network for software developers. With you every step of your journey. Built on Forem — the open source software that powers DEV and other inclusive communities.Made with love and Ruby on Rails. DEV Community © 2016 - 2023. We're a place where coders share, stay up-to-date and grow their careers.



This post first appeared on VedVyas Articles, please read the originial post: here

Share the post

Environment Variables in Environment Variables in NodeJs: The complete Guide

×

Subscribe to Vedvyas Articles

Get updates delivered right to your inbox!

Thank you for your subscription

×