Blog post 3 min read

Stop using dotenv in Node.js v20.6.0+

Published on
Authors
Blog image

Horray, Node.js v20.6.0 is finally here!

I’m excited to say that, with this release, we now have built-in support for the .env file. This means that you can finally stop using the dotenv package to load in environment variables from .env files. In this short article, I demonstrate how we can now access environment variables in a .env file in your Node.js application.

Setting up

Suppose you have a simple Express application in app.js :

import express from "express";
const app = express();
const PORT = 3000;

app.get("/", async (req, res) => {
  res.send(`Hello! My name is ${process.env.NAME}.`);
});

app.listen(PORT, async () => {
  console.log(`App listening on port ${port}`);
});

Now, create a file named .env at the root of the application next to the app.js file to store the environment variable:

NAME=Cinderella

Using Node.js v20.6.0

Now make sure that you have Node.js v20.6.0 — you can get it from the official download web page or by using NVM:

nvm install 20.6.0

Just make sure that when you run node -v , you see the output v20.6.0 or later.

Setting environment variables

Now, we can set all these environment variables for our application and start it up by using the new env-file flag included in the start command:

node --env-file=.env app.js

If you’re following the example, then now if you visit [http://localhost:3000](http://localhost:3000/), you should see the text: “Hello! My name is Cinderella.”

Closing thoughts

In the past, we used to rely on the dotenv module to load environment variables into our application from .env files. With the lastest Node.js v20.6.0 release, Node.js comes with native support for .env files and we no longer have to use the dotenv module.

Having read this article, you now know how to access the environment variables within your application by using the new env-file flag included your Node.js application start command.

Starting with Infisical is simple, fast, and free.
Full Infisical Logo

PRODUCT

Secret Management

Secret Scanning

Pricing

Security

RESOURCES

Blog

Infisical vs Vault

Careers

Hiring

Forum

Open Source Friends

LEGAL

Terms of Service

Privacy Policy

Subprocessors

Service Level Agreement

CONTACT

Team Email

Sales

Support