1566

Is there a way to read environment variables in Node.js code?

Like for example Python's os.environ['HOME'].

1

11 Answers 11

2193
process.env.ENV_VARIABLE

Where ENV_VARIABLE is the name of the variable you wish to access.

See Node.js docs for process.env.

10
  • 5
    Note that this will not be visible outside the node process and its subprocesses. E.g. it wouldn't be visible if you fire env in another shell window while the node process is running, nor in the same shell after the node process exits. Commented May 30, 2015 at 10:10
  • 28
    this also works for assigning variables. process.env.FOO = "foo"; works.
    – chicks
    Commented Sep 11, 2015 at 17:16
  • 44
    It's worth mentioning that this does not work in a React application. process.env is sanitized for security reasons. Only variables that begin with REACT_ENV_ are available. See: github.com/facebookincubator/create-react-app/blob/master/… Commented Jul 11, 2017 at 12:25
  • 17
    @MarkEdington I think it should be REACT_APP_
    – Mr. 14
    Commented Oct 19, 2017 at 15:35
  • 9
    @Mr.14 Right you are! It's REACT_APP_ not REACT_ENV_ Commented Oct 20, 2017 at 18:17
174

When using Node.js, you can retrieve environment variables by key from the process.env object:

for example

var mode   = process.env.NODE_ENV;
var apiKey = process.env.apiKey; // '42348901293989849243'

Here is the answer that will explain setting environment variables in node.js

4
  • 1
    what lib is required to use the above process.env method?
    – user_mda
    Commented Nov 1, 2015 at 19:27
  • 5
    @user_mda process.env is built into the node.js api. Commented Jan 20, 2016 at 1:47
  • Do I just set whatever I want on the process.env? why do people set it there as opposed to say, a config object that is require()'ed by node.js?
    – PDN
    Commented Apr 27, 2016 at 1:05
  • 4
    process.env gives you access to environment variable set at an operating system level. These can be set in various ways and will depend on where you are deploying your app For example, I often run my local app using NODE_ENV=development NODE_PATH=lib node server.js. Then process.env.NODE_PATH will return 'lib' Commented May 6, 2016 at 19:22
75

To retrieve environment variables in Node.JS you can use process.env.VARIABLE_NAME, but don't forget that assigning a property on process.env will implicitly convert the value to a string.

Avoid Boolean Logic

Even if your .env file defines a variable like SHOULD_SEND=false or SHOULD_SEND=0, the values will be converted to strings (“false” and “0” respectively) and not interpreted as booleans.

if (process.env.SHOULD_SEND) {
 mailer.send();
} else {
  console.log("this won't be reached with values like false and 0");
}

Instead, you should make explicit checks. I’ve found depending on the environment name goes a long way.

 db.connect({
  debug: process.env.NODE_ENV === 'development'
 });
2
  • 6
    I like to use 'yes' and 'no' for boolean env vars which must be explicitly checked. This avoids problems in many programming languages.
    – Dogweather
    Commented Aug 24, 2019 at 4:23
  • i like to be able to just say THIS_FEATURE=0 THAT_FEATURE=1 MAIL_TO='[email protected]' ./myapp
    – yellowsir
    Commented Nov 7, 2023 at 15:17
69

If you want to use a string key generated in your Node.js program, say, var v = 'HOME', you can use process.env[v].

Otherwise, process.env.VARNAME has to be hardcoded in your program.

1
  • 1
    Why do you have process.env['HOME']?
    – AlgoRythm
    Commented Sep 12, 2019 at 23:52
54

You can use the dotenv package to manage your environment variables per project:

  • Create a .env file under the project directory and put all of your variables there as VAR_NAME=value pairs.
  • Add require('dotenv').config(); to the top of your application entry file.

Now you can access your environment variables with process.env.VAR_NAME.

6
  • 19
    The dotenv package is useful, but the question asked is answered by reading process.env.ENV_VARIABLE. The dovenv package is all about loading setting from a file into the environment. Commented May 11, 2018 at 14:40
  • 1
    That's my point: manage and load env variables from env library.
    – Huy Vo
    Commented May 11, 2018 at 15:38
  • 1
    You can do the same in a non-node.js-specific way using the envdir utility. Commented Jun 23, 2018 at 18:23
  • 2
    This should be the answer. I was trying just with the process.env.MY_VAR and wouldn't work until I put the requre sentence. Thanks!! Commented Sep 26, 2021 at 20:42
  • 2
    As of node 20, experimental support for .env files has been baked in. You can use node --env-file=.env app.js to load environment variables from a .env file without using dotenv
    – Jarede
    Commented Jul 24 at 10:38
14

Using process.env. If Home is your env variable name then Try this:

const HOME = process.env.HOME;

Or

const { HOME } = process.env;
1
  • This doesn't directly address the hoisting issue with ES module imports but ensures your environment variables are set before any module logic runs. any import that reads envs errors
    – droid192
    Commented Mar 23 at 12:53
7

If you want to see all the Enviroment Variables on execution time just write in some nodejs file like server.js:

console.log(process.env);

-1

You first have to install the following library, ensuring you are in the root of your project:

npm i dotenv

Next create your .env file ensuring it is in the root of your project directory, here is an example of how to add a new variable within it:

# test variable
TESTVARIABLE='The test variable is working, value pulled from local!'

Next you would have to reference this module/library in the file you wish to use the environment variable e.g index.js, at the top of the file add the following code:

require("dotenv").config();

Now you can use/obtain the environment variable like so:

const message = process.env['TESTVARIABLE'];
1
-2

#Install the npm package dotenv

npm i dotenv

#Let's create a file .env

#Inside the .env file what I will do is that...

DATABASE_CONFIG={"host":"localhost","user":"root","password":"password123"}

BASE_URL=192.168.163.128;

#Now we will create the index.js file and it contains like the following ways...

require('dotenv').config();

// Example - 01: const url=process.env.BASE_URL; console.log("Base Url which is reading from env : ${url}")

//Example - 02:

const databaseConfigString = process.env.DATABASE_CONFIG; console.log(databaseConfigString);

let databaseConfig;

try { databaseConfig = JSON.parse(databaseConfigString); } catch (error) { console.error('Error parsing DATABASE_CONFIG:', error.message); }

if (databaseConfig) { console.log('Database Config:', databaseConfig); console.log('Host:', databaseConfig.host); console.log('User:', databaseConfig.user); console.log('Password:', databaseConfig.password); }

https://www.youtube.com/watch?v=gzCZ7l4pK3Y

-2

addon ensure envs are there before imports read them:

import { a} from "A.mjs";
console.log('env checks here')
import {b} from "B.mjs";

Despite log is before the import, nodejs will hoist all imports to the top and process respective modules. If any module eg B.mjs imports an env variable it will run before the env checks. thus one cannot use destructure { foo } = process.env but use a preinit script or dynamically import:

import myEnvCheck ... from ...;
myEnvCheck(["env1","env2"])

// now use a dynamic import which is run when reached / not hoisted; 
import("index.js").catch(...);

alternatively you can use import "dotenv/config"; in index.js and put the envs in a file instead

-9

Why not use them in the Users directory in the .bash_profile file, so you don't have to push any files with your variables to production?

4
  • 2
    The reason is because if you use .bash_profile then it will set it for that user's environment but if you are running multiple instances there then you have to set multiple env variables for that rather than having single one. E.g. if you set PORT variable then you have to make it like PORT_1, ... but if you use it through .env then you can use same code with .env file having different PORT number. Commented Jul 30, 2020 at 6:44
  • I don't see how you set a variable in a .bash_profile it's any different than a .env. It's SAFER when an app is hosted on a linux server in the .bash_profile with the same variables you would set on a .env file. You can still use different PORT number in a bash_profile based on conditions and again it's also safer. Commented Jul 6, 2022 at 0:29
  • .env is local, .bash_profile is global, with all the problems that entails (name clashes/no namespacing between projects, accidentally leaking important credentials, not cleaning up vars from old projects, etc). Also, this isn't portable between operating systems. By properly gitignoring .env, you won't push files with variables into production either.
    – ggorlen
    Commented Mar 25 at 23:19
  • .bash_profile is only global on the server where you host your project. .env file floats around with your project, even though it's hidden it's easier to accidentally commit it. You only update the environment variables on the server in deployment. I think all of you are thinking locally. Commented Aug 2 at 20:34

Not the answer you're looking for? Browse other questions tagged or ask your own question.