Introduction:
Node.js 20.6.0 introduced built-in support for .env files, which means you no longer need to rely on external packages like dotenv to handle your environment variables. This is a welcome change, as it makes it easier to manage environment variables in Node.js applications.
Body:
To use the built-in support for .env files, you first need to create a .env file in the root directory of your project. In this file, you can define your environment variables, each with its corresponding value. For example:
PORT=8080
DB_HOST=localhost
DB_USERNAME=root
DB_PASSWORD=password
Once you have created the .env file, you can load the environment variables from it using the process.env object. For example:
const port = process.env.PORT;
const dbHost = process.env.DB_HOST;
const dbUsername = process.env.DB_USERNAME;
You can also use the require('dotenv').config() method to load the environment variables from the .env file. However, this is not necessary in Node.js 20.6.0, as the built-in support will take precedence.
const dbPassword = process.env.DB_PASSWORD;
Conclusion:
The built-in support for .env files in Node.js 20.6.0 is a welcome change that makes it easier to manage environment variables in Node.js applications. If you are using Node.js 20.6.0 or later, I encourage you to start using the built-in support for .env files.
Call to action:
If you have any questions about using the built-in support for .env files in Node.js, please leave a comment below. I would be happy to help.
Happy coding