乐闻世界logo
搜索文章和话题

How do you load environment variables from .env and .env.local with dotenv?

1个答案

1

In modern application development, using environment variables to store sensitive information and application configuration is a very common practice. dotenv is a widely adopted library that helps developers load environment variables from .env files in Node.js projects. When it comes to loading environment variables from .env and .env.local files, this library also works effectively. Here are the detailed steps and examples:

Installing dotenv

First, you need to add the dotenv library to your project. This can be done by running the following command:

bash
npm install dotenv

Creating .env and .env.local Files

In the root directory of your project, create two files: .env and .env.local. Typically, the .env file stores common configurations for all environments, while .env.local is used for configurations specific to local development. For example:

.env file content:

shell
DB_HOST=localhost DB_USER=root DB_PASS=s1mpl3

.env.local file content:

shell
DB_PASS=localpassword API_KEY=abcdef12345

Configuring dotenv

To load environment variables from these files, configure dotenv at your application's entry point (e.g., index.js or app.js). The config method of dotenv facilitates this task. You can specify multiple paths by passing a configuration object, as shown below:

javascript
require('dotenv').config({ path: '.env' }); require('dotenv').config({ path: '.env.local' });

Note that the order of paths is critical. Since dotenv adds later-loaded environment variables to process.env, and later-loaded variables override earlier ones, you should load .env first, then .env.local, to ensure that .env.local variables override those in .env.

Using Environment Variables

After configuration, you can access these variables in your application through process.env. For example, you can retrieve the database password and API key as follows:

javascript
const dbPassword = process.env.DB_PASS; const apiKey = process.env.API_KEY; console.log(`Database password is: ${dbPassword}`); console.log(`API Key is: ${apiKey}`);

Conclusion

By implementing this approach, you can flexibly load environment variables from different .env files, ensuring appropriate application configuration across various development environments while safeguarding sensitive information from being hardcoded in the code. This method is particularly well-suited for managing configuration differences between different development environments.

2024年7月22日 14:20 回复

你的答案