A Dive into Built-In .env File Support and Configuration

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

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:

.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

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

UpChecker

Reliable uptime monitoring and instant alerts for any website downtime.

  • Uptime Monitoring
  • Performance Monitoring
  • SSL Certificate Alerts
  • Domain Monitoring
  • DNS Checker
  • XML Sitemap Monitoring