How to use environment variables in Node.js



Image not found!!

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:

1. Set Environment Variables:

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.

On Unix/Linux/Mac:

bash
export VARIABLE_NAME=value

On Windows:

cmd
set VARIABLE_NAME=value

2. Access Environment Variables in Node.js:

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}`);

3. Use a Module for Configuration:

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}`);

4. Use a Package for Dotenv Files:

You can use the dotenv package to load environment variables from a .env file. Install the package using:

bash
npm install dotenv

Create a .env file in your project's root and add your variables:

bash
DATABASE_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.

Note:

  • Be cautious when handling sensitive information with environment variables, and never expose them in your codebase or public repositories.
  • Always validate and sanitize environment variables before using them in your application.

By following these steps, you can effectively use environment variables in your Node.js applications to manage configuration settings and other runtime parameters.