How do you set an environment variable in Node.js?

Setting Environment Variables in Node.js

Setting environment variables in Node.js is crucial when you need to inject server configurations into your application, hide sensitive information like database passwords, or even set different settings between your development and production environment.

The correct way to set an environment variable in Node.js is by using the process.env object. This is a global object injected by Node.js at runtime on your application, and it represents the state of the system environment your application is in when it starts.

To set an environment variable, you can simply give the process.env object a new property. For instance, if we want to set a variable called VAR_NAME, we would do the following.

process.env.VAR_NAME = 'value';

Now, VAR_NAME is available anywhere in your application as long as your Node.js server is running.

While this is a straightforward and effective way to set environment variables, keep in mind that they will only be available for the current process. If you stop and then restart your Node.js server, the variables you set will be wiped out because each time a process starts, it gets its own set of environment variables.

For persistent environment variables, which you usually need for things like database connection information, you would normally use a .env file with a package like dotenv to load the values into process.env when your application starts.

Lastly, it's worth noting that keeping sensitive information in your code is generally a bad practice. Instead, these values should be stored in environment variable. This adds a layer of security as no sensitive data is exposed in your codebase. Providing different values for different environments (development, testing, production) becomes manageable and efficient with this technique.

Other options like set VAR_NAME='value'; and env.set('VAR_NAME', 'value'); are not valid methods in Node.js. These could lead to errors in your code. Thus, always stick with process.env for setting environment variables in your Node.js applications.

Do you find this helpful?