Set Environment Variable for Node.js Process

Shahriar Shovon

Supported OS

  • All


Share this post with your friends

In this post, I will show you, how to start node.js with environment variables.

Starting Node.js with Single Environment Variable

Let's say we have an environment variable API_KEY which has the value c3697d975a9a394828289efcfc328c02 Now we want to it to be available only on our node.js process. Doing that is pretty simple. Basically you start node.js with the environment variable. For example, run this command from the terminal/console, $ API_KEY=c3697d975a9a394828289efcfc328c02 node It opens up node.js REPL command line interface. Now we can print the variable with the following command: $ console.log(process.env.API_KEY) c3697d975a9a394828289efcfc328c02 We can execute a single command without going into Node.js REPL interface. $ API_KEY=c3697d975a9a394828289efcfc328c02 node -e 'console.log(process.env.API_KEY)' Remember this environment variable is only available to the node.js process you started with that variable.

Starting Node.js with Multiple Environment Variable

You can also include more than one variable at a time. KEY1=value1 KEY2=value2 KEY3=value3 node $ console.log(process.env.KEY1) value1 $ console.log(process.env.KEY2) value2 $ console.log(process.env.KEY3) value3

Set Environment Variable through .bashrc

You can also use .bashrc file to do that automatically. So you won't have to type in everything everytime. Open the .bashrc file: $ nano ~/.bashrc Add the following line to the .bashrc file. alias node='API_KEY=c3697d975a9a394828289efcfc328c02 USERNAME=shovon node' Once you're done, save it. then, open a new terminal and run the following $ node -e 'console.log(process.env.API_KEY)' c3697d975a9a394828289efcfc328c02 $ node -e 'console.log(process.env.USERNAME)' shovon