DEV Community

Paulund
Paulund

Posted on • Originally published at paulund.co.uk

NodeJS ENV Support

Starting from Node.js v20.6.0, Node.js supports .env files for configuring environment variables.

Previously you would need to use a package called dotenv to load environment variables from a .env file into process.env.

This is now built into Node.js and you can use the --env-file flag to load a .env file into your application.

Format

The .env file should be in the root of your project and should contain the environment variables you want to load into your application.

Your configuration file should follow the INI file format, with each line containing a key-value pair for an environment variable.

PASSWORD=nodejs
Enter fullscreen mode Exit fullscreen mode

Usage

To initialize your Node.js application with predefined configurations, use the following CLI command: node --env-file=config.env index.js.

For example, you can access the following environment variable using process.env.PASSWORD when your application is initialized.

const password = process.env.PASSWORD
Enter fullscreen mode Exit fullscreen mode

.env.example

It's a good idea to include a .env.example file in your project, this will contain all the environment variables that are required for your application to run.

This will allow you to see what environment variables are required and what values they should be.

NODE_OPTIONS

In addition to environment variables, this change allows you to define your NODE_OPTIONS directly in the .env file, eliminating the need to include it in your package.json.

NODE_OPTIONS=--max-old-space-size=4096
Enter fullscreen mode Exit fullscreen mode

Conclusion

This is a great addition to Node.js and will make it easier to configure your application when you're running it locally.

Resources

  • Node.js v20.6.0
  • dotenv
  • dotenv-safe

Sentry blog image

How I fixed 20 seconds of lag for every user in just 20 minutes.

Our AI agent was running 10-20 seconds slower than it should, impacting both our own developers and our early adopters. See how I used Sentry Profiling to fix it in record time.

Read more

Top comments (1)

Collapse
 
dotenv profile image
Dotenv

it's amazing to see Node adopt .env! as it does we are turning our attention to better protecting your .env files. for example, we've created a precommit hook that prevents your .env files from being committed to code:

dotenvx.com/docs/features/precommit

The Most Contextual AI Development Assistant

Pieces.app image

Our centralized storage agent works on-device, unifying various developer tools to proactively capture and enrich useful materials, streamline collaboration, and solve complex problems through a contextual understanding of your unique workflow.

👥 Ideal for solo developers, teams, and cross-company projects

Learn more

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay