310

I'm trying to follow a tutorial on NodeJS. I don't think I missed anything but whenever I call the process.env.NODE_ENV the only value I get back is undefined. According to my research the default value should be development. How is this value dynamically set and where is it set initially?

3
  • 3
    to set NODE_ENV for heroku apps you can use: heroku config:set NODE_ENV="production" Commented Jun 17, 2014 at 23:09
  • 27
    Although the answers below will solve the problem temporarily by setting the environment variable, the bigger lesson here should be that you can never know whether any environment variable will be set... So write your code accordingly and test whether it's set and if so, to what. Don't make assumptions about it. Commented Dec 16, 2015 at 1:17
  • Does this answer your question? How to set NODE_ENV to production/development in OS X Commented Jan 4, 2021 at 11:45

26 Answers 26

310

process.env is a reference to your environment, so you have to set the variable there.

To set an environment variable in Windows:

SET NODE_ENV=development

on macOS / OS X or Linux:

export NODE_ENV=development
11
  • 11
    you might add that if NODE_ENV is not set the app behaves like in "development" mode
    – Rocco
    Commented Sep 21, 2013 at 20:53
  • 1
    For Linux, vi ~/.bash_profile, then insert NODE_ENV=development and save.
    – stonyau
    Commented Oct 12, 2014 at 3:41
  • 17
    In case anyone else struggles... there is a difference between "SET V = VAL" and "SET V=VAL". Spaces matter.
    – willem
    Commented Mar 14, 2016 at 6:39
  • 5
    Note that the module "cross-env" to do similar to the above, and it will work on both OSX and Windows: "cross-env NODE_ENV=development". You need to install cross-env first: "npm install cross-env --save". Have that in a script in your package.json and you're good to go on both platforms. Commented Jun 9, 2016 at 15:59
  • 13
    Didn't work for me. I executed export NODE_ENV=development on my Mac terminal before doing a react-native run-ios from the same terminal. When debugging, the value of process.env.NODE_ENV is undefined.
    – Ash
    Commented Jun 26, 2019 at 5:54
113

tips

in package.json:

"scripts": {
  "start": "set NODE_ENV=dev && node app.js"
 }

in app.js:

console.log(process.env.NODE_ENV) // dev
console.log(process.env.NODE_ENV === 'dev') // false
console.log(process.env.NODE_ENV.length) // 4 (including a space at the end) 

so, this may better:

"start": "set NODE_ENV=dev&& node app.js"

or

console.log(process.env.NODE_ENV.trim() === 'dev') // true
7
  • 3
    What you can do is this, so you don't have to trim: "start": "set NODE_ENV=dev&& node app.js" Commented Dec 19, 2018 at 15:56
  • 3
    Excellent observation, console.log(process.env.NODE_ENV.length) // 4 (including a space at the end)
    – gregn3
    Commented Jun 8, 2020 at 14:01
  • 4
    Using SET makes the start-up script limited to Windows.
    – Quanta
    Commented Sep 29, 2020 at 17:47
  • 3
    You can do this to solve the space issue: "start": "export NODE_ENV='dev' && ...". So put the env between two '.
    – erkage
    Commented Jul 11, 2021 at 8:46
  • 2
    NEVER hardcode windows-specific stuff inside package.json Commented Nov 24, 2021 at 15:23
73

For people using *nix (Linux, OS X, etc.), there's no reason to do it via a second export command, you can chain it as part of the invoking command:

NODE_ENV=development node server.js

Easier, no? :)

1
  • 6
    A package like cross-env will allow that to work on windows as well. Commented Sep 6, 2016 at 15:38
57

We ran into this problem when working with node on Windows.

Rather than requiring anyone who attempts to run the app to set these variables, we provided a fallback within the application.

var environment = process.env.NODE_ENV || 'development';

In a production environment, we would define it per the usual methods (SET/export).

4
  • 8
    This is the most pragmatic solution.
    – druskacik
    Commented Sep 14, 2019 at 15:39
  • What if the value of process.env.NODE_ENV is undefined and the user wants to change development to production in .env file?
    – Kiran RS
    Commented Mar 17, 2021 at 13:21
  • this works great when using typescript strictNullChecks Commented Sep 17, 2021 at 3:34
  • @KiranRS You environment should not be decided by your .env file. On the contrary, your environment decides which .env file to load (.env.testing, .env.prod, etc). So, if the user wants to run production, it should set process.env.NODE_ENV system-wise. Commented Jun 9, 2023 at 22:14
26

You can use the cross-env npm package. It will take care of trimming the environment variable, and will also make sure it works across different platforms.

In the project root, run:

npm install cross-env

Then in your package.json, under scripts, add:

"start": "cross-env NODE_ENV=dev node your-app-name.js"

Then in your terminal, at the project root, start your app by running:

npm start

The environment variable will then be available in your app as process.env.NODE_ENV, so you could do something like:

if (process.env.NODE_ENV === 'dev') {
  // Your dev-only logic goes here
}
5
  • 2
    I don't think this works. Tried it in my current project and NODE_ENV is still undefined. This might need some more config to work it seems. Commented May 5, 2019 at 9:46
  • 3
    npm install --save-dev cross-env
    – DalSoft
    Commented Feb 8, 2020 at 0:16
  • 1
    for me somehow the accepted answer was not working, but this <3 Commented Apr 6, 2021 at 13:20
  • 1
    for me it is not working either on local machine windows. NODE_ENV is still undefined
    – rendom
    Commented Sep 12, 2021 at 7:29
  • @rendom You still need to declare the value you want to set in the .env file. For example here you would want NODE_ENV="" in .env file and then it would be set with the value you assign it in the run script
    – hanku8
    Commented Nov 13, 2022 at 13:19
18

in package.json we have to config like below (works in Linux and Mac OS)

the important thing is "export NODE_ENV=production" after your build commands below is an example:

  "scripts": {
     "start": "export NODE_ENV=production && npm run build && npm run start-server",
     "dev": "export NODE_ENV=dev && npm run build && npm run start-server",
  } 
  • for dev environment, we have to hit "npm run dev" command

  • for a production environment, we have to hit "npm run start" command

2
  • When I do this I get the error: 'export' is not recognized as an internal or external command, operable program or batch file.
    – Casivio
    Commented Mar 3, 2021 at 19:15
  • @Casivio on Windows, use set instead of export. "scripts": { "start": "set NODE_ENV=production && npm run build && npm run start-server" }
    – cweave
    Commented Jan 2, 2022 at 6:08
15

In macOS for those who are using the express version 4.x.x and using the DOTENV plugin, need to use like this:

  1. After installing the plugin import like the following in the file where you init the application: require('dotenv').config({path: path.resolve(__dirname+'/.env')});

  2. In the root directory create a file '.env' and add the varaiable like:

    NODE_ENV=development or NODE_ENV = development

0
12

As early as possible in your application, require and configure dotenv.

require('dotenv').config()

2
  • This was it for me, I put this in my main.ts
    – xaphod
    Commented Apr 7, 2021 at 13:50
  • THIS. This is the solution. Don't stuff env variables in your package.json
    – Scott
    Commented Jan 9, 2022 at 0:51
10

Must be the first require in app.js

npm install dotenv

require("dotenv").config();
8

In UBUNTU use:

$ export NODE_ENV=test

1
  • What indicated by @gilbert-flamino worked for me. Just to be more explicit. On Windows: "dev": "set NODE_ENV=development&& npx nodemon bin/www", On Ubuntu: "dev": "export NODE_ENV=development&& npx nodemon bin/www",
    – dixoen
    Commented Jun 21, 2022 at 15:40
6

install dotenv module ( npm i dotenv --save )

require('dotenv').config() //write inside the file where you will use the variable

console.log(process.env.NODE_ENV) // returns value stored in .env file

2

In my case, I have a node app. The way I have structured it is that I have client folder and server folder. I had my .env file inline with these two folder. My server file needs the .env file. It was returning undefined because it did not live inside the server file. It was an oversight.

App
-client
-server
-.env

Instead I moved .env inside server file like so:

App
-client
-server
 |-.env <---here
 |-package.json
 |-and the rest of the server files...

(before this - ofcourse have the dotenv npm package installed and follow its doc)
1

It is due to OS

In your package.json, make sure to have your scripts(Where app.js is your main js file to be executed & NODE_ENV is declared in a .env file).Eg:

"scripts": {
    "start": "node app.js",
    "dev": "nodemon server.js",
    "prod": "NODE_ENV=production & nodemon app.js"
  }

For windows

Also set up your .env file variable having NODE_ENV=development

If your .env file is in a folder for eg.config folder make sure to specify in app.js(your main js file)

const dotenv = require('dotenv'); dotenv.config({ path: './config/config.env' });

1

You can use the dotenv package from npm, here is the link: https://www.npmjs.com/package/dotenv

Which allows you to place all your configuration in a .env file

1
  • 1
    Looks like envalid no longer ships with dotenv so you now need to manually install / call this before you invoke envalid's cleanEnv(). This caught me out so leaving this here for others
    – Stretch0
    Commented Sep 20, 2021 at 11:23
0

If you faced this probem in React, you need [email protected] and higher. Also for other environment variables than NODE_ENV to work in React, they need to be prefixed with REACT_APP_.

0

