Handling Environment Variables in Node.js without Dotenv is Now Possible!

Posted by



Introduction:
Environment variables are essential for specifying configuration settings in Node.js applications. Traditionally, developers have used packages like dotenv to manage and load environment variables into their applications. However, with the recent advancements in Node.js, you no longer need to rely on external packages like dotenv to handle environment variables effectively. In this tutorial, we will discuss how you can manage and use environment variables in Node.js without using dotenv.

Step 1: Using the process.env object
One of the simplest ways to access environment variables in Node.js is by using the process.env object. This object provides access to the environment variables set in your system. You can access an environment variable by specifying its name as a key in the process.env object. For example, to access the PORT environment variable, you can use process.env.PORT.

Step 2: Setting environment variables
To set environment variables in your Node.js application, you can do so directly in your system’s terminal before running your application. For example, if you want to set the PORT environment variable to 3000, you can do so using the following command:

PORT=3000 node app.js

This command sets the PORT environment variable to 3000 before running your Node.js application. You can set multiple environment variables in this way by separating them with spaces.

Step 3: Using a .env file
Although you don’t need dotenv to load environment variables from a .env file, you can still use one to manage your environment variables more conveniently. Instead of relying on dotenv, you can load the contents of a .env file into the process.env object using the fs module. Here’s an example of how you can do this:

const fs = require(‘fs’);

const dotenv = fs.readFileSync(‘.env’);
const envConfig = dotenv.split(‘n’);
envConfig.forEach((line) => {
const [key, value] = line.split(‘=’);
process.env[key] = value;
});

By using this code, you can load the contents of a .env file into the process.env object without relying on the dotenv package. This allows you to manage your environment variables more effectively without the need for external dependencies.

Step 4: Handling default values
In some cases, you may want to provide default values for your environment variables if they are not set. You can easily achieve this in Node.js by using the logical OR operator (||) to provide a default value if the environment variable is undefined. Here’s an example:

const PORT = process.env.PORT || 3000;

This code sets the PORT environment variable to 3000 if it is not already set. This can be useful for ensuring that your application behaves correctly even if certain environment variables are not configured.

Conclusion:
In conclusion, you don’t need to rely on external packages like dotenv to manage environment variables in Node.js anymore. By using the process.env object, setting environment variables in your system’s terminal, loading a .env file manually, and handling default values effectively, you can manage and use environment variables in your Node.js applications without the need for additional dependencies. This approach can help simplify your application’s configuration management and reduce dependencies, leading to more maintainable and efficient code.

0 0 votes
Article Rating

Leave a Reply

23 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
@booi_mangang
2 hours ago

If you are using ts, you would use ts-node. But I don't think ts-node support –watch or –watch-path

@michaelxaviercanonizado7931
2 hours ago

Thanks really helped! It also works with tsx when running a typescript file as a script in NextJS. Just add the same command: "tsx –env-file .env.local ${file path}"

@shubhampatil5935
2 hours ago

Use typescript. You will realize why dotenv is needed. Make videos if you have proven solution for all usecases, instead of just gaining attraction.

@111ramico
2 hours ago

NVM ls

@Jajatar
2 hours ago

This is great thanks! Question I don’t use .env file locally, I add whatever variable I need in windows environment variables (for security reasons, don’t want to commit api keys or whatever by mistake) and simply call them in my apps using dotenv (process.env.someVariable). Is there a way to access these with some other flag such as the one you showed —env-file .env ? Thanks again for video

@otakugamingyt
2 hours ago

Still going to stick onto dotenv unless env files can be mentioned in package.json to load envs

@PeterVatler-hv6nf
2 hours ago

Thank you for the tip! I used NVM but it always messed up the packages when I wanted to update the versions. I started using scoop package manager which is awesome, you can use as many node version as you want, it handles their packages very well, it's really easy to update the versions. At work I use 18, 20 LTS and the latest 21. I ended up installing other developer tools like Git by scoop because it's much more easier to update than using a windows installer.

@powertester5596
2 hours ago

A question: This works from command line (and thus in CI) but if I want to run a piece of code (say tests) from an IDE (such as VSCode), what would be required to load the env variables?

@Cap10Chunks
2 hours ago

Definitely going to ditch dotenv now. Have you tried out Remix?

@JohnMcclaned
2 hours ago

That cursor flashing animation is wild

@losVamonos
2 hours ago

Will an api key be exposed on the frontend using this method?

@iamadetoye
2 hours ago

Hello Devs here,

I just fixed an issue watching this video, might be of help to you too.

[
import dotenv from "dotenv"
dotenv.config()
] gave me a lot of headache when combined with "config" npm package and typescript. I even questioned my three years as a Dev only to find out after a week of being stuck and unable to deploy on this video from the dotenv documentation shared in the video that i should jave used

[
import "dotenv/config"
]

I felt like I just console.log("HELLO WORLD!!!") again😂😂😂

I have great relief right now. It's 12:39. I can still push before today ends. 😅

@neurabrain
2 hours ago

what is a font in vscode?

@nitishsingh925
2 hours ago

vary help full video now i am using like that in package.json file
"scripts": {

"start": " nodemon –env-file .env ./index.js"

},
any more way to do this then replay me any one 🙋‍♂🙋‍♂

@surendramaran
2 hours ago

not sure how can the production code will read the environment

@adarshchakraborty
2 hours ago

Can anyone tell me which theme & font is that

@amadikesullivan2962
2 hours ago

I have a question. Looking at the folder structure, the .env is inside the the src folder with index.js. When you using the terminal to load the dotevn, is it absolute to write the file that needs the environment variables it in each case ? Or is something to be loaded once and the whole app starts using it ?

@everyhandletaken
2 hours ago

Still surprises me that this was not in Node since v1, but still, good to finally have it.

Kinda wondering why the default behaviour isn't to pick up .env & the flag is only required if you want to using another filename.. i.e that is what dotenv has been doing all these years (though, I actually prefer env-var package, mostly)

@babyboie20
2 hours ago

Volta is also a really good nvm alternative.

@polioann
2 hours ago

whaat

23
0
Would love your thoughts, please comment.x
()
x