In Node.js, you can use environment variables to configure and parameterize your applications. Environment variables are values that are set outside of the application and can be accessed within your Node.js code. They are often used to store configuration settings, API keys, database connection strings, and other sensitive information.
Here's how you can use environment variables in Node.js:
Before running your Node.js application, you need to set the environment variables. This can be done in various ways, depending on your operating system.
bashexport VARIABLE_NAME=value
cmdset VARIABLE_NAME=value
You can access environment variables in your Node.js code using the process.env
object.
javascript// Example: Accessing an environment variable named DATABASE_URL
const databaseUrl = process.env.DATABASE_URL;
// Use the variable in your code
console.log(`Database URL: ${databaseUrl}`);
To organize your environment variables and configuration settings, you can create a separate module to handle the configuration. This module can export an object with all the necessary configuration values.
javascript// config.js
module.exports = {
databaseUrl: process.env.DATABASE_URL,
apiKey: process.env.API_KEY,
// Add other configuration variables here
};
In your main application file:
javascript// app.js
const config = require('./config');
console.log(`Database URL: ${config.databaseUrl}`);
console.log(`API Key: ${config.apiKey}`);
You can use the dotenv
package to load environment variables from a .env
file. Install the package using:
bashnpm install dotenv
Create a .env
file in your project's root and add your variables:
bashDATABASE_URL=mongodb://localhost:27017/mydatabase API_KEY=your_api_key
In your application, require and configure dotenv
at the beginning:
javascript// app.js
require('dotenv').config();
const databaseUrl = process.env.DATABASE_URL;
const apiKey = process.env.API_KEY;
console.log(`Database URL: ${databaseUrl}`);
console.log(`API Key: ${apiKey}`);
Remember to add the .env
file to your .gitignore
to avoid committing sensitive information.
By following these steps, you can effectively use environment variables in your Node.js applications to manage configuration settings and other runtime parameters.