For me, the issue was that I was using the pkg library to turn my app into an executable binary. In that case, the accepted solutions didn't work. However, using the following code solved my problem:

const NODE_ENV = (<any>process).pkg ? 'production' : process.env.NODE_ENV;

I found this solution here on GitHub.

0

In Electron Js

"scripts": {
    "start": "NODE_ENV=development electron index.js",
},
0

If you define any function with the name process then that may also cause this issue.

0

Defining process.env.NODE_ENV in package.json for Windows/Mac/Linux:

Here's what worked for me on my Mac (MacBook Pro 2019, 16 inch, Big Sur):

"scripts": {
    "build": "export NODE_ENV=prod || set NODE_ENV=prod&& npx eslint . && node --experimental-json-modules ./backend/app.js && gulp",
},

Using the export NODE_ENV=prod || set NODE_ENV=prod&& string may work in Windows and Linux but I haven't tested that.

If someone could confirm that would be great.

Unfortunately using the cross-env npm package did NOT work for me at all in my package.json file and I spend a long time on my Mac trying to make this work.

0

I also faced this issue. I moved .env file to the root folder (not the project folder, a level higher) and it worked out.

Check it. it might help you as well

0

Well, this answer could help you and it works with these stack, Node.js with Next.js and tRPC.

Steps:

  1. You have to install dotenv package to access the .env data through your process.env object. So if you are using npm you have to type: npm install dotenv
  2. Then, you have to find the folder where is located your environment variables validation, it usually have a validator library like Zod, the file in this folder could have the extension .js or .mjs. Here you have to add this code at the beginning:
// eslint-disable-next-line @typescript-eslint/no-var-requires
require('dotenv').config();
0

I was using the dotenv as follows

import express from "express";
import dotenv from "dotenv";

const app = express();
const port = process.env.PORT;
 
dotenv.config(); 

but the correct way of using is

import express from "express";
import dotenv from "dotenv";
dotenv.config(); 
const app = express();
const port = process.env.PORT;

it should be at top of any variable i

0

If you are running command in PowerShell, try this:

$env:NODE_ENV = "development"
nodemon(npm) server.js

If you are running command Unix-like shells (e.g., Bash), try this:

NODE_ENV=development nodemon(npm) server.js
0

in package.json

"scripts": {
   "start": "nodemon server.js",
   "start:prod": "NODE_ENV=production nodemon server.js"
 },

in root directory / create file .env: and add the following.

NODE_ENV=development
PORT=3000

in app.js file add the following

// Express app setup
const express = require("express");
const morgan = require("morgan"); // HTTP request logger middleware for node.js.
const app = express();
app.use(express.json());

// Will not run in production
if (process.env.NODE_ENV === "development") app.use(morgan("dev"));

// Test route
app.get("/", (req, res) => {
  res.status(200).json({ status: "Success", message: "Request Recieved" });
});

in server.js

const dotenv = require("dotenv"); //  Loads environment variables from .env file
dotenv.config({ path: ".env" });
const app = require("./app");
// init server
const PORT = process.env.PORT || 8000;
app.listen(PORT, () => {
  console.log(`Server is running on port: http://localhost:${PORT}`);
});

Run Command: npm start Hit route: http://localhost:3000

0

Perhaps someone have the same issue as I do. When using WSL and running NODE_ENV=xxx && node xx.js, because WSL can call Windows programs by default, the node program might be the Windows version of Node.js. It reads Windows environment variables, while NODE_ENV=xxx runs in the WSL bash, which can lead to undefined values!

You can edit /etc/wsl.conf and restart WSL to avoid this issue:

[interop]
# disable
enabled = false
# or do not add Windows path
appendWindowsPath = false

-3

You can also set it by code, for example:

process.env.NODE_ENV = 'test';

5
  • 81
    I STRONGLY discourage anyone from ever changing the environment identifier in application logic. You never want the application to suddenly think it is something else than it really is. This should only ever be changed on system-level, as many of the other answers suggest.
    – Kafoso
    Commented Jul 7, 2015 at 13:00
  • 7
    You might want to read about 12 factor apps: 12factor.net/config. This code would be a violation of that. There are good reasons to keep your config separate from your code.
    – jcollum
    Commented Jul 28, 2017 at 16:00
  • 2
    It might be useful only for automated testing, but even then it could be abstracted and injected into your main code, instead of being read directly from env. Commented Nov 21, 2018 at 18:21
  • 1
    Let's not downvote this answer so much that the informative comment by @Kafoso gets diminished. Or add this information to some well-voted answer. Commented Jun 17, 2020 at 9:56
  • Well, what if someone packs a web application with webpack and runs it in nginx?
    – Mario Eis
    Commented Sep 24, 2022 at 16:12

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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