Learn how to work with environment variabes in Node.js

Can check environment variables:

  1. Start node REPL: node in terminal (before this check if node is installed by node -v)

  2. console.log(process.env)


const app = require('http').createServer((req, res) => res.send('Ahoy!'));
//in case of PORT, this particular var is undefined usually in all cloud providers, so this way works - gets 3000, or prefers if YOU define something in sys env
const PORT = process.env.PORT || 3000;

app.listen(PORT, () => {
  console.log(`Server is listening on port ${PORT}`);
});

The line const PORT = process.env.PORT || 3000 will take the value of the PORT if it’s available or default to listening to 3000 as a fallback port. Try running the code by saving it in a file like server.js and run:

node server.js The output should be a message saying, “Server is listening on port 3000.” Stop the server with Ctrl+C and restart it with the following command:

PORT=9999 node server.js The message should now say, “Server is listening on port 9999.” This means the PORT variable has been temporarily set in front of the node for this execution by PORT=9999.

How to set env variable

PORT=9999 node server.js

A similiar way to do this is:

process.env.MY_VARIABLE = 'ahoy';

both above are temporary ways

  • value is only set during the execution of this Node.js process and only available in child processes spawned by this process.
  • You should avoid overriding environment variables as much as possible and just initialize a configuration variable in your code, as shown in the PORT example (works for PORT because usually in case of PORT, this particular var is undefined usually in all cloud providers, so this way works - gets 3000, or prefers if YOU define something in sys env)

.env files

If you develop multiple Node.js projects on one computer, you might have overlapping environment variable names. For example, different messaging apps might need different Twilio Messaging Service SIDs, but both would be called TWILIO_MESSAGE_SERVICE_SID. A great way to achieve project-specific configuration is by using .env files. These files allow you to specify a variety of different environment variables and associated values.

Typically, you don’t want to checkin these files in source control. So when you create one, just add .env to your .gitignore file.

because you dont checkin these, you can search and get .env.example - it is shared by others as template file, refer it to write your .env file and and write your values.

How do we load the values from this file? The easiest way is by using an npm module called dotenv. Simply install the module via npm:

npm install dotenv --save

Afterward, add the following line to the very top of your entry file:

require('dotenv').config();

This code will automatically load the .env file in the root of your project and initialize the values, skipping any variables already preset. Be careful not to use .env files in your production environment, though. Instead, set the values directly on the respective host. So you might want to wrap your load statement in an if statement:

if (process.env.NODE_ENV !== 'production') {
  require('dotenv').config();
}

With this code, we’ll only load the .env file if the server isn’t already in production mode.

Let’s see this in action. Install dotenv in a directory, as shown above. Create an dotenv-example.js file in the same directory and place the following lines into it:

console.log('No value for FOO yet:', process.env.FOO);

if (process.env.NODE_ENV !== 'production') {
  require('dotenv').config();
}

console.log('Now the value for FOO is:', process.env.FOO);

Afterward, create a file called .env in the same directory with this content:

FOO=bar

Run the script:

node dotenv-example.js

The output should look like:

No value for FOO yet: undefined
Now the value for FOO is: bar

As you can see, the value was loaded and defined using dotenv. If you rerun the same command with NODE_ENV set to production, you’ll see that it’ll stay undefined.

NODE_ENV=production node dotenv-example.js

Now the output should be:

No value for FOO yet: undefined
Now the value for FOO is: undefined

If you don’t want to modify your actual code, you can also use Node’s -r argument to load dotenv when executing the script. Change your dotenv-example.js file to:

console.log('The value for FOO is:', process.env.FOO);

Now execute the file as you normally would:

node dotenv-example.js

The script should output that the current value for FOO is undefined. Now execute it with the appropriate flag to require dotenv:

node -r dotenv/config dotenv-example.js

The result is that FOO is now set to bar since the .env file has been loaded. If you want to learn more about dotenv, make sure to check out its documentation.

Environment Varialbes in Next.js

Next.js has built-in support for loading environment variables from .env.local into process.env.

See more on the official documentation: https://nextjs.org/docs/basic-features/environment-variables


Reference: This article by Dominik Kundel