# How to read environment variables in Node.js

In Node.js, you can read environmental variables using the `process.env` object. This object provides access to the user environment, including environment variables. Here's a simple example of how you can read environmental variables in Node.js:

```jsx
// Accessing a specific environment variable
const apiKey = process.env.API_KEY;

if (apiKey) {
  console.log('API Key:', apiKey);
} else {
  console.error('API Key not found in environmental variables.');
}
```

When running your Node.js application, you can set environmental variables in the terminal or script before starting the application. For example:

```bash
# Setting an environmental variable in Linux/macOS
export API_KEY=your_api_key

# Setting an environmental variable in Windows (PowerShell)
$env:API_KEY = "your_api_key"
```

Then, when you run your Node.js script, it can access the environmental variable using `process.env.API_KEY`.

Keep in mind the following:

1. Security Considerations:
    - Avoid hardcoding sensitive information directly in your code. Instead, use environmental variables to store sensitive data like API keys, database passwords, etc.
    - Be cautious about exposing sensitive information unintentionally.
2. Default Values:
    - It's a good practice to provide default values or check if the environmental variable exists before using it to avoid potential issues.
3. Environment-specific Configuration:
    - Environmental variables are useful for managing configuration settings in different environments (development, testing, production, etc.).
4. External Configuration:
    - Tools like `dotenv` can be used to load environmental variables from a `.env` file during development. Install it using `npm install dotenv`, and then include the following line at the beginning of your script:
        
        ```jsx
        require('dotenv').config();
        ```
        
        Create a `.env` file in your project directory with key-value pairs:
        
        ```
        API_KEY=your_api_key
        ```
        
        Now, you can access these variables using `process.env` as usual.
        

Remember to handle environmental variables with care, especially when dealing with sensitive information, and follow security best practices.