Environment variables in Node.js
Node.js is a popular runtime environment that allows you to run JavaScript on the server-side. It provides a way to access environment variables, which are global variables that are available to all Node.js processes.
Why use environment variables?
Environment variables are often used to store configuration settings for your Node.js applications. This can include sensitive information such as API keys, database connection strings, or any other environment-specific settings. By using environment variables, you can keep this information separate from your code and easily change it as needed, without having to modify your application’s source code.
Accessing environment variables in Node.js
In Node.js, you can access environment variables using the process.env
object. This object contains key-value pairs of all the environment variables that are set for the current process. For example, if you have an environment variable called DB_HOST
, you can access it like this:
const dbHost = process.env.DB_HOST;
console.log('Database host:', dbHost);
You can also set default values for environment variables in case they are not defined. For example:
const port = process.env.PORT || 3000;
console.log('Server running on port', port);
Setting environment variables
Environment variables can be set in different ways depending on your operating system and deployment environment. In a Unix-based system, you can set environment variables using the export
command. For example:
export DB_HOST=127.0.0.1
In Windows, you can set environment variables using the set
command. For example:
set DB_HOST=127.0.0.1
Using environment variables in Node.js applications
Once you have set your environment variables, you can use them in your Node.js applications as needed. It’s important to handle them securely, especially when dealing with sensitive information. Avoid hardcoding any sensitive data into your code and consider using a package like dotenv
to load environment variables from a .env
file.
By using environment variables in your Node.js applications, you can easily manage configuration settings and keep sensitive information secure, making your applications more flexible and easier to deploy.