Read environment variables in Node.js
Environment variables are a useful way to store configuration settings for your Node.js applications. They allow you to separate sensitive information, such as API keys or database credentials, from your codebase and provide a flexible way to configure your application across different environments.
In this article, we will explore different methods to read environment variables in Node.js.
1. Using process.env
The most common way to read environment variables in Node.js is by using the process.env
object. This object provides access to all the environment variables defined on the system.
To read an environment variable, simply access it as a property of the process.env
object. For example, to read the value of an environment variable named API_KEY
:
const apiKey = process.env.API_KEY;
If the environment variable is not defined, the value will be undefined
. To provide a default value, you can use the logical OR operator:
const apiKey = process.env.API_KEY || 'default-value';
2. Using the dotenv package
The dotenv package is a popular choice for managing environment variables in Node.js applications. It allows you to store environment variables in a .env
file and loads them into the process.env
object.
To use the dotenv package, start by installing it in your project:
npm install dotenv
Create a .env
file in the root of your project and define your environment variables:
API_KEY=your-api-key
DB_HOST=localhost
DB_PORT=5432
In your Node.js application, require the dotenv package and call the config
method:
require('dotenv').config();
After calling config
, the environment variables defined in the .env
file will be available in the process.env
object.
3. Using environment-specific configuration files
If you have different configuration settings for different environments (e.g., development, production), you can use environment-specific configuration files.
Create separate configuration files for each environment, such as config.development.js
and config.production.js
. In these files, define the environment-specific variables:
// config.development.js
module.exports = {
apiKey: 'development-api-key',
dbHost: 'localhost',
dbPort: 5432
};
// config.production.js
module.exports = {
apiKey: 'production-api-key',
dbHost: 'production-db-host',
dbPort: 5432
};
In your Node.js application, require the appropriate configuration file based on the current environment:
const config = require(`./config.${process.env.NODE_ENV || 'development'}.js`);
You can then access the environment variables as properties of the config
object:
const apiKey = config.apiKey;
Make sure to set the NODE_ENV
environment variable to the desired environment when running your application.
These are some of the common methods to read environment variables in Node.js. Choose the method that best suits your application’s needs and security requirements.
Happy coding!
Leave a Reply