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:
bashnpm 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:
shellDB_HOST=localhost DB_USER=root DB_PASS=s1mpl3
.env.local file content:
shellDB_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:
javascriptrequire('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:
javascriptconst 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.